0

Here is my query:

$db->query("INSERT INTO mytable(col1, col2) VALUES('val1', 'val2')");

I'm trying to understand that query inserts a new row or not? How can I determine it?


Note: I'm not using execute() in this case.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Martin AJ
  • 6,261
  • 8
  • 53
  • 111

3 Answers3

1

Taken directly from w3schools.com/php/php_mysql_insert...

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

You're looking for this: if ($conn->query($sql) === TRUE)

Edit: Sorry, took wrong example as @Drew pointed out!

Below is correct snippet, it does make use of execute, as I think it should (correct me if I'm wrong!)

This link might be of more use: pdostatement.execute

try {
     $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
     // set the PDO error mode to exception
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $sql = "INSERT INTO MyGuests (firstname, lastname, email)
     VALUES ('John', 'Doe', 'john@example.com')";
     // use exec() because no results are returned
     $conn->exec($sql);
     echo "New record created successfully";
    }
catch(PDOException $e)
    {
      echo $sql . "<br>" . $e->getMessage();
    }

and

<?php 
function customExecute(PDOStatement &$sth, array $params = array()) { 
    if (empty($params)) 
        return $sth->execute(); 
    return $sth->execute($params); 
} 
?>

Hope this helps!

Community
  • 1
  • 1
Juan Venter
  • 133
  • 1
  • 10
  • 2
    You mean taken from an unrelated dblibrary reference? – Drew Jul 04 '16 at 15:06
  • Juan, at the bottom there is PDO. Even still, it would return a `PDOStatement`, no? Am I wrong, I might be. Please tweak your answer so I can turn my DV into an upvote my friend. – Drew Jul 04 '16 at 16:43
0

PDO query function will return a PDOStatement

You can check for the error code in the PDOStatement. It should be 0 if everything was executed succesfully. Another option, is checking to rowCount function result - if new row was inserted, it should be 1.

Ron Dadon
  • 2,666
  • 1
  • 13
  • 27
0

You typically perform execute() call on a PDOStatement object, returned via prepare() call.

Here, the return value of your query() call would also be PDOStatement object on which, you can apply your rowCount().

PDO::query() returns a PDOStatement object, or FALSE on failure.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183