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.
直接取自 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;
}
你正在寻找这个:if ($conn->query($sql) === TRUE)
编辑: 抱歉,正如@Drew指出的那样,举了错误的例子!
下面是正确的片段,它确实使用了执行,因为我认为它应该(如果我错了,请纠正我!)
此链接可能更有用: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();
}
和
<?php
function customExecute(PDOStatement &$sth, array $params = array()) {
if (empty($params))
return $sth->execute();
return $sth->execute($params);
}
?>
希望这可以帮助!
您通常对通过调用返回execute()
的PDOStatement
对象执行prepare()
调用。
在这里,您query()
调用的返回值也将是PDOStatement
对象,您可以在其上应用您的rowCount()
.
PDO::query()
返回一个PDOStatement
对象,或者FALSE
失败。
PDO查询函数将返回一个PDOStatement
您可以检查 PDOStatement 中的错误代码。如果一切都成功执行,它应该是 0。另一种选择是检查rowCount函数的结果 - 如果插入了新行,它应该是 1。