UPDATE not working

Why isn’t this updating the table? The db connection is correct and I have confirmed the $values.

$servername = “localhost”;
$database = “mydatabase”;
$dbuser = “mydbuser”;
$db_password = “banana”;

// Create connection

$conn = mysqli_connect($servername, $dbuser, $db_password, $database);

$result = mysqli_query($conn, $sql);
$sql = “UPDATE users
SET
avatar =’$avatar’
WHERE username=’$username’”;

It’s kind of hard to take the posted code serious. It’s out of order (you cannot use the $sql variable before it has been assigned a value) and it’s doubtful you are using a php version old enough so that the $avatar and $username variables exist and are being populated with submitted data.

Your form processing code needs to -

  1. detect that a post method form has been submitted.
  2. use the correct $_POST variables that correspond to the form field names.
  3. validate the input data before using it. there’s no point in running the query if the data is empty or if not of the correct format.
  4. not put external data directly into the sql query statement. use a prepared query instead, with a place-holder in the query statement for each value, then supply the data when the query gets executed.
  5. switch to use the much simpler php PDO extension.
  6. use the user id (an auto-increment index column) when referring to existing data in a query.
Sponsor our Newsletter | Privacy Policy | Terms of Service