-1

I'm currently trying to use a sql query to get the id from the last inserted row in my table and wanted to use this id in another sql query, where I update the phone number, but really can't get this to work. Credentials are working fine and i erased for security reasons. Sorry for any error, new to programming.

My code:

error_reporting(E_ALL);
ini_set('display_errors', 1);

    $pdo = new PDO('mysql:host=;dbname=','','');
    $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    //insert data 

$insertid = "SELECT id FROM dados ORDER BY id DESC LIMIT 1";//the first query where i get the id

    if(isset($_POST['telefone'])){

      $sql = $pdo->prepare("UPDATE dados SET telefone=? WHERE id = ($insertid) "); //where i wanted to use the id
      $sql->execute(($_POST['telefone']));
    //  echo 'telefone inserido com sucesso';
    }
?> 

But i keep getting the error: Warning: PDOStatement::execute() expects parameter 1 to be array, string given on line 28 ($sql->execute(($_POST['telefone']));)

eitibiti
  • 45
  • 6
  • Side note: Do not use string interpolation or concatenation to get values into SQL queries. That's error prone and might make your program vulnerable to SQL injection attacks. Use parameterized queries. See ["How to include a PHP variable inside a MySQL statement"](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) and ["How can I prevent SQL injection in PHP?"](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – sticky bit Jan 06 '22 at 16:59
  • 1
    Not related to the error you get, but you can simplify your code in a single query: `UPDATE dados SET telefone=? ORDER BY id DESC LIMIT 1` – forpas Jan 06 '22 at 17:12
  • thanks @forpas, that's what i wanted! – eitibiti Jan 06 '22 at 19:00

2 Answers2

0

PDOStatement::execute() does expect first parameter to be an array. So you should change this:

$sql->execute(($_POST['telefone']));

with this:

$sql->execute([$_POST['telefone']]);
Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26
0

Actually i did not needed to use 2 queries, only one, it goes like:

$sql = $pdo->prepare("UPDATE dados SET telefone=? ORDER BY id DESC LIMIT 1");

Thanks to @forpas for clarifying!!

eitibiti
  • 45
  • 6