charly
charly

Reputation: 193

Update Mysql column field from a table based on user id

I am new to PHP and SQL, at the moment I am just learning and experimenting not worried about security side. I am trying to Update the username and email based on the user id. My table name is users, and the columns within this table are "id, username, email, password".

Now the query doesn't execute this is what I have done so far.

<?php
include("db_connect.php");
error_reporting(0);
$email = $_POST['email'];
$username= $_POST['username'];
$id = $_POST['id'];
$sql= "UPDATE users SET username= '.$username.' , email= '.$email.' WHERE id='.$id.' ";
if($_POST['submit']){
     if (mysqli_query($connection, $sql)) {
          echo "<h3><center>User information Updated successfully</center></h3>";
     } 
     else {
          echo " Something went wrong ";
     }
}
?>
<html>
<head>
<title>Add Data</title>
</head>
<body>   
    <form action="update.php" method="POST" style="font-size: 24px; margin-left: 50px;">
        <h4> update user info</h4>
        Username: <input type="text" name="username"  required><br><br>
        Email: <input type="email" name="email"  required><br><br>
        <input style="background:#2CDC10; font-size:18px;" type="submit" name="submit" value="update data"/>
</form>
</html>

Upvotes: 2

Views: 3188

Answers (1)

user3783243
user3783243

Reputation: 5224

Your main issue is that you are using the PHP concatenation syntax in your SQL string. This makes all your values incorrect and as such your id in where clause doesn't match any record so no records are updated. Your query should be

$sql= "UPDATE users SET username= '$username' , email= '$email' WHERE id='$id' ";

or

$sql= "UPDATE users SET username= '" .$username. "' , email= '" . $email . "' WHERE id='" .$id. "' ";

That would run but is open to SQL injections. You should use prepared statements, parameterize that, and use error reporting:

error_reporting(1);
if(isset($_POST['submit']){
     $email = $_POST['email'];
     $username= $_POST['username'];
     $id = $_POST['id'];
     $sql= "UPDATE users SET username=?, email=? WHERE id=?";
     $stmt = mysqli_prepare($connection, $sql)) {
     mysqli_stmt_bind_param($stmt, "ssi", $username, $email, $id);//third i assumes "id" is an integer
     $result = mysqli_stmt_execute($stmt);
     if(!empty($result)) {
          echo "<h3><center>User information Updated successfully</center></h3>";
     } else {
          printf("Error: %s.\n", mysqli_stmt_error($stmt));
     }
}

This is a rough untested answer. More information about prepared statements can be found here, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.

Upvotes: 2

Related Questions