[英]Store the first result value into a variable from sql query in php
I am trying to store the result from an sql query into a variable in my php query. 我正在尝试将sql查询的结果存储到我的php查询中的变量中。 But thing is, it is not working, simply because I am making schoolboy errors and due to my lack of experience in php. 但是事实是,它不起作用,仅仅是因为我犯了小学生错误以及由于我缺乏php经验。
This is my code: 这是我的代码:
<?php
include "init.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";
}
?>
Please note that as both the registrationNo and driverNo are both unique then the result will either return 0 records (not found) OR just 1 (found). 请注意,由于registrationNo和driverNo都是唯一的,因此结果将返回0条记录(未找到)或仅返回1条(找到)。
I just want to store the registrationNo into the $registrationNo, because I need to use that value elsewhere later. 我只想将registrationNo存储到$ registrationNo中,因为稍后需要在其他地方使用该值。
Would mean a lot if someone could help me fix my error 如果有人可以帮助我修复错误,那将意味着很多
Thanks 谢谢
You have to use ->bind_result()
for that: 您必须使用->bind_result()
:
$result = $conn->prepare( $stmt );
$result->bind_param( 's', $driverNoText );
$result->execute();
$result->store_result();
$result->bind_result( $registrationNo );
while( $result->fetch() )
{
echo $registrationNo;
}
$result->free_result();
Note that the use of ->store_result()
in your example is not necessary (although it is not an error): it doesn't “store the first result”, it store all result set in php side. 请注意,在您的示例中不必使用->store_result()
(尽管这不是错误):它不会“存储第一个结果”,而是将所有结果集存储在php端。 Your script will work even without using it. 您的脚本即使不使用也可以运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.