使用PDO和准备进行的事务。陈述

时间:2018-08-02 11:37:56

标签: php sql pdo

我需要插入两个表,并尝试了事务。效果很好:

$nom = "Nrc";
$contrasenya = "somePassword"; 

    $conn->beginTransaction();

    $conn->exec("INSERT INTO usuari (nom, contrasenya) 
                 VALUES ('$nom', '$contrasenya')");
    $conn->exec("INSERT INTO well (puntuacio, text) 
                 VALUES ('9', 'some text2')");

    $conn->commit();
    echo "New records created successfully";

现在我要介绍一下准备。安全声明。我不确定该怎么做。这就是我尝试过的。它没有给我任何错误,但是也没有插入任何表中:

$nom = "Nrc";
$contrasenya = "somePassword"; 

    $conn->beginTransaction();

    $stmt = $conn->prepare("INSERT INTO usuari (nom, contrasenya) 
                            VALUES (:nom, :contrasenya)");
    $stmt = $conn->prepare("INSERT INTO well (puntuacio, text) 
                            VALUES ('9', 'some text2')");

    $stmt->bindParam(':nom', $nom);
    $stmt->bindParam(':contrasenya', $contrasenya);
    $conn->commit();
    echo "New records created successfully";

3 个答案:

答案 0 :(得分:1)

您的代码有几个问题:

  1. 您永远不会execute声明。
  2. 您可以使用直接使用值的语句覆盖语句($stmt)。因此,您不会使用正确的准备好的语句。

您可以使用以下代码将表中的值INSERT {}:

//start the transaction.
$conn->beginTransaction();

//the variables of the first statement.
$nom = 'Nrc';
$contrasenya = 'somePassword';

//prepare the first statement, bind the values and execute.
$stmt = $conn->prepare("INSERT INTO usuari (nom, contrasenya) VALUES (:nom, :contrasenya)");
$stmt->bindParam(':nom', $nom);
$stmt->bindParam(':contrasenya', $contrasenya); //TODO - use hashing here!

//... or solution without variable.
//$stmt->bindValue(':nom', 'Nrc');
//$stmt->bindValue(':contrasenya', 'somePassword');

$stmt->execute();

//the variables of the second statement.
$puntuacio = '9';
$text = 'some text2';

//prepare the second statement, bind the values and execute.
$stmt = $conn->prepare("INSERT INTO well (puntuacio, text) VALUES (:puntuacio, :text)");
$stmt->bindParam(':puntuacio', $puntuacio);
$stmt->bindParam(':text', $text);

//... or solution without variable.
//$stmt->bindValue(':puntuacio', '9');
//$stmt->bindValue(':text', 'some text2');

$stmt->execute();

//commit all changes of the transaction.
$conn->commit();

注意:正如其他人已经提到的,您也应该hash your passwords

答案 1 :(得分:-1)

来自php.net

  

与PDOStatement :: bindValue()不同,该变量绑定为引用,并且仅在调用PDOStatement :: execute()时进行评估。

答案 2 :(得分:-1)

要插入密码,您应该使用PHP附带的password() function

您不应像在第一个语句中那样直接在prepare语句中直接插入数据

$stmt = $conn->prepare("INSERT INTO well (puntuacio, text) 
                        VALUES (:number, :some_text)");
$stmt->bindParam(':number', $num);
$stmt->bindParam(':some_text', $text);

您应该execute();准备好的语句才能执行查询插入。

如前所述,此外,您必须先覆盖$ stmt变量,然后才能执行查询。