Home > OS >  Is there a way yo use the result of a sql query in a where when making a form submition?
Is there a way yo use the result of a sql query in a where when making a form submition?

Time:01-07

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']));)

CodePudding user response:

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']]);

CodePudding user response:

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!!

  •  Tags:  
  • Related