0

I'm trying to update some data from form inputs, but it displays this error:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 in C:\MAMP\htdocs\PHP\mattina\14_07_user_squadra\edit.php:41 Stack trace: #0 C:\MAMP\htdocs\PHP\mattina\14_07_user_squadra\edit.php(41): PDOStatement->execute() #1 {main} thrown in C:\MAMP\htdocs\PHP\mattina\14_07_user_squadra\edit.php on line 41

this is my code:

$title = 'edit user';

$pdo = new PDO('mysql:host=localhost;port=3306;dbname=test_one_to_many', 'root', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$error = false;
$id = "";

if ($_SERVER["REQUEST_METHOD"] == "GET") {
  $id = $_GET['id'];

  $statement = $pdo->prepare("SELECT * FROM users WHERE id = $id");
  $statement->execute();
  $users = $statement->fetchAll(PDO::FETCH_ASSOC);

  $query = $pdo->query("SELECT * FROM type");

  $privileges = $query->fetchAll();
}




if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = htmlspecialchars($_POST['name']);
  $surname = htmlspecialchars($_POST['surname']);
  $adress = htmlspecialchars($_POST['adress']);
  $city = htmlspecialchars($_POST['city']);
  $type_id = (int) htmlspecialchars($_POST['type_id']);




  $statement = $pdo->prepare("UPDATE users SET name = :name , surname = :surname , adress = :adress , city = :city, type_id = :type_id WHERE id = $id)");

  $statement->bindValue(':name', $name);
  $statement->bindValue(':surname', $surname);
  $statement->bindValue(':adress', $adress);
  $statement->bindValue(':city', $city);
  $statement->bindValue(':type_id', $type_id);
  $statement->execute();

  header("location:index.php");
}

thanks!

Bubu23
  • 31
  • 4
  • Yo have an extra *)* in _WHERE id = $id)");_ It should be _WHERE id = $id");_ – nacho Jul 17 '22 at 08:57
  • Deleted, but have the same error :/ – Bubu23 Jul 17 '22 at 09:01
  • This error is coming from the fact that you are **neglecting** prepared statements, which you are correctly using for the INSERT query but for some extremely strange reason not for the SELECT. You must use prepared statements for ANY query that involves a php variable – Your Common Sense Jul 17 '22 at 09:07
  • You should have *all* parameters to the query as bound parameters, don't make an exception for $id - it's coming from the browser, so it's under control of the user. As you fix that, look at where it's coming from in the POST case (hint: currently nowhere). – IMSoP Jul 17 '22 at 09:09
  • StiLl susceptible to SQL INJECTION! why do have `WHERE id = $id`? You started with parameters, but not use them consequently – Honk der Hase Jul 17 '22 at 09:27
  • Added the prepare statement for the id and solved the issue with it in the POST request, thanks! – Bubu23 Jul 17 '22 at 09:33

0 Answers0