简体   繁体   中英

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. But thing is, it is not working, simply because I am making schoolboy errors and due to my lack of experience in 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).

I just want to store the registrationNo into the $registrationNo, because I need to use that value elsewhere later.

Would mean a lot if someone could help me fix my error

Thanks

You have to use ->bind_result() for that:

$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. Your script will work even without using it.


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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