简体   繁体   中英

How to check if Id is already exist in mysql database using php

Im trying to use this code but its not working for some reason...

Errorcode: Warning: mysql_num_rows() expects parameter 1 to be resource, line number 27

the code im using:

<?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);
  ?>

The error Warning: mysql_num_rows() expects parameter 1 to be resource means that your query had a syntax error.

On successful execution of query, the result variable $check will contain results on that you can perform mysql_num_rows .

If it fails, the value of $check will be FALSE and mysql_num_rows will fail.

Avoid using mysql functions, because they are deprecated. Use mysqli functions instead

If School id is primary key then try replacing the particular line

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

with

$check = mysql_query("SELECT * from wup WHERE Schoolid = ".$schoolid);
$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>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM