【问题标题】:Null return from localhost php coding从 localhost php 编码返回 Null
【发布时间】:2017-11-05 19:14:48
【问题描述】:

我设置了我的本地主机,我已经准备好了所有相关文件。我在运行 sql 查询的地方运行 php,它返回 NULL 值。但它不应该。我通过浏览器访问链接的目录。

有人可以指出返回方向,为什么它返回 NULL?我运行了 SQL 查询,在我的 phpmyAdmin 上运行良好

<?php
header('Content-Type: application/json');
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'myusername');
define('DB_PASSWORD', 'Ihavenopassword');
define('DB_NAME', 'mytablename');
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if(!$mysqli){
    die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT playerid, score FROM score ORDER BY playerid");

//execute query
$result = $mysqli->query($query);


//loop through the returned data
$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$mysqli->close();

//now print the data
print json_encode($data);

【问题讨论】:

    标签: php sql localhost


    【解决方案1】:

    $result 不是您所期望的。您需要获取每个项目,例如 fetch_assoc:

    //loop through the returned data
    $data = array();
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    

    【讨论】:

    • 你好 u_mulder,奇怪的是我这边。它仍然返回 0 个结果。出现这种情况有什么可能的原因吗?
    • 已解决,谢谢!我不得不使用 if (mysqli_num_rows($result) > 0) { // 输出每一行的数据 while($row = mysqli_fetch_assoc($result)) {
    猜你喜欢
    • 2013-08-06
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多