Lawrence
Lawrence

Reputation: 240

Selecting a value from a MySQL database and if posted value is equal then perform 'action'

I have the following code.

<?php
    $code = $_POST['code'];   // textbox
    $con = mysql_connect("***","****","****");
    if (!$con)
    {
        die('Server overload, please try again' . mysql_error());
    }

    mysql_select_db("example", $con);
    $sql = mysql_query("SELECT code FROM exampletable");

    while ($version = mysql_fetch_array($sql))
    {
         // Do something
    }
    mysql_close($con);
?>

I want this code to check the value of an textbox and then search the column code in my MySQL database to look for any matches. If there are any matches, I would like it to check the column known as 'version' and if 'version' is equal to 1 then execute another piece of code.

Upvotes: 1

Views: 1583

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157896

You must compare values using SQL, not PHP iterating over whole table. That's what SQL was invented for.

$code = mysql_real_escape_string($code);
$sql = "SELECT code FROM exampletable WHERE code='$code' and version = 1";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
    echo "exact code found!";
} else {
    echo "not found";
}

Upvotes: 3

Related Questions