4

I am using php to update a mysql DB within a function. I am able to echo my variable names and was able to return the variables on the php page. This proves to me that my variables are working correctly.

Now when I use the update command, my DB does not respond. Yes, I have connected to the DB and it all works.

This is what I am using to update:

mysql_query("UPDATE `table_name`
            SET `int_field` = '$int_value'
            WHERE `username` = $username");
3
  • 1
    After query, you should check the result, from the error, you will find the wrong part easily. For you case, you missed the quotes for $username Commented Sep 30, 2012 at 4:56
  • Swap the string-delimeters from the int to string perhaps?.. mysql_query("UPDATE table_name SET int_field = $int_value WHERE username = '$username'"); Commented Sep 30, 2012 at 4:58
  • 1
    @enhzflep mysql automatically converts it. Commented Sep 30, 2012 at 5:02

5 Answers 5

3

The value for $username should be wrap with single quotes.

mysql_query(" UPDATE table_name 
                 SET int_field = '$int_value' 
               WHERE username = '$username'");

SideNote: your code is vulnerable with SQL Injection. Please read the article below to know how to secure your code,

Best way to prevent SQL injection in PHP?

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that had worked using quotes around $username. And thanks for the sql injection link. I am using a sanitize function on all field variables as well.
@SlapShot you are welcome :D and Welcome to StackOverFlow Community!
1

You need to quote all of your input to the query. This prevents SQL injection, but also simple syntax errors that would occur if your user innocently inputs a special character that would break your query.

mysql_query('UPDATE table_name '.
            'SET int_field = "'.mysql_real_escape_string($int_value).'" '.
            'WHERE username = "'.mysql_real_escape_string($username).'"');

Comments

1

This is the correct STRUCTURE of how to update with a variable in php

mysql_query("UPDATE tablename SET password='". $NPass ."' WHERE custID='$num'");

Comments

0

Try this :

         mysql_query("UPDATE `table_name`
         SET `int_field` = '$int_value'
        WHERE `username` = '$username'");

Comments

0

I had the same problem and found that the SET value doesn't need single quotes and that the WHERE clause does ...

mysql_query("UPDATE table_name SET int_field=$int_value
WHERE username='$username'");

.. seemed to work for me.

Comments

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.