问题
The website is intended to display certain laws/rules by jurisdiction.
There is a simple mysqli query that finds the counties and then displays the county names on screen with this:
echo "><a href=\"index.php?sel_subj=" . urlencode($subject["county_name"]) . "\">
{$subject["county_name"]}</a></li>";
Then you click on a county name (embedded with the link) and a mysqli query is supposed to look up a table with that county name and get all the jurisdictions within that county.
if (isset($_GET['sel_subj'] )){
$query2 = "SELECT * FROM $sel_subj";
$result2 = $mysqli2->query($query2) or die($mysqli2->error.__LINE__);
while ($subject = mysqli_fetch_array($result2)) {
echo "<li";
echo "><a href=\"index.php?sel_page=" . urlencode($subject["muni_name"]);
echo "&sel_subj=" . urlencode($sel_subj). "\">
{$subject["muni_name"]}</a></li>";
}
}
The problem is that some county names include a space or a hyphen. So when I click on the counties that have a hyphen or space, there is an error.
I get this error when there is a hyphen (example: Miami-Dade): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-Dade' at line 173
And this error when there is a space (example: Palm Beach): Table 'florida.palm' doesn't exist73
If the county is just a string without any special characters, then the jurisdictions are displayed no problem.
Is there a simple solution to this?
回答1:
your database structure is wrong.
It have to be ONE table where country being a field among other columns.
So, the code have to be like this
if (isset($_GET['sel_subj'] )){
$query = "SELECT * FROM documents WHERE country = ?";
$stmt = $mysqli->prepare($query) or trigger_error($mysqli->error);
$stmt->bind_param('s',$_GET['sel_subj']);
$stmt->execute();
$res = $stmt->get_result();
while ($subject = mysqli_fetch_array($res)) {
echo "<li";
echo "><a href=\"index.php?sel_page=" . urlencode($subject["muni_name"]);
echo "&sel_subj=" . urlencode($sel_subj). "\">
{$subject["muni_name"]}</a></li>";
}
}
回答2:
You have to wrap your county name if it contains character like that. BUT, you also need to sanitize your input:
$query2 = "SELECT * FROM `".mysqli_real_escape_string ($sel_subj)."`";
EDIT:
Also, you should look into prepared statements to avoid sql injection.
You should further sanitize your input by limiting the table names that can be defined to those containing county information.
来源:https://stackoverflow.com/questions/16837568/mysqli-php-table-names-with-hyphen-or-space