我正在尝试将一些帖子变量插入到数据库中,但似乎无法使其工作。这是我目前的代码。
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");
}
我尝试过几种不同的插件,但无法使其工作。如果我用静态值替换变量,那么它工作正常,我的数据库更新。我也意识到此时存在安全问题,但我想集中精力让插件工作然后返回并修复它们。
答案 0 :(得分:0)
您的代码中存在许多错误。最重要的是
至少它必须是
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");
}