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