繁体   English   中英

如何从SQL查询php获取并将值存储到变量中

[英]How to get and store a value into a variable from SQL query php

我正在尝试将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];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM