Reputation: 2530
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) {...}
).
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.
The new code (PDO prepared statement)
$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();
}
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();
}
I've deleted most of the variables in order to simplify things (since the code is the same)
Upvotes: 2
Views: 7700
Reputation: 1895
There are a number of ways you can check whether an INSERT worked correctly.
As you said, $stmt->execute();
returns true on success or false on failure. So you can use:
$result = $stmt->execute();
if ($result) {...}
PDO Execute documentation here
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) {...}
PDO rowCount documentation here
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) {...}
Note: You must call lastInsertId
on the PDO object, not the $stmt
.
PDO lastInsertId documentation here
Upvotes: 6