Jump to content

[SOLVED] Mysql prepared statement wildcard trouble


Smurph

Recommended Posts

So I have a form that sends data using GET. On the page that handles said form information, immediately after determining that information has been sent, I prepare a statement:

 

$stmt = $db->prepare("SELECT * FROM `Parcel` WHERE `District` = ? AND `LandUseCode` > ? AND `LandUseCode` < ? AND `PropAddrStreetName` = ?");
//I actually select certain fields. But I did that properly.
if (!$stmt) {  
echo "DATABASE error!<br>" . $db->error; 
exit();
}else{ 
$stmt->bind_param('siis', $sqlDistr, $loUseCode, $hiUseCode, $sqlRoadName );
$stmt->bind_result(...); //I don't use '...' in my code, just trust me that this part isn't the problem
}

 

Later, I set the variables that were used in the bind_param method. But what if I don't want to search based on 'PropAddrStreetName' value? I have the $sqlRoadName variable set to "%" by default (and it changes if necessary data was sent via the form), but it still doesn't work. I also have problems searching if I don't enter district information. Both of these are strings, as you can tell, and the middle two are ints. The ints work just fine.

 

$sqlRoadName = '%';
$RoadName = $_GET['road']; //road is the name of the field in the form I'm corresponding to. That's not the problem.
...
if ($RoadName != "") {
$sqlRoadName = $RoadName; //This should change the value from "%" ONLY if it's not blank...
}

 

Then, of course, I execute the statement, and fetch the results. It works if I don't leave 'District' on 'any' (it's a dropdown, and I use the same method of setting it to "%" unless other data was entered), and I don't leave the 'Road' field empty.

 

 

Thanks

I've just recently started working with prepared statements and the mysqli class. Before, I would make the SQL query dynamically adding the conditions as necessary. But with now 3 possible conditions that search text values, I need to know how to make a text comparator that will return all text.

 

For instance if a user chose 'any' in the dropdown box that sends data that we'll use for the `District`, I'd like it to basically not narrow the results by what the District field has. I was told that the '%' character was SQL's wildcard, however, I can't return results when "%" is the value of the variable which is bound to the corresponding question mark in the prepared statement.

 

Will I have to still dynamically create the statement to be prepared? That's gonna take like 4-5 if conditions.

 

 

This is a mySQL question, but should it be placed in the PHP forum?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.