我是php和mysql的新手。我正在尝试检查用户是否已被带走。如果它被采用,那么它将不会添加到数据库中。但是,我尝试了很多代码来完成这个技巧,但我使用的代码都没有。我不确定我做错了什么。这就是我现在所拥有的:
<?php
include 'db_settings.php';
db_connect();
//Escape variables for security
$user = mysqli_real_escape_string($con, $_POST['user']);
$pass = mysqli_real_escape_string($con, $_POST['pass']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO users (user, pass, email)
VALUES ('$user','$pass', '$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added</br>";
mysqli_close($con);
echo "<a href='sign-up.html'>sing-up again!</a></br>";
echo "<a href='index.html'> Go Back Home </a>";
?>`
我知道这段代码没有为用户提供检查功能,因为我删除了所有关于它的代码。所以,如果有可能你们帮助我,我会很感激。
答案 0 :(得分:1)
您的代码似乎没问题 做一件事在你的mysql控制台或phpMyadmin上运行下面的代码
ALTER TABLE `users` ADD UNIQUE (
`user`
);
答案 1 :(得分:1)
您需要将数据库中的结果与Select查询匹配,where子句中的条件取决于您要匹配记录的基础。所以你可以试试这样的东西
$query = "SELECT email,user FROM users where user='$user' and email='$email' ";
$result = mysql_query($query);
if (mysql_num_rows($result)) { // user already exists }
else { // Insert query }
答案 2 :(得分:0)
您需要首先执行一个选择查询,该查询将使用发布的电子邮件/用户名获取用户,并检查结果中是否显示任何记录。
仅在此之后触发插入查询。
$sql = "SELECT email FROM users where email='".$email."'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
//user already exists
}
如果您不想在重复记录的情况下执行任何操作,还有一个备用。
使用INSERT...IGNORE
它不会在复制时插入记录。
答案 3 :(得分:0)
<?php
include 'db_settings.php';
db_connect();
//Escape variables for security
$user = mysqli_real_escape_string($con, $_POST['user']);
$pass = mysqli_real_escape_string($con, $_POST['pass']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO users (user, pass, email)
VALUES ('$user','$pass', '$email')";
$checkQuery = "SELECT * from users where user='".$user."';";
$result = mysqli_query($con,$checkQuery);
if ($result) {
die("Username taken");
} else {
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added</br>";
}
mysqli_close($con);
echo "<a href='sign-up.html'>sing-up again!</a></br>";
echo "<a href='index.html'> Go Back Home </a>";
?>`
答案 4 :(得分:0)
你应该尝试这样的事情。
<?php
include "db_setting.php";
$user = $_POST['user'];
$pass = $_POST['pass'];
$email = $_POST['email'];
$check = mysql_query("select * from registration_table where username = $user");
$check_user = mysql_num_row($check);
if($check_user > 0)
{
echo "This username already exists";
}else
{
mysql_query("insert INTO registration_table ('user','pass','email') VALUES ($user,$pass,$email)");
}