-->

MySQL/PHP foreach still only displaying first in d

2019-08-24 01:37发布

问题:

I am querying results from a database, where more than one result should be queried. However, when I tried displaying the result of the query, only one result showed, so I tried to use a foreach function, but it's still not working. I'm beat, no idea what I'm doing wrong. Anyone have a good idea of what's going wrong?

Here's the MySQL query code:

<?php


    //Database Information 
    $dbhost = ""; 
    $dbname = ""; 
    $dbuser = ""; 
    $dbpass = ""; 

    //Connect to database 
    mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error()); 
    mysql_select_db($dbname) or die(mysql_error()); 

    $filename = $_GET['filename'];

$new_captions = mysql_query("SELECT * from captions where image = 'http://math.stanford.edu/inc/img/PalmDrive.png' ORDER BY idnum DESC LIMIT 5");
while($rows = mysql_fetch_array($new_captions)){
    $caption = $rows;
    }

?>

And here's the foreach:

<?php foreach($caption as $rows) {?>

<div id="set_caption" style="width:<?php echo $caption['width'];?>px; height:<?php echo $caption['height'];?>px; left:<?php echo $caption['posleft'];?>px; top:<?php echo $caption['postop'];?>px;"><?php echo $caption['text'];?></div>

<?php } ?>

回答1:

You have following mistakes.

  1. $caption is not declare before.
  2. use array_push or $caption[] = $rows; to make caption array.
  3. Use $row variable in the foreach.

    //Database Information 
    $dbhost = ""; 
    $dbname = ""; 
    $dbuser = ""; 
    $dbpass = ""; 
    
    //Connect to database 
    mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error()); 
    mysql_select_db($dbname) or die(mysql_error()); 
    
    $filename = $_GET['filename'];
    
    $new_captions = mysql_query("SELECT * from captions where image = 'http://math.stanford.edu/inc/img/PalmDrive.png' ORDER BY idnum DESC LIMIT 5");
    
    $caption = array();
    
    while($rows = mysql_fetch_array($new_captions)){
         $caption[] = $rows;
    }
    
    foreach($caption as $row) {        
    <div id="set_caption" 
         style="width:<?php echo $row['width'];?>px; 
                height:<?php echo $row['height'];?>px; 
                left:<?php echo $row['posleft'];?>px;  
                top:<?php echo $row['postop'];?>px;">
         <?php echo $row['text'];?>
    </div>        
    

    }



回答2:

I think $caption is an array, so your code should be like this

while($rows = mysql_fetch_array($new_captions)){
    $caption[] = $rows;
}

EDIT:

Your foreach loop is also wrong.

Your variable is $rows not $caption.

<div id="set_caption" style="width:<?php echo $rows['width'];?>px; height:<?php echo $rows['height'];?>px; left:<?php echo $rows['posleft'];?>px; top:<?php echo $rows['postop'];?>px;"><?php echo $rows['text'];?></div>

<?php } ?>