插入

时间:2017-04-12 06:47:15

标签: php

我尝试让我的表单在尝试之前检查 名称 扩展程序 的重复值插入到数据库但我每次都用语法得到一个错误(请注意这不是真正的RedZ,他的弟弟,仍然自己学习)

if($_POST['action'])
{

include('email.php');
$address="";
$name=$_POST['name'];
$extension=$_POST['extension'];
$department=$_POST['department'];
$phone=$_POST['phone'];
$email=$_POST['email'];

$checkname=mysqli_query("SELECT name, email, extension, phone, department FROM {$table} WHERE name = '{$name}' AND WHERE extension = '{$extension}'");
$num_rows = mysql_num_rows($checkname);

if ($num_rows) { //if rows where found by select
trigger_error('It exists.', E_USER_WARNING);
} else {
$query = "
    INSERT INTO users (ID, Name, Email, Extension, Phone, Department)
    VALUES (NULL, '{$name}', '{$email}', '{$extension}', '{$phone}', '{$department}')";
mysql_query($query);

header("Location: index.php");
}


}
?>

2 个答案:

答案 0 :(得分:-1)

最终守则: -

    if ($_POST['action']) {

 include('email.php');
 $address = "";
 $name = $_POST['name'];
 $extension = $_POST['extension'];
 $department = $_POST['department'];
 $phone = $_POST['phone'];
 $email = $_POST['email'];

 $check_q = mysql_query("select phone from users where phone='$phone'") or die("");

 if ($check_q == 1) { ? >
     < script > alert("duplicate value"); < /script>
     <?php
    }
    else
    {
    $query = "INSERT INTO users (ID, Name, Email, Extension, Phone, Department) VALUES (NULL, '$name', '$email', '$extension', '$phone', '$department')";
        $rez = mysql_query($query);
    header("Location: index.php");
    }  

        }
        ?>

答案 1 :(得分:-1)

正如我们在评论中所讨论的那样,我猜你只需要保存表中的唯一用户。

所以你有这个查询:SELECT name, email, extension, phone, department FROM {$table}看起来很好(如果$ table varible不是空的)。但是你没有条件让你获得表格中的所有行。如果您需要检查某些字段,则应添加条件:

检查具有相同名称的行

SELECT name, email, extension, phone, department 
FROM {$table} 
WHERE name = '{$name}'

检查具有相同电子邮件的行

SELECT name, email, extension, phone, department 
FROM {$table} 
WHERE email = '{$email}'

检查具有相同名称和电子邮件的行

SELECT name, email, extension, phone, department 
FROM {$table} 
WHERE name = '{$name}' AND email = '{$email}'

然后你可以这样做:

if ($num_rows) { //if rows where found by select
    trigger_error('It exists.', E_USER_WARNING); 
} else { //if rows where not found by select
    $query = "
        INSERT INTO users (ID, Name, Email, Extension, Phone, Department) 
        VALUES (NULL, '{$name}', '{$email}', '{$extension}', '{$phone}', '{$department}')
    ";
    mysql_query($query);
}