2

我想用 PHP 从数据库中检索数据并将其显示在网站上。

此代码无法正常工作。我想在我的数据库中显示所有雪佛兰汽车。

<?php
$db = mysqli_connect("localhost","myusername",
"mypassword","database");

if (mysqli_connect_errno()) { 
    echo("Could not connect" .
      mysqli_connect_error($db) . "</p>");
    exit(" ");
}

$result = mysqli_query($query);

if(!$result){
  echo "<p> Could not retrieve at this time, please come back soon</p>" .   
    mysqli_error($dv);
}

$data = mysql_query("SELECT * FROM cars where carType = 'Chevy' AND active = 1")
  or die(mysql_error());

echo"<table border cellpadding=3>";
while($row= mysql_fetch_array( $data ))
{
  echo"<tr>";
  echo"<th>Name:</th> <td>".$row['name'] . "</td> ";
  echo"<th>ImagePath:</th> <td>".$row['imagePath'] . " </td></tr>";
  echo"<th>Description:</th> <td>".$row['description'] . "</td> ";
  echo"<th>Price:</th> <td>".$row['Price'] . " </td></tr>";
}
echo"</table>";
?>

如何使用 PHP 从数据库中获取数据?

4

2 回答 2

5

你没有查询数据库,所以它不会给你结果

这就是它的工作原理

1)通过以下方式连接到数据库mysql_connect()

mysql_connect("localhost", "username", "password") or die(mysql_error()); 

2)比选择数据库喜欢 mysql_select_db()

mysql_select_db("Database_Name") or die(mysql_error()); 

3)你需要使用mysql_query()

 $query = "SELECT * FROM cars where carType = 'chevy' AND active = 1";
 $result =mysql_query($query); //you can also use here or die(mysql_error()); 

看看是否有错误

4) 比mysql_fetch_array()

  if($result){
         while($row= mysql_fetch_array( $result )) {
             //result
        }
      }

所以试试

$data = mysql_query("SELECT * FROM cars where carType = 'chevy' AND active = 1")  or die(mysql_error()); 
 echo"<table border cellpadding=3>"; 
 while($row= mysql_fetch_array( $data )) 
 { 
    echo"<tr>"; 
    echo"<th>Name:</th> <td>".$row['name'] . "</td> "; 
    echo"<th>ImagePath:</th> <td>".$row['imagePath'] . " </td></tr>"; 
    echo"<th>Description:</th> <td>".$row['description'] . "</td> "; 
    echo"<th>Price:</th> <td>".$row['Price'] . " </td></tr>"; 
 } 
 echo"</table>"; 
 ?> 

笔记:

Mysql_*函数已弃用,因此请使用PDOorMySQLi代替。我建议 PDO 更容易阅读,你可以在这里学习PDO Tutorial for MySQL Developers也检查Pdo for初学者(为什么?以及如何?)

于 2012-12-01T06:05:37.723 回答
2
<?php 
 // Connects to your Database 
 mysql_connect("hostname", "username", "password") or die(mysql_error()); 
 mysql_select_db("Database_Name") or die(mysql_error()); 
 $data = mysql_query("SELECT * FROM cars where cars.carType = 'chevy' AND cars.active = 1") 
 or die(mysql_error()); 
 Print "<table border cellpadding=3>"; 
 while($row= mysql_fetch_array( $data )) 
 { 
 Print "<tr>"; 
 Print "<th>Name:</th> <td>".$row['name'] . "</td> "; 
 Print "<th>ImagePath:</th> <td>".$row['imagePath'] . " </td></tr>"; 
 Print "<th>Description:</th> <td>".$row['description'] . "</td> "; 
 Print "<th>Price:</th> <td>".$row['Price'] . " </td></tr>"; 
 } 
 Print "</table>"; 
 ?> 
于 2012-12-01T06:05:52.607 回答