我的问题是当我输入一个特定的国家名称时,例如:法国,它将输出数据库中的所有数据,而不仅仅是法国。我不知道哪里出了问题,这可能很简单,但我什至不知道如何尝试解决它,所以我来这里寻求帮助
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$country = $_POST['country'];
$_SESSION['country'] = $country;
$sqlQuery = "SELECT * FROM campsites WHERE country LIKE '%$country%'";
$result = $campDataSet->fetchAllCamps($sqlQuery);
//var_dump($result);
if (count($result) > 0) {
echo'<div class="table-responsive">
<table class="table">
<thead id="table1Head">
<tr><td>Name</td>
<td>Address</td>
<td>Postcode</td>
<td>Country</td>
<td>Latitude</td>
<td>Longitude</td>
<td>email</td>
<td>Phone<td>
</thead>
<tbody>
</div>';
foreach ($result as $row) {
echo '<tr><td>' . $row->campsite_name . '</td> <td>' . $row->address . '</td> <td>' . $row->postcode . '</td> <td>' . $row->country. '</td> <td>' . $row->lattitude . '</td> <td>' . $row->longitude . '</td> <td>' . $row->email . '</td> <td>' . $row->phone_number . '</td></td></tr>';
}
echo "</tbody></table>";
} else {
print " 0 results";
}
}
我的数据库类
class campDataSet
{
public $dbHandle, $dbInstance;
public function __construct()
{
$this->db = new campData();
$this->conn = $this->db->getCampData();
}
public function fetchAllCamps()
{
//$sqlQuery = "SELECT campsites.id_campsite, campsites.campsite_name, campsites.address, campsites.postcode, campsites.country, campsites.lattitude, campsites.longitude, campsites.email, campsites.phone_number
// FROM sgb220_clientserver.campsites";
$sqlQuery = "SELECT * FROM sgb220_clientserver.campsites";
if ($data = $this->conn->prepare($sqlQuery)) {
$data->execute();
$dataSet = [];
while ($row = $data->fetch()) {
$dataSet[] = new DBdata($row);
}
} else {
echo "<script> alert(\"Could not prepare SQL statement\") </script>";
}
return $dataSet;
}
答案 0 :(得分:3)
您的fetchAllCamps()
方法不接受任何参数。
使用参数代替在$sqlQuery
内定义fetchAllCamps
:
public function fetchAllCamps($sqlQuery) // <- This
{
if ($data = $this->conn->prepare($sqlQuery)) {
$data->execute();
$dataSet = [];
...
由于您将$_POST
数据直接插入查询中,因此用户能够操作sql,因此可以按自己的意愿提取/处理数据。阅读有关SQL注入的知识,以及如何防止它使数据库免受攻击者的攻击。</ p>
这可能是一个很好的起点:https://stackoverflow.com/a/601524/2232127
答案 1 :(得分:0)
Your issue is that you are running a query that just gets all of the camps instead of only the ones in a certain country. Your fetchAllCamps() function does not accept any parameters.
It would probably be best to move your query into the fetchAllCamps() function, or make another function entirely if you need a function to give you all the camps instead o just ones in a certain country. Instead of passing in the query, just pass the $country variable. Build your query inside the function and run it.
This way you are separating all of your SQL from where you are building your HTML. This is more in line with modern programming standards.