2013-03-05 29 views
1

我想我需要一個基本的PHP/MYSQL刷新,因爲沒有任何工作適合我。MySQL查詢拉一行並顯示結果的第一個字母

我的MYSQL表有兩行信息。

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

打印時,我得到的只有一個結果。 Array ([Name] => Banana [Description] => It's a lovely banana)。表格中肯定有兩個結果。這是爲什麼發生?

其次,這個循環只返回每個結果的第一個字母,我不知道爲什麼!

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

<?php } ?> 

我的大腦受到嚴重擾亂今天:(

+3

建設性的批判:你應該使用PDO作爲mysql_ *函數已正式折舊。 – 2013-03-05 17:30:28

+1

'mysql_fetch_assoc'抓取一行,不是全部。 – 2013-03-05 17:42:26

回答

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

<?php } ?> 
0

要回答你的第一個問題,這是因爲mysql_fetch_assoc()只得到數據的一行從結果集中在一個時間。通常情況下,當環是用來收集所有的結果是這樣的:

$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; 
} 

老實說,我不知道你爲什麼會只呼應了每場的第一個字母是否只是出現的方式。在屏幕上做你的HTML結構的一些問題?換句話說,如果你看HTML源代碼,它顯示是否正確?

+0

當我將它移動到while循環時,它停止了這樣做,但我仍然不知道爲什麼 – 2013-03-05 17:46:25

+0

@JacobRaccuia我真的不明白爲什麼你會遇到這個問題,因爲看起來你的'print_r()'顯示了完整的價值。在設置結果數組的位置和執行輸出的位置之間是否存在一些代碼? – 2013-03-05 17:49:44

+0

不,先生,我已經展示了我的代碼所做的一切。如果我有機會,我會重新創建併發布鏈接,但while循環做到了。 – 2013-03-05 20:25:52

1

MySQL已被棄用,您應該轉移到PDO或MySQLi。要回答你的問題對於後者,你應該使用準備好的語句(雖然在這種情況下,沒有多大意義,因爲你不需要消毒查詢)

$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 
} 
相關問題