oyshee
oyshee

Reputation: 21

unable to check username exists or not

I have created a registration program which insert username password into mysql database. I am now trying to check the username exixts or not. I wrote the following program. its not working. it showing "mysql_num_rows() expects parameter 1 to be resource." I really need your expert suggestion

registration.php

<?php 
require 'jcon.php';
if(isset($_POST["username"], $_POST["firstname"],$_POST["password"])){
    $username=$_POST["username"];
    $firstname=$_POST["firstname"];
    $password=$_POST["password"];
}
$query = mysql_query("SELECT * FROM member WHERE username='$username'");
if(mysql_num_rows($query) != 0)
{
echo "Username already exists";
}
else{
$sql="INSERT INTO member (username, firstname, password)
VALUES ('$username', '$firstname','$password')";}
if(!mysqli_query($con,$sql)){
    die('Error: ' . mysqli_error($con));
}
echo "Dear {$firstname} ! you have been successfully registered. "
?>

Upvotes: 1

Views: 310

Answers (2)

Willy Pt
Willy Pt

Reputation: 1845

You can use this query:

SELECT COUNT(*) as cnt FROM member WHERE username = '$username'`. 

If he's not registered, cnt column will return 0.
Therefore, you can avoid the needed parameter as it is possible for mysql_query to return FALSE if the query doesn't reproduce result and it's not possible for mysql_fetch and friends to make it as parameter.

Upvotes: 0

Shoe
Shoe

Reputation: 76240

it showing "mysql_num_rows() expects parameter 1 to be resource

This is the typical case where mysql_query returns false upon failure therefore triggering the infamous:

mysql_num_rows() expects parameter 1 to be resource

This can be caused by multiple factors. Try running the query in phpMyAdmin or directly to the database and see the error or fetch the last mysql error via mysql_error.

It's good practice to always check if the returned value of mysql_query is false or if the mysql_error string is not empty:

if ($result and empty(mysql_error()))
    // everything ok

Note: Never ever mix mysql_ and mysqli_ functions. If you have to choose I'd go with mysqli since mysql_* functions are considered deprecated.

Upvotes: 1

Related Questions