簡體   English   中英

PHP,從數據庫中獲取數據

[英]PHP, get data from the database

我想用 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 從數據庫中獲取數據?

你不是在查詢數據庫,所以它不會給你結果

這是它的工作原理

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 它更容易和更容易閱讀你可以在這里學習MySQL 開發人員的 PDO 教程也檢查PDO 初學者(為什么?以及如何?)

<?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>"; 
 ?> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM