J
J
jameson322018-08-05 02:04:11
PHP
jameson32, 2018-08-05 02:04:11

I can't figure out how to extract data from the database. Only one line is displayed, why?

Good time!
Here is the code:

<?php


$db->Query("SELECT * FROM fanswer WHERE question_id = '$id'  ORDER BY a_id DESC");

if($db->NumRows() > 0){

while($ans = $db->FetchArray()){

$logina =$ans["a_name"];
$db->Query("SELECT * FROM db_users WHERE user = '$logina'");
$ua = $db->FetchArray();
$ua1 = $ua["ava"];
 

?>

<table width="95%" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td><table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">



<tr>
<td width="25%" bgcolor="#F8F7F1"><strong><center>
    
    
 <?  


 if(empty($ua1)) {
echo '<center><img src="/noava.png"></center>';
}else{
echo '<center><img src="/'.$ua['ava'].'"></center>';
} 
?>
    
    <?php echo $ans["a_name"]; ?></center></strong></td>

<td width="75%" bgcolor="#F8F7F1"><?php echo $ans["a_answer"]; ?></td>
</tr>
<tr>
<td bgcolor="#F8F7F1"></td>

<td bgcolor="#F8F7F1" style="text-align:right;"><?php echo 'Добавлено '.$ans["a_datetime"].'' ?></td>
</tr>
</table></td>
</tr>
</table><br><? } } ?>

This code displays only one first line, but with data from the users table (avatar), but if you remove the lines:
$logina =$ans["a_name"];
$db->Query("SELECT * FROM db_users WHERE user = '$logina'");
$ua = $db->FetchArray();
$ua1 = $ua["ava"];

then it displays everything, but of course without the avatars that are registered in db_users
Please help me with advice, what am I doing wrong...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-08-05
@jameson32

You are using $db for two tasks at once - it is natural that the second query causes its result to overwrite the result of the first query.
What to do? There are three options - two stupid ones, and one correct one:

  1. After executing the first request, get all the data at once - throw them into a separate array, and go around this array in a loop
  2. Do not use $db to execute a query inside a loop - create a separate instance of the class responsible for working with the database for this
  3. Finally, the correct option is to get all the data in one query, for this you need to deal with such a thing as JOIN (just take it and google it - "sql join")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question