如果在PDO预处理语句中插入成功,则为if / else语句的语法
我正在尝试从mySql语句切换到PDO预处理语句,但是我很难找到if / else语句的正确语法,如果插入成功,我必须使用它(之前是 if($ result){...}
)。
I'm trying to switch from mySql statements to PDO prepared statements, but I'm having trouble figuring out the correct syntax for the if/else statements that I have to use if the insert was successful (which were previously if($result) {...}
).
我知道$ stmt-> execute();成功时返回true,失败时返回false,但我无法确定如何设置语句以对其执行操作。
I know that $stmt->execute(); returns true on success or false on failure, but I haven't been able to determine how to set the statement up to act on that.
新代码(PDO预备声明)
$gender = $_POST['gender'];
if ($gender==="female" ) {
try {
$stmt = $conn->prepare('INSERT INTO customer_info (fname...) VALUES(:fname...)');
$stmt->bindParam(':fname', $_POST['fname'], PDO::PARAM_STR);
$stmt->execute();
} catch(PDOException $e) {
echo $e->getMessage();
}
这是原始的其余部分if($ gender ===female)
function
This is the rest of the original if ($gender==="female")
function
$result = @mysql_query($qry);
if($result) {
$qry="SELECT * FROM customer_info WHERE user_name='$_POST['user_name']' AND password='$_POST['password']'";
$result=mysql_query($qry);
if($result) {
if(mysql_num_rows($result) == 1) {
//user_name Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_USER_ID'] = $member['user_id'];
session_write_close();
header("location: flatter_iframe.html");
exit();
}else {
header("location: login_failed.html");
exit();
}
我删除了大部分变量以简化操作(因为代码相同)
有很多方法可以检查INSERT是否有效正确。
There are a number of ways you can check whether an INSERT worked correctly.
如你所说, $ stmt-> execute();
成功时返回true,失败时返回false。所以你可以使用:
As you said, $stmt->execute();
returns true on success or false on failure. So you can use:
$result = $stmt->execute();
if ($result) {...}
rowCount将返回查询所包含的行数。插入成功后,该值应为1.
rowCount will return the number of rows afffected by a query. After a successful insert, this should be 1.
$stmt->execute();
$affected_rows = $stmt->rowCount();
if ($affected_rows == 1) {...}
如果您的表有一个ID列,您可以使用 lastInsertId()$ c返回上一个插入行的ID $ c>。
If your table has an ID column, you can return the ID of the last inserted row using lastInsertId()
.
$stmt->execute();
$newCustomerInfoId = $pdo->lastInsertId();
if ($newCustomerInfoId) {...}
注意:您必须致电 lastInsertId ,而不是 $ stmt
。
Note: You must call lastInsertId
on the PDO object, not the $stmt
.