1

I am facing one issue. I need to check value which should present within two column values using PHP and MySQL. I am explaining my table below.

    id      zip_from               zip_to

     1        751001                751030

db_postcode:

$post_code='751010';
$sql="select * from db_postcode where zip_from >='".$post_code."' and zip_to='".$post_code."'";
$sqlpin=mysqli_query($conn,$sql);
if (mysqli_num_rows($sqlpin) > 0) {
    $data=array("status"=>"Success","msg"=>"Product is available for this postcode");
}else{
    $data=array("status"=>"Failed","msg"=>"Product is not available for this postcode");
}
echo json_encode($data);

Here I am getting the message {"status":"Failed","msg":"Product is not available for this postcode"} which is wrong because code 751010 is present within 751001-751030. Here I need to check the user given value should be present within that two column.

9
  • Can you share the exact column definitions? Is zip_from a INT column? And why do you think that this is related to PHP? Commented Jan 9, 2019 at 11:58
  • 1
    You have zip_to = , but i think you need zip_to <=. Commented Jan 9, 2019 at 11:59
  • @NicoHaase : both column is varchar. Commented Jan 9, 2019 at 11:59
  • @Cynical : No as per you also not working. Commented Jan 9, 2019 at 12:00
  • Mind the SQL injection Commented Jan 9, 2019 at 12:01

2 Answers 2

1

Your compare is written the wrong way around, what you want is to check that $post_code is between zip_from and zip_to:

$sql="select * from db_postcode where '$post_code' between zip_from and zip_to";

Note that this will only work if all zip_from, zip_to and $post_code values are the same length, otherwise you will run into issues that in a string compare, 2 > 100000. If they are not the same length, you should cast them to integer to compare them.

Sign up to request clarification or add additional context in comments.

Comments

0

Well, Your query would should be this:

$sql="select * from db_postcode where ".$post_code." BETWEEN zip_from and zip_to";

2 Comments

I have already tried this but same issue. Let me to remind you both column has datatype varchar.
Please explain why it should be like this and which exact changes were needed

Your Answer

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