PDO - Show message if inserted successfully in MySQL

Discuss coding issues, and scripts related to PHP and MySQL.
PloMar
Posts: 48

PDO - Show message if inserted successfully in MySQL

I wrote a PHP code to insert some data in to MySQL database. I want to display a message indicating whether the records are successfully added to the database or not.
So, how can I check if the Insert was successfully performed without making another SQL query?
Code:

Code: Select all

<?php
try {
  $db_user = 'root';
  $db_pass = 'pass';
  $db = new PDO( 'mysql:host=localhost;dbname=the_db', $db_user, $db_pass );
  $name = 'some_name';
  $email = 'some@mail.com';
  $sql = "INSERT INTO table_name (name, email) VALUES (:name, :email)";
  $query = $db->prepare($sql);
  $query->execute(array(':name'=>$name, ':email'=>$email));
}
catch(PDOException $e) {
  echo $e->getMessage();
}

MarPlo Posts: 186
You can check if the Insert was succesfully performed simply using rowCount() function:

Code: Select all

<?php
try {
  // ...
  if($query->rowCount() > 0){
  echo 'Record Inserted Successfully';
  }
}
catch(PDOException $e) {
  echo 'Data not inserted: '. $e->getMessage();
} 

sandy Posts: 3

Code: Select all

try {
      $db_user = 'root';
          $db_pass = 'pass'; 
          $db = new PDO( 'mysql:host=localhost;dbname=the_db', $db_user, $db_pass );
          $name = 'some_name';
          $email = 'some@mail.com';
          $sql = "INSERT INTO table_name (name, email) VALUES (:name, :email)";
          $query = $db->prepare($sql);
           $result= $query->execute(array(':name'=>$name, ':email'=>$email));
                        if ($result !== false) {
            echo "The no of row inserted :" . $result;
        }
    } catch (PDOException $e) {
        echo $e->getmessage();
    } 

Similar Topics