我有一份登记表。在数据库中,用户名和电子邮件是唯一索引。当表单提交并且数据库中已存在用户名或电子邮件时,不会插入值。我想通知用户没有插入值。我怎么能这样做?
HTML
<form action="register.php" method="post" id="reg" onsubmit='return validate();'>
Company Name:
<input type="text" class="inputs" name="name" id="name" /><br />
Email:
<input type="text" class="inputs" name="email" id="txtEmail" /><br />
User name:
<input type="text" class="inputs" name="uname" id="uname"/><br />
Password:
<input type="password" class="inputs" name="pass" id="pass1"/><br />
Conferm Password:
<input type="password" class="inputs" name="cpass" id="pass2"/><br /><br />
<input type="submit" value="Register" class="button" />
</form>
register.php:
include ("db.php");
if (isset($_POST['register'])) {
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
mysqli_query($con,"INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','')");
}
答案 0 :(得分:3)
* 甜蜜和短暂*
首先使用 select
查询检查用户名或电子邮件是否存在,如果结果为0(表示不存在), Insert
查询将提前运行
<?php
if($_POST['register']){
$uname = $_POST['uname'];
$email = $_POST['email'];
$name= $_POST['name'];
$pass= $_POST['pass'];
$result = mysqli_query($con, 'SELECT * from TABLE_NAME where email_id = "'.$email.'" or username = "'.$uname.'" ');
if(mysqli_num_rows($result) > 0){
echo "Username or email already exists.";
}else{
$query = mysqli_query($con , 'INSERT INTO TABLE_NAME (`email_id`, `username`,`name`,`pass`) VALUES("'.$email.'", "'.$email.'", "'.$uname.'","'.$name.'", "'.$pass.'")');
if($query){
echo "data are inserted successfully.";
}else{
echo "failed to insert data.";
}
}
}
?>
答案 1 :(得分:0)
查询方法将返回true或false,具体取决于是否已插入行。
答案 2 :(得分:0)
尝试以下代码
include ("db.php");
if (isset($_POST['register']))
{
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
$var = mysqli_query('SELECT * from company_profile where email_id = "'.$email.'" or username = "'.$uname.'" ');
$num = mysqli_num_rows($var);
if($num==0)
{
$result = INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','');
$res = mysqli_query($result);
if($res)
{
echo "Records Inserted Successfully!!";
}
else
{
echo "Records Inserted Failed!!";
}
}
else
{
echo "User with the Details Already exists!!"
}
}