PHP MySql无法正确检索数据

时间:2015-02-13 22:10:12

标签: php mysql mysqli

我试图从MySql数据库中检索一个表,但我的代码返回了错误的数据。这是我的代码

<?php 
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "net_trade";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno()) {
    die("Connection failed: " . mysqli_connect_error());
}


echo "<link rel='stylesheet' type='text/css' href='style.css'>";

echo "<h1>NET TRADE</h1>";
echo "<div align='center'>";
echo "<ul>";
echo "<li><a class='nav' href='inventory.php'>INVENTORY</a></li>";
echo "<li><a class='nav' href='supplier.php'>SUPPLIER</a></li>";
echo "<li><a class='nav' href='customer.php'>CUSTOMER</a></li>";
echo "<li><a class='nav' href='sales.php'>SALES</a></li>";
echo "</ul>";
echo "</div>";

echo "<form method='POST' action='create_supplier.html'>
      <input type='SUBMIT' class='style19' name='new_item' value='Add New Item'></form>";



echo "<table class='TFtable'>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Quantity</th>";
echo "<th>Name</th>";
echo "<th>Brand</th>";
echo "<th>Model</th>";
echo "<th>Serial</th>";
echo "<th>Date Supplied</th>";
echo "<th>Supplier</th>";
echo "</tr>";


$result = mysqli_query($conn, "SELECT * FROM inventory");

if (mysqli_num_rows($result) > 0) {


   while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
        echo "<tr>";
        echo "<td>".$row['0']."</td>";
        echo "<td>".$row['1']."</td>";
        echo "<td><a href='edit.php?id=".$row['0'].">".$row['2']."</a></td>";
        echo "<td>".$row['3']."</td>";
        echo "<td>".$row['4']."</td>";
        echo "<td>".$row['5']."</td>";
        echo "<td>".$row['6']."</td>";
        echo "<td>".$row['7']."</td>";
        echo "</tr>";
    }
mysqli_free_result($result);
}else {
    echo "0 results";
}
mysqli_close($conn);
echo "</table>";



?>

结果应该是这个......

enter image description here

但是我的代码会返回类似的内容..

enter image description here

结果从数据库表中跳过一行..这就是我的主要问题

1 个答案:

答案 0 :(得分:0)

我相信这一行在您的代码中已经过时了。

  echo "<td><a href='edit.php?id=".$row['0'].">".$row['2']."</a></td>";

你需要注意到href中匹配的双引号,这就是这个。

<td><a href="edit.php?id=12345">asd</a></td>

我认为你得到的是这个。

  <td><a href='edit.php?id=12345>asd</a></td>

请注意,您的href是以单引号启动的(Web浏览器可以容忍,但不是标准的),并且没有结束。

您可能希望代码看起来像这样。字符串连接不容易阅读,因此sprintf()可以更好地构成这种链接标记。

 echo sprintf ('<td><a href="edit.php?id=%d>%s</a></td>', $row[0], $row[2]);

专业提示:当结果奇怪时,​​请务必查看来源。