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
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";
}
?>
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 are trying to access the value incorrectly. It is not an array, try replacing this:
$registrationNo = $result["registrationNo"];
with this:
$registrationNo = $result[0]->registrationNo;
Hope that helps!
Do you have an idea where exactly you're facing the issue?
You could try debugging. Try something like this:
$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.
Hope this helps.
Peace! xD
Try this: (for array fetching)
<?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 ...
?>
The way you're doing it now, $result is an array holding the entire row of data from your table, but since you're trying to return a single value instead of a complete row, you can just use this:
$sql = "SELECT registrationNo FROM cars WHERE driverNo = " . $_POST['driverNo'];
$registrationNo = $conn->query($sql)->fetch_row()[0];
Basically, this dumps the array returned from the query into fetch_row()
, and the [0]
is accessing just the first element in that array. Since you only specified a single field in your SQL, the first value in that array should be the data you want.
If you want to keep all of your code, you could just alter it this way:
$registrationNo = $result->fetch_row()[0];