如何使用php检查mysql数据库中是否已存在Id

时间:2016-09-13 05:34:14

标签: php mysql database variables

我试图使用这段代码,但由于某些原因它无法正常工作......

  

错误代码:警告:mysql_num_rows()期望参数1为资源,第27行

我正在使用的代码:

<?php
 include("db.php");

    $lname = $_POST['lname'];
    $fname = $_POST['fname'];
    $mname = $_POST['mname'];
    $adress = $_POST['address'];
    $gender = $_POST['gender'];
    $nationality = $_POST['nationality'];
    $religion = $_POST['religion'];
    $contact = $_POST['contact'];
    $email = $_POST['email'];
    $school = $_POST['school'];
    $year = $_POST['year'];
    $schooladd = $_POST['schooladd'];
    $schoolid = $_POST['schoolid'];
    $database = $school;
    mysql_select_db("$database", $con); 
    $ID = str_replace(' ', '_', $lname.$schoolid);

    //check if id already exist

  $check = mysql_query("SELECT * from wup WHERE Schoolid = '$schoolid'");   

  if (mysql_num_rows($check) > 0) {
   echo "User Already Exist";   
  }

  else
    {
    $sql = "INSERT INTO scholars (ID, Schoolid, Lastname, Firstname, Middlename, Address, Gender, Nationality, Religion, Contact, Email, School, Year, Schooladdress)
     VALUES ('$ID', '$schoolid', '$lname', '$fname', '$mname', '$adress', '$gender',
    '$nationality', '$religion', '$contact', '$email', '$school', '$year', '$schooladd')";}

   mysql_query($sql,$con);
   mysql_close($con);
  ?>

3 个答案:

答案 0 :(得分:0)

错误Warning: mysql_num_rows() expects parameter 1 to be resource表示您的查询存在语法错误。

成功执行查询后,结果变量$check将包含您可以执行mysql_num_rows的结果。

如果失败,$check的值将为FALSE,mysql_num_rows将失败。

避免使用mysql函数,因为它们已被弃用。使用mysqli函数

答案 1 :(得分:0)

如果学校ID是主键,请尝试替换特定行

$check = mysql_query("SELECT * from wup WHERE Schoolid = '$schoolid'");

$check = mysql_query("SELECT * from wup WHERE Schoolid = ".$schoolid);

答案 2 :(得分:0)

$checkid= mysqli_query($con,"SELECT * FROM scholars WHERE ID= '".$schoolid."'  ")
$match  = mysqli_num_rows($checkid);

if ($match > 0){
    echo "<script>
        alert('ID already exist!');
    </script>";
}