PHP PDO准备语句失败

时间:2013-10-24 18:37:52

标签: php mysql database pdo

当我想为我的数据库提交数据时,我一直在失败。 建立连接,但是当我使用时:

 $sql = $MyConnection->prepare("
    INSERT INTO AMP_USERS (Username, Password, Lastname, Email) VALUES ('$username', '$password', '$lastname', '$email')
    ");

  $sql->execute();

我失败了。 我已经完成了:

$sql->bindParam(:username, $username)

等等,但是没有工作/没有提供错误。 不知何故,数据不会存储到数据库中,并且错误必须在这段代码中的某处。

修改

虽然我不认为所有代码都是必要的,但我会发布它:

    <?php

  require('config.php');

  if($MyConnection = new PDO('mysql:host=fdb6.biz.nf;dbname=1446018_venator', $dbusername, $dbpassword)) {
    echo "A connection has been made!";
  }

  $username = $_POST['username'];
  $password = $_POST['password'];
  $lastname = $_POST['lastname'];
  $email = $_POST['email'];

  // Hasing the password:
  // A higher "cost" is more secure but consumes more processing power
  $cost = 10;

  // Create a random salt
  $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');

  // Prefix information about the hash so PHP knows how to verify it later.
  // "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
  $salt = sprintf("$2a$%02d$", $cost) . $salt;

  // Hash the password with the salt
  $hash = crypt($password, $salt);

  $sql = $MyConnection->prepare("
    INSERT INTO AMP_USERS (Username, Password, Lastname, Email) VALUES (:username, :password, :lastname, :email)
    ");
  $sql->bindParam(':username', $username);
  $sql->bindParam(':password', $hash);
  $sql->bindParam(':lastname', $lastname);
  $sql->bindParam(':email', $email);
  $sql->execute();

?>

1 个答案:

答案 0 :(得分:1)

失败但未报告错误

更改PDO的错误报告。

$MyConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

如果出现SQL错误,PDO应立即报告。

选择数据库

除了由变量插值引起的可能错误之外,我在查询中看到的唯一错误是表名不是完全限定的。如果您尚未选择数据库,则可能需要。

$MyConnection = new PDO("mysql:host=localhost;dbname=DBNAME");
// or in the query
"INSERT INTO DBNAME.AMP_USERS ..."

注意 您不会真正写DBNAME,而是数据库的实际名称是什么。

使用准备好的陈述

你应该这样做,不管是为了防止注射,但是根据你使用的变量的内容,它们也可能引起问题。

$stmt = $MyConnection->prepare("
    INSERT INTO AMP_USERS (Username, Password, Lastname, Email) VALUES (?,?,?,?)
");
$stmt->execute(array($username, $password, $lastname, $email));

使用$stmt->execute(array(":username" => $username))$stmt->bindParam(":username", $username)(或bindValue)等命名参数也有效。


如果这些解释无法帮助您解决问题,则忽略了问题中的重要数据。

相关问题