mysqli php table names with hyphen or space

青春壹個敷衍的年華 提交于 2020-01-16 11:51:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!