gpt4 book ai didi

php- 无法从 mysql (mysqli) 获取结果

转载 作者:太空宇宙 更新时间:2023-11-03 12:22:05 26 4
gpt4 key购买 nike

我正在尝试为应用项目设置 API。

我有一个名为“users”的 mysql 表,我在其中添加了一行。

使用代码:

// Create connection
$mysqli = new mysqli("localhost","user", "pass", "db");

// Check connection
if($mysqli->connect_errno){

$result = "Failed to connect to MySQL: " . mysqli_connect_error();
print_r( json_encode($result) );
return false;

}

$row = $mysqli->query("SELECT * FROM users");
print_r( json_encode($row) );

我得到一个空结果,怎么回事? (连接不会抛出错误)

确切地说,我得到:

{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}

编辑:

得到ym原问题的答案,谢谢!

现在使用代码:

$row = $mysqli->query("SELECT * FROM users WHERE email = '".$email."'");
$result = $row->fetch_array();
print_r( json_encode($result) );

我得到结果:

{"0":"test","username":"test","1":"test@test.com","email":"test@test.com","2":"test","password":"test","3":"2013-10-18 22:22:53","date_registered":"2013-10-18 22:22:53","4":"1","id":"1"}

我想要的是这样的:

{"username":"test","password":"test","email":"test@test.com", ...etc }

我怎么得到它?

最佳答案

试试这个:

$result = $mysqli->query("SELECT * FROM users");
$row = $result->fetch_array(MYSQLI_ASSOC);
print json_encode($row); // json_encode returns a string...

为你的关联数组试试这个:

while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$rows[] = $row;
}
print json_encode($rows);

或者您可以尝试... $rows = $result->fetch_all(MYSQLI_ASSOC);

关于php- 无法从 mysql (mysqli) 获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19459572/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com