2015-08-13 45 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