MySQL从数据库中检索不检索多行

时间:2013-05-22 19:58:18

标签: php mysql

我正在尝试从用户输入中使用LIKE查询检索所有数据并将其与数据库匹配,它可以工作,但只返回一条记录,但我在表中有很多记录。

返回它可以找到的最接近的记录,

所以说例如我有2条记录,其中ItemDesc字段包含字符'The',当我在输入框中搜索'The'并单击submit时,它返回最接近的(最早创建的)记录,当它应该返回时两者。

<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";    
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to      MySQL");

mysql_select_db("a3355896_book") or die("Unable to connect to database");

$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'"; 
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>

抱歉应该包含检索:

<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";

}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}

&GT?;    

1 个答案:

答案 0 :(得分:1)

您实际上并未在此处访问数据 - 您需要迭代结果集。

$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
    //Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
    $row = mysql_fetch_assoc($result);
    //do stuff with "row"
}

除非您这样做,否则您只是选择不将其包含在您的snippit中。让我们知道:))

- Edit-- 首先,我道歉 - 旧习惯我建议您使用mysql_fetch_assoc而不是mysqli函数集。

尝试使用fetch_assoc或fetch_array函数,它可以解决您的问题。我从来没有使用过你使用的方法,我认为它已被弃用了一段时间。 看看这里: http://php.net/manual/en/mysqli-result.fetch-assoc.php

相关问题