user3112318 user3112318 - 5 months ago 13
SQL Question

PHP, display mysql row in view

I'm having trouble displaying the sql below in the hph view file.

$query = mysqli_query($con, "SELECT TF.tf_ID AS QuestID, TF.Question AS Question FROM QuizQuestions quest, addTF TF WHERE quest.QuestID = TF.tf_ID AND quest.QuizID ='".$quizID."' AND quest.Type = 'tf'");
$rows = array();
while ($row = mysqli_fetch_assoc($query)) {
$rows[] = $row;
}
echo json_encode($rows);


This is the part of the php view that is supposed to display the sql. I know it is wrong but I don't know how to fix it. Any help is welcome.

<?php foreach($json as $tf) :?> <?php echo $tf['Question']; ?> <div class="row-fluid"><div class="span8">
<div class="btn view" id="view" style="width: 98%">
<p class="text-left" style="margin: 0;float: left;">
<input type ="hidden" value="tf" name="type">
<input type="checkbox" id="questID" value="<?php echo $tf['tf_ID'];?>" name="questID" class="questID" > <?php echo 'Question: '.$tf['Question']; ?> </input><br/>
<input type="hidden"> <?php echo 'Answer: '.$tf['Answer'] ; ?> </input><br/>
</div> </div> </div> <?php endforeach; ?>


I've used similar codes and they work. They problem is I do not know how to work with sql "AS". My apology in advance if this question was once asked and for the format.

Answer

There is no method called mysqli_fetch_assoc(). There is mysql_fetch_assoc() but not mysqli_fetch_assoc().

You can do this to get the rows:

$query = "SELECT TF.tf_ID AS QuestID, TF.Question AS Question FROM QuizQuestions quest, addTF TF WHERE quest.QuestID = TF.tf_ID AND quest.QuizID ='".$quizID."'  AND quest.Type = 'tf'";


$result = mysqli_query($con, $query);

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

If you are calling the query through an Ajax method and returning the data to JavaScript you should JSON encode. However, if you are just printing the rows with PHP there is no reason to JSON encode them.

To iterate the rows in PHP you can do:

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    echo '<div>' . $row['foo']; . '</div><div>' . $row['bar']; . '</div>';
}
Comments