Reputation: 1
My code:
<?php
require_once('auth.php');
require_once('connection.php');
$value1 = $_POST['value1'];
$qry=mysql_query("SELECT * FROM table WHERE (`value1` LIKE '%".$value1."%')") or die(mysql_error());
if(mysql_num_rows($qry) > 0){
while ($result = mysql_fetch_array($qry)){
$value1 = $result['value1'];
$value2 = $result['value2'];
}}else{die ("can't find ".$value1."");}
?>
<br />
<table width="700" border="0">
<tr>
<td colspan="2" align="center"><strong>Info for <?php echo $value1; ?></strong></td>
</tr>
<tr>
<td width="100">Some text:</td>
<td width="590"><?php echo $value2;?></td>
</tr>
The code is working great when there is only one row with the same value of value1. If there are 2,3 or more rows with the same value for value1 the script displays only the values from the last row in my table found with the queried value. I want it to display separate tables with entries from all queried rows. I've searched online for help, but all I could find is how to retrieve the values from my database, nothing helpful for me
Upvotes: 0
Views: 2727
Reputation: 57002
you should move your html block to inside the while loop. try this
<br />
<table width="700" border="0">
<?php
if(mysql_num_rows($qry) > 0){
while ($result = mysql_fetch_array($qry)){
$value1 = $result['value1'];
$value2 = $result['value2'];
?>
<tr>
<td colspan="2" align="center"><strong>Info for <?php echo $value1; ?></strong></td>
</tr>
<tr>
<td width="100">Some text:</td>
<td width="590"><?php echo $value2;?></td>
</tr>
<?php
}}else{die ("can't find ".$value1."");}
?>
</table>
I moved the <table>
code to before the while loop, moved the table rows to inside the loop and the table close tag after the loop. this way you get all rows.
If you don't want to show the table at all if there is no rows you can move the <table ..>
and </table>
tags to inside the if
statement block.
Edit:
if(mysql_num_rows($qry) > 0){
?>
<br />
<table width="700" border="0">
<?php
while ($result = mysql_fetch_array($qry)){
$value1 = $result['value1'];
$value2 = $result['value2'];
?>
<tr>
<td colspan="2" align="center"><strong>Info for <?php echo $value1; ?></strong></td>
</tr>
<tr>
<td width="100">Some text:</td>
<td width="590"><?php echo $value2;?></td>
</tr>
<?php
}
echo '</table>';
}else{die ("can't find ".$value1."");}
?>
Upvotes: 1
Reputation: 1802
You're assigning values from the returned rows to $value1 and $value2. So each iteration of the loop replaces the last stored values in these variables.
This will effectively only give you the last row values found (last values assigned to the variables.)
You either need to push these values into a collection/array and re-loop through them to build your table, or put the table code in the initial loop.
Upvotes: 1