Koiski
Koiski

Reputation: 568

Posting and checking if values allready exists in database PHP

So i am posting some strings to my database. I want it to be able to check if it allready exist an id in my database with same name as the new one. In that case it should alert "notvalid". I have also experienced that in some cases it doesn't save the strings at all even though the id is different from the others. Don't know why that happens..

Here is my code

        $.ajax({
                 type : "POST",
                 url : "saveid.php",
                 data:  {"qid": id, "qtext1": text1, "qtext2": text2, "qtext3": text3, "allCounters": allCounters},
                 dataType: "json",
                 success: function(msg2){ 
                    if (msg2 = 'notvalid') {

                    alert(msg2);
                }
                if (msg2 = 'valid') {

                    alert(msg2);    
                }
             }
        });


<?php   
if (isset($_POST['qid']) && isset($_POST['qtext1']) && isset($_POST['qtext2']) && isset($_POST['qtext3']) && isset($_POST['allCounters'])) { 
    $connection = @mysql_connect('localhost', 'root', '') 
        or die (mysql_error()); 
    mysql_select_db('test', $connection) 
        or die (mysql_error()); 

    $id=$_POST['qid'];
    $text1=$_POST['qtext1'];
    $text2=$_POST['qtext2'];
    $text3=$_POST['qtext3'];
    $allCounters=$_POST['allCounters'];

    $result = mysql_query("SELECT * FROM code WHERE id ='$id' LIMIT 1");
    if (mysql_fetch_row($result)) {
        echo json_encode('notvalid');
    } else {
        $query = mysql_query("INSERT INTO code (id, text1, text2, text3, allCounters) VALUES ('$id','$text1','$text2','$text3','$allCounters')"); 
        echo json_encode('valid');
    }


} 
?> 

This is the first time i am working with PHP. I will appreciate if someone could explain why this doesn't work, how to make it work or any other tips. Thanks

Upvotes: 0

Views: 264

Answers (2)

Justin John
Justin John

Reputation: 9616

Please check your code once again.

You are assigning the value, not checking the equality in ajax success callback. So both statements will be true with your code and both alerts will trigger.

Change from

if (msg2 = 'notvalid') {            
         ^

to

if (msg2 == 'notvalid') {
         ^^

Same applies for if (msg2 = 'valid') too.

Upvotes: 1

phil-lavin
phil-lavin

Reputation: 1217

In answer to your question, see the mysql_num_rows function.

if (mysql_num_rows($result)) {
    echo json_encode('notvalid');
}

As an aside, also look into not using mysql_* functions as they've been deprecated and their use is discouraged. Mysqli and PDO are PHP native alternatives.

If you're using mysql_ functions, you'll need to make sure you escape values going into your database with mysql_real_escape_string() to prevent SQL injection. See http://en.wikipedia.org/wiki/SQL_injection for info.

Upvotes: 1

Related Questions