在php中显示SQL查询结果

问题描述 投票:7回答:3

我试图在sql数据库中显示php的结果MySQL语句是正确的,并在phpMyAdmin中做我想要的但由于某种原因我的代码在网页中断

这是代码

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
echo [$result];

一般来说,我需要通过表id限制从min到max的随机数

php mysql random numbers generator
3个回答
9
投票

您需要从查询中获取的结果集的每一行中获取数据。你可以使用mysql_fetch_array()

// Process all rows
while($row = mysql_fetch_array($result)) {
    echo $row['column_name']; // Print a single column data
    echo print_r($row);       // Print the entire row data
}

将您的代码更改为:

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['fieldname']; 
}

6
投票

您需要执行while循环以从SQL查询中获取结果,如下所示:

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )    
FROM modul1open) ORDER BY idM1O LIMIT 1";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    // If you want to display all results from the query at once:
    print_r($row);

    // If you want to display the results one by one
    echo $row['column1'];
    echo $row['column2']; // etc..

}

另外,我强烈建议不要使用mysql_ *,因为它已被弃用。而是使用mysqliPDO扩展。你可以阅读更多有关here的信息。


2
投票

您不能使用mysql_query直接查看查询结果,它只会在mysql中激活查询。

要获得结果,您必须在脚本中添加一些内容

require_once('db.php');  
 $sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) ORDER BY idM1O LIMIT 1";

 $result = mysql_query($sql);
 //echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    print_r($row);
}

这会给你结果;

© www.soinside.com 2019 - 2024. All rights reserved.