PHP中表中的所有值='s'错误

问题描述:

我有这个代码.

$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s',$username);
//$username = $_POST["username"];
$username ="netsgets";
$stmt->execute();
$stmt->store_result(); 
var_dump(stmt['likedFour']);

根据表UserData,likeFour应该等于'empty'.由于某种原因,var_dump(stmt ['likedFour']);返回字符串"s".为什么会这样?

According to table UserData, likeFour should equal 'empty'. For some reason, var_dump(stmt['likedFour']); is returning the string 's'. Why is this?

编辑(这是您告诉我的操作,但是不起作用): 当我运行此脚本时,脚本将在var_dump处停止.

Edit (this is what you told me to do but it is not working): when I run this the script stops at the var_dump.

require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s',$username);
//$username = $_POST["username"];
$username ="netsgets";
$stmt->execute(); 
$row = $stmt->fetch_assoc();
var_dump($row['likedFour']);

为什么var_dump(stmt['likedFour']);返回's':

因为在stmt之前缺少美元符号,所以PHP认为您正在尝试访问常量 stmt而不是变量 .由于您尚未定义该常量,因此它会回到假设您尝试访问 string "stmt"的位置.对于字符串,索引必须是数字,因此PHP应该向您抛出非法字符串偏移"警告,但会尝试通过将'likedFour'强制转换为整数(将为0)来为您修复该错误.

Why does var_dump(stmt['likedFour']); return 's':

Because you're missing the dollar sign before stmt, so PHP thinks you're trying to access the constant stmt instead of the variable $stmt. Since you haven't defined that constant, it will fall back to assuming you're trying to access the string "stmt". For strings, indices must be numeric so PHP should be throwing you an "Illegal string offset" warning but will try to fix it for you by casting 'likedFour' to an integer (which will be 0).

因此,var_dump(stmt['likedFour'])与PHP中的var_dump("stmt"[0])含义完全相同,这就是为什么要获取输出"s"的原因:"stmt"的第一个字符.

Therefore, var_dump(stmt['likedFour']) means the exact same thing as var_dump("stmt"[0]) to PHP, which is why you're getting the output "s": the first character from "stmt".

您首先需要从查询中检索结果行. $stmt是用于执行查询和检索结果的mysqli_stmt对象,实际上不是结果本身.

You first need to retrieve the resulting rows from your query. $stmt is the mysqli_stmt object that you use to execute the query and retrieve the results, it is not actually the result itself.

为避免日后头疼,在尝试检索结果之前,请始终检查查询是否成功执行.然后获取数据行:

To save yourself headaches in the future, always check whether your query even executed successfully before trying to retrieve the results. Then fetch the row of data:

$success = $stmt->execute();
if (!$success) {
    echo $stmt->error;
} else if ($stmt->num_rows == 0) {
    echo 'No results matching that username';
} else {
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    var_dump($row['likedFour']);
}

如果您不知道将返回多少行,请为了安全起见遍历它们:

If you don't know how many rows will be returned, loop through them just to be safe:

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    var_dump($row['likedFour']);
}