MySQL查询拉一行并显示结果的第一个字母
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 :(
我想我需要一个基本的PHP / MYSQL刷新,因为没有什么对我有用。 p>
我的MYSQL表有两行信息。 p>
$ results = mysql_query(“SELECT Name,Description FROM products”);
$ results = mysql_fetch_assoc( $ results);
print_r($ results);
code> pre>
打印时,我得到的只是一个结果。 Array([Name] =&gt; Banana [Description] =&gt;这是一个可爱的香蕉) code>。 表中肯定有两个结果。 为什么会发生这种情况? p>
其次,这个循环只返回每个结果的第一个字母,我不知道为什么! p>
foreach($结果为$ res){
?&gt;
名称:&lt;?php echo $ res ['Name']; ?&gt;&lt; br /&gt;
说明:&lt;?php echo $ res ['Description']; ?&gt;&lt; br /&gt;
&lt;?php}?&gt;
code> pre>
我的大脑今天严重受挫:( p> \ n div>
while($res = mysql_fetch_assoc($results)){
?>
Name : <?php echo $res['Name']; ?><br />
Description : <?php echo $res['Description']; ?><br />
<?php } ?>
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?
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
}