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

后端 未结 3 835
耶瑟儿~
耶瑟儿~ 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:03

    try 
    {
        $cnx = new PDO ($dsn,$dbuser,$dbpass);   
        $cnx->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $cnx->beginTransaction ();
    
        $stmt = $cnx->prepare ("SELECT * FROM users WHERE username=?");
        $stmt->execute(array($username));
    
        $cnx->commit();
    
        while ($row = $stmt->fetch (PDO::FETCH_OBJ)){
            echo $row->userid;
        }
    }
    
    catch (Exception $e) { 
        if (isset ($cnx)) 
            $cnx->rollback ();
           echo "Error:  " . $e; 
        }
    }
    

提交回复
热议问题