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.
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.
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!
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.
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 aPDOStatement
object, orFALSE
on failure.