我试图从具有两列的数据库中获取用户提交。一个用于艺术家,一个用于标题。我想从简单的表单中获取他们的输入,并将所有类似的结果输出到下一页的表格中。我已经包含了迄今为止我写的整个脚本。我在页面上没有收到任何错误,但我也没有得到任何结果。我花了好几天在网上看看我是否可以自己解决这个问题,但是我没有这么幸运。很抱歉这么粗鲁,但我是这个网站的新手,想要提供尽可能详细的信息。
<?php
include("db_connect.php");
// - get form data from "searchform.php"
$song_query = $_GET['song_query'];
// - column 1 and column 2 are all we're looking for in the db
// - title and artist are currently the two cols. Table is named
"song_list"
$col1 = "title";
$col2 = "artist";
$tablename = "song_list";
echo "<H1>Search results</H1>";
if ($song_query == "") {
echo "What are you going to sing? You didn't enter a search term! Please
try again.";
exit;
}
// - pick the db connection out of the included file and give error if
failed.
mysqli_select_db($conn, $db_name) or die(mysqli_error());
// - cleans up string inputted by user to avoid harmful code insertion
into form
$song_query = strtoupper($song_query);
$song_query = strip_tags($song_query);
$song_query = trim($song_query);
// - set up parameters for accessing the query of the db
$sql = "SELECT $col1, $col2 FROM $tablename WHERE $col1, $col2 LIKE
'%$song_query%'";
$result = mysqli_query($conn, $sql);
if (isset($_GET['$result'])){
if (mysqli_num_rows($result) > 0){
echo "<table><tr>";
echo "<th>Artist</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['$result'] . "</td>";
echo "</tr>";
echo "</table>";
}
}
}
?>
答案 0 :(得分:0)
你错了SQL
,它正在运行时构建
$sql = "SELECT $col1, $col2 FROM $tablename WHERE $col1, $col2 LIKE
'%$song_query%'";
成为
$sql = "SELECT title, artist FROM $tablename WHERE title, artist LIKE
'%$song_query%'";
在这里查看WHERE title, artist LIKE
$song_query
从$_GET['song_query']
获取值,该值在运行时更改。
答案 1 :(得分:0)
此WHERE $col1, $col2 LIKE '%$song_query%'
是您需要说的无效语法
WHERE col1 LIKE '%something%' AND col2 LIKE '%something%'
所以这应解决问题
$sql = "SELECT $col1, $col2
FROM $tablename
WHERE $col1 LIKE '%$song_query%'
AND $col2 LIKE '%$song_query%'";
虽然这对SQL Injection Attack很开放 甚至if you are escaping inputs, its not safe! 使用prepared parameterized statements
$sql = "SELECT title, artist
FROM songlist
WHERE title LIKE ? AND artist LIKE ?";
$stmt = $conn->prepare($sql);
$val = sprintf('%%%s%%', $song_query);
$stmt->bind_param('ss',$val, $val);
$stmt->execute();
$stmt->bind_result($title, $artist);
echo "<table><thead><tr>";
echo "<th>Artist</th><td>Title</th>";
echo "</tr></thead><tbody>";
while ($stmt->fetch()) {
echo "<tr>";
echo "<td>$artist</td>";
echo "<td>$title</td>";
echo "</tr>";
}
echo "</tbody></table>";
另请注意,您在制作表格时犯了一些错误,我认为我已经修复过了。