0
After performing a query (An INSERT or UPDATE) I would like to know if any changes were made in the database or if nothing happened. With Mysqli I used mysqli_affected_rows. However, I don’t know how I would do this with PDO. In a SELECT I would like to know if any records were returned and how many records were found.
Examples of code I would like to have information if there have been changes:
INSERT:
I wonder if the records were entered
<?php
//Conexão com o Banco de Dados
$c = new Conexao();
$conexao = $c->conectar();
$query = "INSERT INTO events(title,color,start,end)VALUES(:titulo_evento,:cor_evento,:inicio_evento,:fim_evento)";
$stmt = $conexao->prepare($query);
$stmt->bindValue(':titulo_evento',$this->__get('titulo_evento'));
$stmt->bindValue(':cor_evento',$this->__get('cor_evento'));
$stmt->bindValue(':inicio_evento',$this->__get('inicio_evento'));
$stmt->bindValue(':fim_evento',$this->__get('fim_evento'));
$stmt->execute();
//Aqui eu gostaria de verificar se o Insert deu certo
?>
UPDATE
I wonder if the records have been updated correctly
<?php
//Conexão com o Banco de Dados
$c = new Conexao();
$conexao = $c->conectar();
$query = "UPDATE events SET title = :titulo_evento, color = :cor_evento, start = :inicio_evento, end = :fim_evento WHERE id = :id"
$stmt = $conexao->prepare($query);
$stmt->bindValue(':titulo_evento',$this->__get('titulo_evento'));
$stmt->bindValue(':cor_evento',$this->__get('cor_evento'));
$stmt->bindValue(':inicio_evento',$this->__get('inicio_evento'));
$stmt->bindValue(':fim_evento',$this->__get('fim_evento'));
$stmt->bindValue(':id',$this->__get('id'));
$stmt->execute();
//Aqui eu gostaria de verificar se o Update deu certo (Por exemplo, alterou a linha)
?>
SELECT:
I wonder if any record has been found and how many
<?php
//Conexão com o Banco de Dados
$c = new Conexao();
$conexao = $c->conectar();
$query = "SELECT * FROM tbl_usuarios WHERE idade = :idade";
$stmt = $conexao->prepare($query);
$stmt->bindValue(':idade',$this->__get('idade'));
$stmt->execute();
//Aqui eu gostaria de verificar se o SELECT encontrou algum registro e quantos registros ele encontrou
?>
Have you seen the
PDOStatement::rowCount()
?– Woss
No, I’m a little new in PDO. This rowCount returns the number of affected lines ? Could be used in Select and Update ?
– Gato de Schrödinger
The
$stmt->execute()
you return a Boolean. You can determine whether or not it worked with the return of this function. https://www.php.net/manual/pdostatement.execute.php– gmsantos