简体   繁体   中英

SQL query not working but works in PHPMyAdmin

I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.

I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).

I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.

$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);

$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';

foreach ($vesselArray as $value) {
 $i = $i + 1;
 $sqlExtend .= " vesselID = '$value'";

 if ($i < $arrayCount){
  $sqlExtend .= " OR";
 }
}

$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;

$query = $db->query($newQuery)->fetchAll();

I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.

Any help would be greatly appreciated!

Thanks

That query probably doesn't return what you think it does. AND takes precedence over OR , so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.

You'd do better to create a query with an IN clause like this:

SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)

Here's some code to do just that:

$vesselFilter = $_GET['vesselFilter'];


// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
    echo "Bad data in input";
    exit;
}

// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));


// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';


$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;

$query = $db->query($newQuery)->fetchAll();
var_dump($query);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM