为什么我的代码没有从我的SQL数据库正确输出信息


Why does my code not output the information from my SQL database correctly?

我正试图从我的sql数据库表输出信息到我的网页。

这是我的表的结构。

Name      Type              Null    Default
Name      text              No      None
Picture   varchar(30)       No      None
Date      date              No      None
Price     int(11)           No      None

这是我用来查询数据库和输出数据的:

mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM Events";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
while ($i < $num) {
$Name=mysql_result($result,$i,"Name");
$Picture=mysql_result($result,$i,"Picture");
$Date=mysql_result($result,$i,"Date");
$Price=mysql_result($result,$i,"Price");

echo "<b>$Name</b><br>$Picture</br><br$Date</br><br>$Price</br>";
$i++;
}
?>

这是输出到网页上的内容:

$Name
$Picture
$Price
"; $i++; } ?>

下面是需要做的.....

1。忘记mysql -它容易注射和古老的历史-使用mysqli_PDO

2。使用合适的链获取数据…

3。完井时,close连接

<?php
$mysqli = new mysqli($host,$username,$password,$database);
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s'n", mysqli_connect_error());
    exit();
}
$query = "SELECT * FROM Events";
if ($result = $mysqli->query($query)) {
    /* fetch object array */
    while ($row = $result->fetch_row()) {
        $Name=$row["Name"];
        $Picture=$row["Picture"];
        $Date=$row["Date"];
        $Price=$row["Price"];
        echo "<b>$Name</b>
              <br>$Picture<br>
              <br>$Date</br>
              <br>$Price</br>";
    }
    /* free result set */
    $result->close();
}
/* close connection */
$mysqli->close();
?>

参考:http://php.net/manual/en/class.mysqli-result.php

输入以下行错误:

$num=mysql_numrows($result);

缺少下划线,应该是:

$num=mysql_num_rows($result);

这是第一个错误,第二个在这一行:

echo "<b>$Name</b><br>$Picture</br><br$Date</br><br>$Price</br>";

查看<br$Date,,你会发现在它之前缺少一个>,应该是

 <br>$Date

最后的提示:你应该停止使用mysql函数,并开始使用mysqli或PDO作为PHP.net建议,因为mysql扩展是旧的,没有改进。如果你不想学习新的东西,可以考虑使用mysqli,它可以非常类似于使用mysql(在语法上),但有更多的改进。

你可以这样编辑你的代码:

while($row = mysql_fetch_array($result))
{
  $Name = $row["Name"];
  $Picture = $row["Picture"];
  $Date = $row["Date"];
  $Price = $row["Price"];

  echo "<b>$Name</b><br>$Picture</br><br>$Date</br><br>$Price</br>";
}