PHP和MySQL:导致查询排除表中第一条记录的原因: 例如,我有一个这样的脚本:
$query = "SELECT * FROM cars WHERE car_name = 'BMW'";
$results = mysql_query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>Vehicle Name:<th>";
echo "</tr>";
while($row = mysql_fetch_array($result)){
$name = $row['car_name'];
echo "<tr>";
echo "<td>$name<td>";
echo "</tr>";
}
echo "</table>";
除第一行外,所有行都会被返回。请帮助一个兄弟。
答案 0 :(得分:0)
修改强>
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same name,
you must use the numeric index of the column or make an alias for the
column. For aliased columns, you cannot access the contents with the
original column name
您正在使用mysql_fetch_array,这就是它在文档中所说的内容。我从不使用mysql *函数,所以我不会很快就跳到这种类型的结论。使用mysql_fetch_assoc($results)
,我99%肯定会解决您的问题。之所以会有所不同,可以在文件上面的段落中找到。我假设您的第一行与以下行中的至少一行相同。这意味着你很可能错过的不仅仅是第一个。可能是也可能不是。
结束编辑
在代码中添加4件事。
echo "<tr>";
echo "<th>ID</th>"; // THIS
echo "<th>Vehicle Name:</th>"; // Add closing tags........
echo "</tr>";
echo mysql_num_rows($results); // THIS (compare this to your MYSQL output row count)
while($row = mysql_fetch_array($results)){ **THIS... you have $results set with query, but $result here*** make sure both are $results OR $result
$id = $row['YOUR_AI_ID']; // THIS
$name = $row['car_name'];
echo "<tr>";
echo "<td>$id</td>"; // THIS
echo "<td>$name</td>"; // Add closing tags.......
echo "</tr>";
}
立即行动吧。回来看看结果。
答案 1 :(得分:0)
不是答案,但评论时间太长:
让我们在您的餐桌上cars
巅峰
什么
$qs = array(
array('total #rows', 'SELECT Count(*) FROM cars'),
array('#BMW', "SELECT Count(*) FROM cars WHERE car_name='BMW'"),
array('#LIKE BMW', "SELECT Count(*) FROM cars WHERE car_name LIKE '%BMW%'"),
array('#car_names', "SELECT Count(*) FROM (SELECT distinct car_name as foo FROM cars) as bar")
);
foreach( $qs as $query ) {
echo $query[0], "<br />\r\n";
$result = mysql_query($query[1]) or die(mysql_error());
while ( false!==($row=mysql_fetch_row($result)) ) {
echo ' ', $row[0], "\r\n";
}
}
如果放在脚本中而不是发布的代码中打印? 输出应该是
total #rows<br />
6
#BMW<br />
2
#LIKE BMW<br />
3
#car_names<br />
4
BTW:不推荐使用mysql_ *扩展名,
见http://docs.php.net/manual/en/mysqlinfo.api.choosing.php