【发布时间】:2019-10-26 14:08:14
【问题描述】:
所以我是 SQL、PHP 和 HTML 的新手。我正在尝试为我的数据库创建一个搜索系统,其中包含食品及其价格表。我到处寻找与我有同样问题的人,但似乎没有一个解决方案对我有帮助。
我已经在所有我能找到的论坛上进行了广泛搜索,YouTube 上的大量教程都无济于事。
主要PHP代码:
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<title>Lists of foods and prices! Input yours here!</title>
</head>
<body>
<h1>Insert your fav food!</h1>
<table>
<form action = "" method = "post">
<tr>
<td>Food: </td><td><input type="text" name="Food"></td></tr>
<tr>
<td>Price: </td><td><input type="integer" name="Price"></td></tr>
<tr>
<td>Supermarket: </td><td><input type="text" name="Supermarket"></td></tr>
</tr>
<tr>
<td><input type="submit" name = "submit"></td></tr>
</form>
</table>
<table>
<form action = "" method = "post">
<tr>
<td>Search: </td><td><input type="text" name="Search"></td></tr>
<tr>
<td><input type="submit" name = "Search"></td></tr>
</form>
</table>
<?php
if(isset($_POST["submit"])){
include 'dbconfig.php';
include 'New Text Document.js';
$Food = $_POST['Food'];
$Price = $_POST['Price'];
$Supermarket = $_POST['Supermarket'];
mysqli_query($conn,"INSERT INTO costsoffood VALUES('$Food', '$Price', '$Supermarket')");
}
if(isset($_POST["Search"])){
include 'dbconfig.php';
$search = $_POST["Search"];
$query="SELECT * FROM costsoffood WHERE Food LIKE %$search%";
$result=mysqli_query($conn,"SELECT * FROM costsoffood WHERE Food LIKE '%$search%'");
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
echo "<tr><td>". $row['food']."</td><td>". $row['price']."</td><td>".$row['supermarket']."</td></tr>";
}
echo "</table>";
}
else{
echo "no results";
}
}
?>
</body>
</html>
dbconfig.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dataone";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
【问题讨论】:
-
有什么问题?你没有在这里说你的问题实际上是什么
-
请阅读SQL injection。不要使用字符串连接构建查询,而是使用 prepared statements 和 bound parameters。请参阅 this page 和 this post 了解一些很好的示例。
-
你的字符串周围缺少引号
-
您需要启用错误报告。 How to get the error message in MySQLi?