Click here to Skip to main content
15,896,912 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey Guys,
I am trying to check mysql table if the name already exists: this is the code

SQL
if (mysql_num_rows(mysql_query('SELECT COUNT(*) FROM table WHERE FirstName=\'' . $firstname . '\' AND LastName=\'' . $lastname . '\' LIMIT 1')) == 0)
    {
        
        $query = "INSERT INTO table(FirstName,LastName, number)VALUES('$firstname', '$lastname', 'number')";
        mysql_query($query,$con);
        echo " uploaded";

    }

    else
    {
        echo "Record already exists";
    }


but i am getting record already exists all the time and it isn't inserting anything. How to fix this please help.
Posted

Count function always returns at least one row. So when you compare if rows returned is 0, then it fails and goes to the else statement. What you need to do is check the value returned by count or change the query to
SQL
SELECT 1 FROM TABLE WHERE FIRSTNAME = 'John' AND LASTNAME = 'Smith'
 
Share this answer
 
Comments
Sandeep Mewara 30-Oct-12 22:39pm    
OP's comment:
thanks i got it now.
I used a select query without count matching the names and it worked.
thanks i got it now.
I used a select query without count matching the names and it worked.
 
Share this answer
 
Comments
Sandeep Mewara 30-Oct-12 22:39pm    
This is not an answer. Please use 'Have a Question or Comment' link to respond to an answer. It will notify answerer of your comment such that he can come back and reply. Or if needed, use Improve Question link to edit/update your question at anytime.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900