2015-08-13 47 views
0
#GET from Mysql 
$select = "SELECT content from content WHERE page = 'index';"; 
$result = mysql_query($select); 
$row = mysql_fetch_row($result); 

#Show in diferent places in my page 
<?PHP echo $row[0]; ?> 
<?PHP echo $row[1]; ?> 

我正在使用以上代碼,問題是: 它只顯示第一個結果。我錯了什麼?[PHP] [Mysql]選擇並顯示簡單

+2

RTFM:http://php.net/mysql_fetch_row該函數獲取** SINGLE **行數據。 –

+1

如果可以的話,你應該[停止使用'mysql_ *'函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。他們不再被維護,並[正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。瞭解[準備](http://en.wikipedia.org/wiki/Prepared_statement)[聲明](http://php.net/manual/en/pdo.prepared-statements.php),並考慮使用PDO ,[這真的不難](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+0

這是一個客戶端。我真的必須這樣做,否則我將不得不在他的所有頁面中使用準備好的語句 –

回答

0
$select = "SELECT content from content WHERE page = 'index';"; 
$result = mysql_query($select); 

//$row = mysql_fetch_row($result); 
// mysql_fetch_row() fetches ONLY ONE ROW 

// If you want to fetch them all, yes, you must use a loop. 
while ($row = mysql_fetch_row($result)) { 
    $rows[] = $row; 
} 
// So do this, get all the rows, and then you can use them in different places in your page 

// Show in diferent places in your page 
<?PHP echo $rows[0][0]; ?> 
<?PHP echo $rows[1][0]; ?> 
-2

這是更好地做到這一點在一個for循環 - 這樣,它會得到所有的結果每一次,而不是硬編碼的,只有兩個結果的情況下,等

<?php 
$select = "SELECT content from content WHERE page = 'index';"; 
$result = mysql_query($select); 
$rows = mysql_fetch_assoc($select); 

foreach ($rows as $row) { 
    echo $row['content']; // associative array with strings for keys 
} 
?> 

此外,你應該是出於安全原因使用mysqli

+0

我不能在不使用循環的情況下使用它嗎?回聲在頁面的不同部分 –

+0

只要變量處於範圍內,就可以在一個位置運行查詢並將打印循環放在任何需要的地方。 – Jeff