How can I use prepared statements combined with Transactions with PHP?

后端 未结 3 833
耶瑟儿~
耶瑟儿~ 2020-12-31 19:51

My goal is to use a transaction and a prepared statement simultaneously, to achieve both integrity of data, and prevention of SQL injection.

I have this:

<         


        
3条回答
  •  醉话见心
    2020-12-31 20:14

    Did you mean this?

    try {
        $cnx = new PDO($dsn,$dbuser,$dbpass);   
        $cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $cnx->beginTransaction();
        $stmt=$cnx->prepare("
            SELECT * FROM users, othertable 
            WHERE users.username=? 
            AND othertable.some_column=?");
    
        $stmt->execute(array($user_input,$user_input_2));
    
        $cnx->commit();
    }
    catch (Exception $e){
           $cnx->rollback();
           echo "an error has occured";
    }
    

    That is assuming that the two tables data does not have duplicate field names, otherwise you're going to have to use:

    SELECT users.field1 as u_field1, othertable.field1 as o_field1 FROM users, othertable 
    WHERE users.username=? 
    AND othertable.some_column=?
    

提交回复
热议问题