PHP, get data from the database

前端 未结 2 1337
臣服心动
臣服心动 2021-01-22 04:50

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

相关标签:
2条回答
  • 2021-01-22 05:38
    <?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>"; 
     ?> 
    
    0 讨论(0)
  • 2021-01-22 05:42

    you are not querying to database so it wont give you result

    this is how it works

    1) connect to the database by mysql_connect()

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

    2) than select the database like mysql_select_db()

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

    3) you need to use mysql_query()

    like

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

    to see if error

    4) and than mysql_fetch_array()

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

    so try

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

    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 ?)

    0 讨论(0)
提交回复
热议问题