1

This is a really simple one, I just can't get my head around it sorry. I have this PHP code which picks up my form value, then compares it with the value stored in the database. That works fine.

However I am not sure how to write this logic in terms of this query:

If posted value = database value { // do something } else { // do something else }

if (empty($_POST['order_id']) === false) {
    // prepare data for inserting 
    $order_id = htmlentities(trim($_POST['order_id']));
    $order_id = preg_replace("/[^0-9]/","", $order_id);

    $result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
    $row    = mysqli_fetch_assoc($result);

    echo $row['order_id'];

}

SOLVED:

Solved the question, was a silly one I know! Just needed this at the end of the code:

if($order_id === $row['order_id']) {
    echo 'found';
} else {
    echo 'not found';
}
2
  • Consider getting the number of results affected by your query and evaluate off of that value. If that number is 0, then we didn't find any matching results. You can then take the user down the else path. Otherwise, you can take them down the happy path. Commented Dec 31, 2013 at 18:36
  • does $_POST['order_id'] contain an id that contains only one non-digit character. The preg_replace function in your code does remove only one non-digit character. Commented Dec 31, 2013 at 19:00

4 Answers 4

3

Try

If ($result->num_rows === 1) { do something } else { do something else }
Sign up to request clarification or add additional context in comments.

2 Comments

num_rows > 0 can also be considered, depending on the behaviour OP wants.
True, though he's launching mysqli_fetch_assoc only once, I assumed the result was expected to be only one.
0

Since you did the business logic in your query you can just use

if( ! is_null($row)) {
   // do
} else {
   // nothing
}

Comments

0

Did I read too much into "If posted value = database value "? Are you just referring to the order_id?

if ($row['listingName'] == $_POST['frm_listingName']) {
    // something
}
else {
    //something else
}

Comments

0

Check this code:

if (empty($_POST['order_id']) === false) {
    // prepare data for inserting 
    $order_id = htmlentities(trim($_POST['order_id']));
    $order_id = preg_replace("/[^0-9]/","", $order_id);

    $result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");

    if(mysqli_num_rows($result)>0)
    {
        //Match found. do something.
    }
    else
    {
        //No match found. do something.
    }
}

N.B. In place of mysqli_num_rows($result) you can also use $result->num_rows

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.