我正在使用一个简单的表单,使用下面的PHP从数据库返回值,如何在行中返回其他值?
目前它正在返回产品ID,我也希望返回产品名称和描述。
<?php
$db = new mysqli("localhost", "root", "", "master");
if (isset($_GET['keywords'])) {
$keywords = $db->escape_string($_GET['keywords']);
$query = $db->query("
SELECT productID, productName
FROM promo
WHERE productID LIKE '%{$keywords}%'
OR productID LIKE '%{$keywords}%'
");
?>
<div class="resul-count">
Found <?php
echo $query->num_rows;
?> Results.
</div>
<?php
if ($query->num_rows) {
while ($r = $query->fetch_object()) {
?>
<div class="result">
<a href="#"><?php
echo $r->productID;
?></a>
</div>
<?php
}
}
}
?>
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="./search.php" method="get">
<label>Search By Product ID:
<input type="text" name="keywords">
</label>
<input type="submit" value="search" autocomplete="off">
</form>
</body>
</html>
答案 0 :(得分:1)
首先,如果您希望它返回如下所示的值,则需要将产品描述添加到select语句中:
<?php
$db = new mysqli("localhost", "root", "", "master");
if (isset($_GET['keywords'])) {
$keywords = $db->escape_string($_GET['keywords']);
$query = $db->query("
SELECT productID, productName, productDescription
FROM promo
接下来,这个WHERE子句是多余的。您使用相同的搜索搜索每个项目两次
WHERE productID LIKE '%{$keywords}%'
// OR productID LIKE '%{$keywords}%' -- redundant code. same as the first test.
");
?>
<div class="resul-count">
Found <?php echo $query->num_rows;?>
Results.
</div>
<?php
if ($query->num_rows) {
while ($r = $query->fetch_object()) {
?>
<div class="result">
<a href="#"><?php
echo $r->productID;
最后你只是回应了产品ID。如果你想要其他两个项目,你需要回复它们:
echo $r->productName;
echo $r->productDescription;
?></a>
</div>
<?php
}
}
}
?>
将所有这些放在一起:
<?php
$db = new mysqli("localhost", "root", "", "master");
if (isset($_GET['keywords'])) {
$keywords = $db->escape_string($_GET['keywords']);
$query = $db->query("
SELECT productID, productName, productDescription
FROM promo
WHERE productID LIKE '%{$keywords}%'
// OR productID LIKE '%{$keywords}%' -- redundant code. same as the first test.
");
?>
<div class="resul-count">
Found <?php echo $query->num_rows;?>
Results.
</div>
<?php
if ($query->num_rows) {
while ($r = $query->fetch_object()) {
?>
<div class="result">
<a href="#">
<?php
echo $r->productID;
echo $r->productName;
echo $r->productDescription;
?>
</a>
</div>
<?php
}
}
}
?>