简体   繁体   中英

MySQL query pulling one row and displaying first letter of result

I think I need a basic PHP / MYSQL refresh, because nothing is working for me.

My MYSQL Table has two rows of information.

 $results = mysql_query("SELECT Name, Description FROM products");
 $results = mysql_fetch_assoc($results);
 print_r($results);

When printing this, all I get is one result. Array ( [Name] => Banana [Description] => It's a lovely banana ) . There are definitely two results in the table. Why is this happening?

Secondly, this loop only returns the first letter of each result, and I don't know why!

foreach($results as $res) {
?>
    Name : <?php echo $res['Name']; ?><br />
    Description : <?php echo $res['Description']; ?><br />

<?php } ?>

My brain is seriously scrambled today :(

while($res = mysql_fetch_assoc($results)){
?>
    Name : <?php echo $res['Name']; ?><br />
    Description : <?php echo $res['Description']; ?><br />

<?php } ?>

MySQL has been deprecated and you should either move to PDO or MySQLi. To answer your question for the latter, you should use a prepared statement (although in this case it doesn't matter much since you don't need to sanitize the query)

$connection = new mysqli('localhost','root','pw','db');// start mysqli connection
$results = $connection ->prepare('SELECT Name, Description FROM products');// create the statement you want to work with
(object)array('Name'=>'','Description'=>'');// set up the variables you want to put retrieved data in
$results ->bind_result($res ->Name, $res ->Description);// attach the variables to the prepared statement
while($results ->fetch()){// execute the prepared statement
    // perform actions with $res->Name and $res ->Description
}

To answer your first question, it is because mysql_fetch_assoc() only gets one row of data from the result set at a time. Typically, a while loop is used to gather all results like this:

$results = mysql_query("SELECT Name, Description FROM products");
$result_array = array(); // don't name this array the same as your result set ($results) or you will overwrite it.
while($row = mysql_fetch_assoc($results)) {
    $result_array[] = $row;
}

I honestly don't know why you would only be echoing out the first letter of each field. Does it just appear that way on screen do to some problem with your HTML construct? In other words if you look at the HTML source, is it shown correctly?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM