将第一个结果值存储到php中sql查询的变量中


Store the first result value into a variable from sql query in php

我正试图将sql查询的结果存储到php查询中的一个变量中。但问题是,它不起作用,仅仅是因为我犯了学生时代的错误,而且我缺乏php方面的经验。

这是我的代码:

<?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";
    }
?>  

请注意,由于registrationNo和driverNo都是唯一的,因此结果将返回0条记录(未找到)或仅返回1条记录(找到)。

我只想将registrationNo存储到$registrationNo中,因为以后我需要在其他地方使用该值。

如果有人能帮我修复错误,那将意义重大

感谢

您必须使用->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();

请注意,在您的示例中使用->store_result()是不必要的(尽管这不是一个错误):它不"存储第一个结果",而是将所有结果集存储在php端。你的脚本即使不用也能工作。


  • 阅读有关bind_result的更多信息
  • 阅读有关store_result的更多信息