Reputation:
How do I use loop in select query? Query only fetch one Row, at a time, from Select Query. I want to fetch multiple rows In the Select Query but through a loop
Select ID
$id=$_REQUEST['id'];
function get_id($id){
$result1=mysql_query("select * from products where id='$id'")
or die("Id Problem"."<br/><br/>".mysql_error());
$results1= array();
$k=0; // add the new line
while($row1=mysql_fetch_assoc($result1)){
$results1[] = $row1['id'];
$k++;
}
return $results1;
}
Pid Array
$pid1=get_id($id);
<?php
$max1=count($pid1);
for($n=0; $n<$max1; $n++)
{?>
<input type="hidden" name="pid[]" value="<?php echo $pid1[$n]?>" />
<?php }?>
Pid Session
$_SESSION['pid']=$_POST['pid'];
I want fetch
Multiple Rows In Select Query But through Loop
<?php
$pid = join(',',$_SESSION['pid']);
$result=mysql_query("SELECT id AS wid FROM mywishlist
where pid='$pid'")
or die("Id Problem"."<br/><br/>".mysql_error());
$results= array();
$i=0; // add the new line
while($row=mysql_fetch_array($result)){
$results[$i] = $row['wid'];
$i++;
}
echo $results;
$max=count($results);
for($j=0; $j<$max; $j++)
{
?>
<input type="text" name="wid[]" value="<?php echo $results[$j]; ?>" />
<?php }?>
Upvotes: 0
Views: 2147
Reputation: 9293
You're doing some things the hard way, tracking and controlling things that would run fine on autopilot. For example - for loops require you to know the length while foreach loops just run 'til they're done.
Letting PHP take care of the array index by using [] instead of assigning the index will also save you some effort. And since each of your loops really only does one thing, they don't really need braces.
$result=mysql_query('SELECT id AS wid FROM mywishlist where pid="'.$pid.'"') or die();
$results= array();
while($row=mysql_fetch_array($result))
$results[]=$row['wid'];
foreach($results as $wid)
echo '<input type="text" name="wid[]" value="'.$wid.'" />';
Of course, you could eliminate one of these loops because they both essentially handle the same data...
$result=mysql_query('SELECT id AS wid FROM mywishlist where pid="'.$pid.'"') or die();
while($row=mysql_fetch_array($result))
echo '<input type="text" name="wid[]" value="'.$row['wid'].'" />';
Furthermore, reidentifying the key from id to wid doesn't make much sense. Since there is only 1 field in the result, why bother identifying it - we can just fetch the row.
$result=mysql_query('SELECT id FROM mywishlist where pid="'.$pid.'"') or die();
while($row=mysql_fetch_row($result))
echo '<input type="text" name="wid[]" value="'.$row[0].'" />';
Ooh, let's do it in 2 lines
$result=mysql_query('SELECT id FROM mywishlist where pid="'.$pid.'"') or die();
while($row=mysql_fetch_row($result)) echo '<input type="text" name="wid[]" value="'.$row[0].'" />';
Upvotes: 1