php - MySQLi prepare in if-statement
Get the solution ↓↓↓I am having a weird error. The following code:
$stmt = $mysqli->prepare("SELECT sold FROM Sales WHERE unitId = ? AND date = ?");
$stmt->bind_param('is', $unitId, $date);
$stmt->execute();
$stmt->bind_result($col1);
if ( $stmt->fetch() ) {
// If something was fetched, it has already uploaded a value today so we need to update it
echo "Existed!";
$update = $mysqli->prepare("UPDATE Sales SET sold = ? WHERE unitId = ? AND date = ?");
var_dump($update);
} else {
// It hasn't been inserted yet, so insert the new record
echo "Not here man?!";
}
Says the $update is false, so the prepared statement with the update SQL did not return an object.
However, if i place that part before in the code, for example here:
$stmt = $mysqli->prepare("SELECT sold FROM Sales WHERE unitId = ? AND date = ?");
$update = $mysqli->prepare("UPDATE Sales SET sold = ? WHERE unitId = ? AND date = ?");
var_dump($update);
$stmt->bind_param('is', $unitId, $date);
$stmt->execute();
$stmt->bind_result($col1);
if ( $stmt->fetch() ) {
// If something was fetched, it has already uploaded a value today so we need to update it
echo "Existed!";
} else {
// It hasn't been inserted yet, so insert the new record
echo "Not here man?!";
}
Then it works? Now the var_dump says that $update is an object.
Why can't i do it after the fetch? Do i need to prepare all statements at once? I believe i am missing something fundamental here, which is why i am asking.
Hope someone can clarify. Thank you
EDIT
I figured it out! I need to call free_result BEFORE i prepare another statement. However, i have no idea why, so i am leaving this question open to get a clarification. This code works, now i just need to know why:
$stmt = $mysqli->prepare("SELECT sold FROM Sales WHERE unitId = ? AND date = ?");
$stmt->bind_param('is', $unitId, $date);
$stmt->execute();
$stmt->bind_result($col1);
if ( $stmt->fetch() ) {
$stmt->free_result();
// If something was fetched, it has already uploaded a value today so we need to update it
$update = $mysqli->prepare("UPDATE Sales SET sold = ? WHERE unitId = ? AND date = ?");
$update->bind_param('dis', $amount, $unitId, $date);
if ( $update->execute() )
echo "Success";
else
echo "Failure";
} else {
// It hasn't been inserted yet, so insert the new record
echo "Not here man?!";
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: err_ossl_pem_no_start_line
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.