PHP,从数据库中获取数据

时间:2012-12-01 06:04:00

标签: php mysql

我想用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从数据库中获取数据?

2 个答案:

答案 0 :(得分: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_*函数已弃用,因此请改用PDOMySQLi。我建议PDO更简单易读,你可以在这里学习PDO Tutorial for MySQL Developers并检查Pdo for beginners ( why ? and how ?)

答案 1 :(得分: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>"; 
 ?>