这是我之前的代码,SO用户说容易注入,所以我决定尝试将其转换为与PDO一起使用。
if(isset($_POST['q'])) {
$q = $_POST['q'];
$select = $db->query("SELECT * FROM customers WHERE name LIKE '%$q%' OR email LIKE '%$q%' ORDER BY ID DESC");
<form method="post">
<input type="text" name="q" /> <input type="submit" name="search" />
</form>
这是我试图插入的代码:
include 'database.php';
$pdo = Database::connect();
$q = $_POST['q'];
$sql = 'SELECT * FROM customers WHERE name LIKE '%$q%' OR email LIKE '%$q%' ORDER BY ID DESC';
if(isset($_POST['q'])) {
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['name'] . '</td>';
echo '<td>'. $row['email'] . '</td>';
echo '<td>'. $row['mobile'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="read.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="update.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="delete.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
}
Database::disconnect();
?>
我得到的错误是: 注意:未定义的索引:q 警告:除以零
有关为何发生这种情况的任何想法?
答案 0 :(得分:2)
您收到错误是因为q
不存在,您尚未将其发布到该页面。你应该尝试这样的事情:
$pdo = Database::connect();
$q = filter_input(INPUT_POST, 'q', FILTER_SANITIZE_STRING);
if ($q)
{
$query = "SELECT * FROM customers WHERE name LIKE :q OR email LIKE :q ORDER BY ID DESC";
$sth = $pdo->prepare($query);
$sth->bindParam(':q', "%{$q}%", PDO::PARAM_STR);
$sth->execute();
}
答案 1 :(得分:1)
用此
替换您的查询$sql = "SELECT * FROM customers WHERE name LIKE '%$q%' OR email LIKE '%$q%' ORDER BY ID DESC";
您可以通过将条件更改为
来使用您的代码if(isset($q)){
// your code
}
答案 2 :(得分:1)
我得到的错误是:注意:未定义索引:q警告:除以零
这意味着$ _POST [&#39; q&#39;]未定义您的代码应
if(isset($_POST['q'])) {
$pdo = Database::connect();
$q = $_POST['q'];
$sql = 'SELECT * FROM customers WHERE name LIKE '%$q%' OR email LIKE '%$q%' ORDER BY ID DESC';
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['name'] . '</td>';
echo '<td>'. $row['email'] . '</td>';
echo '<td>'. $row['mobile'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="read.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="update.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="delete.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
}
Database::disconnect();
}
?>
不要忘记添加html表单