PHP,从数据库中获取数据

问题描述:

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

I want to retrieve data from a database with PHP and show it on a website.

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

This code does not work correctly. I want to display all cars that are Chevy on my database.

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

How do I get data from the database with PHP?

您不是要查询数据库,所以不会给您结果

这是它的工作方式

1)通过 mysql_connect() 连接到数据库

1) connect to the database by mysql_connect()

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

2),而不是选择 mysql_select_db()

2) than select the database like mysql_select_db()

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

3)您需要使用 mysql_query()

3) you need to use 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更容易阅读,您可以在这里学习面向MySQL开发人员的PDO指南 面向初学者的Pdo(为什么?以及如何?)

Note:

Mysql_* function are deprecated so use PDO or MySQLi instead . I would suggest PDO its lot more easier and simple to read you can learn here PDO Tutorial for MySQL Developers also check Pdo for beginners ( why ? and how ?)