我正试图将sql查询的结果存储到php查询中的一个变量中。但问题是,它不起作用,仅仅是因为我犯了学生时代的错误,而且我缺乏php方面的经验。
这是我的代码:
<?php
if(!empty($_POST['driverNo'])){
$driverNoText = $_POST['driverNo'];
$stmt = "SELECT registrationNo FROM cars WHERE driverNo = ?";
$result = $conn->prepare($stmt);
$result->bind_param('s', $driverNoText);
$result->execute();
$result->store_result();
if($result->num_rows > 0){
$registrationNo = $result["registrationNo"];
echo $registrationNo;
}
else{
$registrationNo = "";
}
}
else{
echo "Something went horribly wrong";
}
?>
我只想将registrationNo存储到$registrationNo中,因为以后我需要在其他地方使用该值。
如果有人能帮我修复错误,那将意义重大
感谢
您试图错误地访问该值。它不是一个数组,请尝试替换它:
$registrationNo = $result["registrationNo"];
这个:
$registrationNo = $result[0]->registrationNo;
希望能有所帮助!
您知道问题的具体位置吗?
您可以尝试调试。试试这样的东西:
$stmt = "SELECT registrationNo FROM cars WHERE driverNo = ?";
$result = $conn->prepare($stmt) or die( mysqli_error($dbh) ); // Where $dbh = mysqli_connect("localhost","root", "password", "database");
$result->bind_param('s', $driverNoText);
$result->execute() or die( mysqli_stmt_error($result) );
//$result->store_result();
/* I'd prefer you to use bind result instead */
$result->bind_result($registrationNo);
echo $registrationNo; // This must show the registration no.
希望这能有所帮助。
和平!xD
试试这个:(用于数组获取)
<?php
// your codes ...
$result->bind_param('s', $driverNoText);
$result->execute();
$result->bind_result($col);
if($result->num_rows > 0){
while ($result->fetch()){
$registrationNo = $col;
echo $registrationNo."<br/>";
}
} else{
$registrationNo = '';
echo $registrationNo."<br/>";
}
// your code ...
?>
现在的做法是,$result是一个数组,包含表中的整行数据,但由于您试图返回单个值而不是完整的一行,因此可以使用以下方法:
$sql = "SELECT registrationNo FROM cars WHERE driverNo = " . $_POST['driverNo'];
$registrationNo = $conn->query($sql)->fetch_row()[0];
基本上,这会将查询返回的数组转储到fetch_row()
中,而[0]
只访问该数组中的第一个元素。由于您在SQL中只指定了一个字段,因此该数组中的第一个值应该是您想要的数据。
如果你想保留所有的代码,你可以这样修改:
$registrationNo = $result->fetch_row()[0];