由于某种原因,通过 PHP 运行的查询不会返回结果。我已经在 MySQL 命令行中尝试了这两个查询,它们在那里工作得很好。这是代码(澄清一下,mysql_connect.php 工作正常)。
<?php
error_reporting(-1);
// retrieve email from cookie
$email = $_COOKIE['email'];
// connect to mysql database
require('mysql_connect.php');
// get user_id by searching for the email it corresponds to
$id = mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email")or die('couldn\'t get id');
// get data by using the user_id in $id
$result = mysqli_query($dbc,"SELECT * FROM users WHERE user_id=$id")or die('couldn\'t get data');
//test if the query failed
if($result === FALSE) {
die(mysql_error());
echo("error");
}
// collect the array of results and print the ones required
while($row = mysql_fetch_array($result)) {
echo $row['first_name'];
}
?>
当我运行脚本时,我收到消息“无法获取 id”,但该查询在 MySQL 命令行和 PHPMyAdmin 中有效。
最佳答案
你的代码不会工作有两个原因 - $id
不会神奇地变成整数,而是一个 mysqli 结果。而 email 是一个字符串,所以应该用引号引起来。
但是...
为什么会是这样?
如果您想获取用户的所有数据,对于某些电子邮件,只需让您第二个查询通过电子邮件获取数据并删除第一个:
SELECT * FROM users WHERE email='$email';
并且不要忘记转义您的输入,因为它在 cookie 中。或者,按照建议使用准备好的语句。
关于PHP - 无法从数据库检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23247725/