Kristin Shehorn
Kristin Shehorn

Reputation: 1

PHP Coding to Connect MYSQL Issues

I am creating a database to make my 'PHP' website but I couldn't do this. My website is cruzapp that is related to rideshare companies and changing it in to php to get details about our users. But I can't connect MYSQL by using the following PHP code:

?php
$username = "name";
$password = "password";
$hostname = "host"; 

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
 or die("Not connected to MySQL");
echo "Connected to MySQL<br>";

//select a database to work with
$selected = mysql_select_db("examples",$dbhandle) 
  or die("Could not select examples");

//execute the SQL query and return records
$result = mysql_query("SELECT id, model,year FROM cars");

//fetch tha data from the database 
while ($row = mysql_fetch_array($result)) {
   echo "ID:"$row{'id'}." Name:".$row{'model'}."Year: ". //display the results
   $row{'year'}.<br>";
}
//close the connection
mysql_close($dbhandle)
?>

Can anyone help me to debug this code? I will be very thankful to you.

Upvotes: 0

Views: 48

Answers (2)

Areeb
Areeb

Reputation: 554

Try this one out. It uses MySQLi with error echoing.

<?php

$username = "name";
$password = "password";
$hostname = "host";
$database = "examples";

$con = mysqli_connect($hostname, $username, $password, $database);

if (!$con) {
    exit("Connection failed: " . mysqli_connect_error());
}

$result = mysqli_query($con, "SELECT id, model,year FROM cars");

if (mysqli_error($con)) {
    exit("Error: " . mysqli_error($con));
}

while ($row = mysqli_fetch_array($result)) {
    echo "ID:" . $row['id'] . " Name:" . $row['model'] . "Year: " . $row['year'] . "<br>";
}

mysqli_close($con);

Upvotes: 1

Saquib Lari
Saquib Lari

Reputation: 190

First of all you should not use mysql because with PHP 7 mysql extension does not work anymore. so you must consider to change it to mysqli or PDO. PDO is recommended. Any how for a quick fix $selected = mysql_select_db($dbhandle,"examples") do this and also check all your values like hostname database name table name and make sure there are no mistakes.

Upvotes: 0

Related Questions