Using variables in MySQL UPDATE - (PHP/MySQL)

I am trying to use variables in mysql update code, but i got the else {echo error message}.
$overwriteName = "UPDATE name SET name = '{$steamprofile['personaname']}' WHERE steamid = '{$steamprofile['steamid']}';";
if ($db->query($overwriteName) === TRUE) {
echo "success";
} else {
echo "error";
}
Answer
Solution:
An easy way of doing this is using prepared statement:
(it's also more secure than using query, see the link for more information)
if($stmt = $db->prepare('UPDATE name SET name = ? WHERE steamid = ?')){ // prepare the query
$stmt->bind_param('ss',$steamprofile['personaname'],$steamprofile['steamid']); // bind your parameters (as many s as there are variables)
$stmt->execute();
// then your code
}
Answer
Solution:
PHP doesn't substitute the value of a variable if you enclose it between simple quotes'$variable'
.
In the query declaration, enclose$steamprofile['personaname']
and$steamprofile['steamid']
like this:
$overwriteName = "UPDATE name SET name = " . "$steamprofile['personaname']" . " WHERE steamid = " . "$steamprofile['steamid']" . ";";
Or don't enclose them at all:
$overwriteName = "UPDATE name SET name = " . $steamprofile['personaname'] . " WHERE steamid = " . $steamprofile['steamid'] . ";";
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: uncaught error: call to undefined function mysqli_connect()
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.