-3

When i use an int (id= 1) in WHERE clause it works but not as a string variable (id= $id)

<?php     
    $conn=mysqli_connect('localhost','root','','htmscontrol');
    $Device_id = $_POST['Device_id'];
    $id = $_POST['id'];
    $sql = "UPDATE identity SET Device_id = '$Device_id'  WHERE id= $id "

    if (mysqli_query($conn, $sql)) {
        echo "Record updated successfully";
    } else {
        echo "Error updating record: " . mysqli_error($conn);
    }

    $conn->close();
    header("Location: header.php"); 
?>
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
Anas
  • 1
  • Please try this $sql = "UPDATE identity SET Device_id = '".$Device_id."' WHERE id= '".$id."' – jubin Jun 15 '21 at 09:52
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Jun 15 '21 at 10:04

1 Answers1

0

You must use mysqli prepared statements:

$sql = "UPDATE identity SET Device_id = ? WHERE id = ? ";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param('si', $Device_id, $id);

if ($stmt->execute()) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $stmt->error;
}

$conn->close();
Dharman
  • 30,962
  • 25
  • 85
  • 135
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39