Jahed Hussain
Jahed Hussain

Reputation: 113

Check To See A Match In MySql

I have a form which has a textbox with an attribute called ref. once this is submitted, it updates on of my fields in the database. I have this code working and fine but what i need now is for it to check if the data entered into the textbox exists in the database and if it does, then it should notify the user to choose another reference. here is my code for the php end:

$ref = mysql_real_escape_string($_REQUEST['ref']);
$id = $_GET['public'];

$con = mysql_connect("localhost", "*****", "******");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db('*****', $con);

$sql = "UPDATE public SET ref = '$ref' WHERE public_id = '$id'";

if (!mysql_query($sql, $con)) {
    die('Error: ' . mysql_error());
} else {
    echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}

any ideas guys?

thanks

Upvotes: 0

Views: 147

Answers (2)

Naftali
Naftali

Reputation: 146360

You can get the number of rows affected:

$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
    //something WAS changed!
}
else {
    //NOTHING was changed ... :-(
}

Also I would watch out for Bobby Tables

You might want to use mysqli or PDO's prepared queries for what you want to do.


Based on OP's comment below:

...

if (!mysql_query($sql, $con)) {
    die('Error: ' . mysql_error());
} else {

    $rowsAffected = mysql_affected_rows($con);
    if($rowsAffected) {
        echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
    }
    else {
        //show some error message?
    }
    
}

Upvotes: 2

haneef puttur
haneef puttur

Reputation: 1

In this case First you run a select command to search for the record with particular reference number. If the result is eof , then run insert command. If not EOF then send a warning to the user saying reference number exist and choose another one.

Upvotes: 0

Related Questions