MySQL查询不输出仅结果标题

时间:2017-12-08 00:03:17

标签: php html css mysql ajax

我目前正在练习PHP和AJAX,我正在尝试创建一个允许用户实时搜索数据库中的产品库存的应用程序。当用户在其中一个条目中键入一个字母时,标题会显示,但不会显示数据。我不确定我做错了但是我会让你们做出判断。代码如下:

  

Results.php - 下面

 <!DOCTYPE html>
<html>
<head>
<title>Results</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect("localhost", "username", "password", "databaseName");
//edited out for safety 

if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"jakeholc_ajaxtest");

$sql="SELECT * FROM stock WHERE name LIKE '%{$q}%'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Product name</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
</tr>";

if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['descr'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "</tr>";
}
}


echo "</table>";
mysqli_close($con);
?>

2 个答案:

答案 0 :(得分:2)

$q = intval($_GET['q']);尝试将您的输入转换为整数。删除此行。

答案 1 :(得分:0)

您可以尝试我的代码。我已经测试了这个。每次输入文本时,输入的文本都会与数据库中的某些记录匹配,如果匹配的记录匹配,则会显示与输入文本匹配的记录。希望这会有所帮助:)请注意,以下代码是“ajax_search.php”的内容。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#search").keyup(function() {
var name = $('#search').val();
if (name == "") {
$("#display").html("");
}
else {
$.ajax({
type: "POST",
url: "ajax_search.php",
data: {
search: name
},
success: function(html) {
$("#display").html(html).show();
}
});
} 
}); 
});
</script>   
</head>

<body>
<input type="text" id="search" placeholder="Search Product Here..." />
<?php
$con = mysqli_connect("localhost","username","password","databasename"); 
if (mysqli_connect_errno()) {
echo "Database Connection Failed: " . mysqli_connect_error();
}
?>
<?php
if (isset($_POST['search'])) {
$key = $_POST['search'];
$query = "SELECT * FROM stock  WHERE name LIKE '%$key%' OR descr LIKE '%$key%' OR price LIKE '%$key%' OR quantity LIKE '%$key%' ";
$execute_query = mysqli_query($con, $query);
echo "<table border='3px' cellpadding='3px' cellspacing='3px' bgcolor='skyblue' align='center'>";
echo "<tr>";
echo "<td>Product Name</td>";
echo "<td>Description</td>";
echo "<td>Price</td>";
echo "<td>Quantity</td>";
echo "</tr>";
while ($result = mysqli_fetch_array($execute_query)) {
echo "<tr>";
echo "<td>".$result['name']."</td>";
echo "<td>".$result['descr']."</td>";
echo "<td>".$result['price']."</td>";
echo "<td>".$result['quantity']."</td>";
echo "</tr>";
}}
mysqli_close($con);
?>
</table>
<div id="display">
<!-- Ouput will display here -->
</div>
</body>
</html>