-1

我正在尝试将一些 post 变量插入数据库,但似乎无法使其正常工作。这是我目前的代码。

 include('db_connect.php'); // = $connection

$name = $_POST['name'];
$email = $_POST['email'];

$result = mysqli_query($connection,"SELECT * FROM users WHERE email='$email'");
$row = mysqli_num_rows($result);

if($row==0)
{
echo("email was not found");
mysqli_query($connection,"INSERT INTO users (name, email, comfirmed) VALUES ('".$name."', '".$email."', 0)");

}
else
{
    echo("email was found");
}

我已经尝试了几种插件的变体,但无法让它工作。如果我用静态值替换变量,那么它可以正常工作并且我的数据库会更新。我也意识到此时存在安全问题,但我想专注于让插入工作然后返回并修复这些问题。

4

1 回答 1

0

您的代码中有很多错误。最重要的是

  • 此代码没有任何错误报告
  • 它没有正确格式化变量
  • 它正在使用 mysqli

至少它必须是

ini_set('display_errors',1);
error_reporting(E_ALL);
include('db_connect.php'); // as shown in http://stackoverflow.com/tags/pdo/info

$sql = "SELECT 1 FROM users WHERE email=?";
$stm = $pdo->prepare($sql);
$stm->execute(array($_POST['email']));

if ($stm->fetchColumn()) {

    echo("email was not found");
    $sql = "INSERT INTO users (name, email, comfirmed) VALUES (?, ?, 0)");
    $stm = $pdo->prepare($sql);
    $stm->execute(array($_POST['name'],$_POST['email']));

} else {
    echo("email was found");
}

或者,如果电子邮件上有唯一索引(必须如此),您可以在单个查询中创建它

ini_set('display_errors',1);
error_reporting(E_ALL);
include('db_connect.php'); // as shown in http://stackoverflow.com/tags/pdo/info

$sql = "INSERT IGNORE INTO users (name, email, comfirmed) VALUES (?, ?, 0)");
$stm = $pdo->prepare($sql);
$stm->execute(array($_POST['name'],$_POST['email']));

if ($stm->rowCount()) {
    echo("email was not found");
} else {
    echo("email was found");
}
于 2013-06-11T05:57:04.777 回答