简体   繁体   中英

PDO Transaction with Prepared Statements not working

I have a PDO Transaction in which I'm trying to use prepared statements to run two queries on my database. They're both insert statements, they insert data from Facebook into two separate tables (named "player" and "bank").

The Facebook data is sent to this php script by an AJAX post. I've made sure my database is InnoDB, so it is compatible with PDO Transactions, and the Facebook data is reaching the php script (because I tried a basic/unsecure Insert statement with this AJAX post and it worked perfectly), but I can't seem to get the Transaction to work with prepared statements. I think I'm integrating the two incorrectly.

This is my current code:

<?php
$servername = "myserver";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabase";

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);

    $conn->beginTransaction();

    // prepare sql and bind parameters
    $stmt = $conn->prepare("INSERT INTO player (fb_id, f_name, l_name, email, gender) 
    VALUES (:fb_id, :firstname, :lastname, :email, :gender)");
    $stmt->bindParam(':fb_id', $userid);
    $stmt->bindParam(':firstname', $userfirst_name);
    $stmt->bindParam(':lastname', $userlast_name);
    $stmt->bindParam(':email', $useremail);
    $stmt->bindParam(':gender', $usergender);

    $userid = $_POST['userid'];
    $userfirst_name = $_POST['userfirst_name'];
    $userlast_name = $_POST['userlast_name'];
    $useremail = $_POST['useremail'];
    $usergender = $_POST['usergender'];
    $stmt->execute();

    $stmt = $conn->prepare("INSERT INTO bank (fb_id, cb, gb, invite) 
    VALUES (:fb_id, :cb, :gb, :invite)");
    $stmt->bindParam(':fb_id', $userid);
    $stmt->bindParam(':cb', $cb);
    $stmt->bindParam(':gb', $gb);
    $stmt->bindParam(':invite', $invite);

    $userid = $_POST['userid'];
    $cb = "100";
    $gb = "0";
    $invite = "0";
    $stmt->execute();

    }
catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
$conn = null;
?>

I've tried using alert(response); to see what the output of this PHP is, but it's giving me a blank result.

If anyone could give me any advice on this that would be awesome! Also, is this a pretty secure method of running queries on my database? Is it secure from injection attacks?

Thanks in advance!

Each transaction should begin with

beginTransaction()

and end with

commit()

You can commit the transaction just after you execute the last query:

$stmt->execute();
$conn->commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM