0

I have the following code which updates a field in a database table to add 1 to it. The ID should have a variable being posted to it. Can anyone see where this is going wrong?

EDIT: Sorry, I completely forgot to mention the actual problem. The database is not updating the field.

<?php
$con=mysqli_connect("localhost","**","***","***");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"UPDATE base SET thumbdown = thumbdown + 1 WHERE id = $_POST['id']");

mysqli_close($con);
?>
4
  • 1
    What exactly is the issue here? @googleyberry Commented Nov 7, 2013 at 18:27
  • 3
    The query looks fine. Just a wild guess, but could you please print out the $_POST['id'] variable? My guess is it is either not set, or not set to an integer value you are expecting it to be set to. Commented Nov 7, 2013 at 18:27
  • @LorenzMeyer This is what is baffling me. The variable is set and I have also tried printing it as a variable as David said. Commented Nov 7, 2013 at 18:32
  • you gotta surround the $_POST with braces. Commented Nov 7, 2013 at 18:34

1 Answer 1

3

You wont get the $_POST['id'] parsed in to the string correctly as it is an array. You must enclose it in braces:

"UPDATE base SET thumbdown = thumbdown + 1 WHERE id = '{$_POST['id']}'"

But remember (always!) to escape the variable first:

$id = mysqli_real_escape_string($_POST['id']);
mysqli_query($con,"UPDATE base SET thumbdown = thumbdown + 1 WHERE id = '{$id}'");
Sign up to request clarification or add additional context in comments.

11 Comments

How do you know if the id field in the db table is an integer? Did I miss something?
I have it set to an integer. I have just tried this code, and it doesnt seem to be working either?
Then you must provide more detail. What is the output? Are there any errors displayed?
I have a system that is posting to the php script. I have confirmed that it is sending the variable 'id' correctly, for example, I can confirm that it sends over a '4' into the ID variable. There are no visible errors. If I hardcode a number into the script then it works just fine, but the issue seems to come from something to do with the variable.
@maciej There are no quotes around it in the query.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.