0

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.

4
  • 2
    do not use mysql. use mysqli or pdo Commented Feb 17, 2017 at 11:11
  • 2
    1. Don't use MySQL, instead switch to MySQLi or PDO. 2. Use mysqli_error() and mysqli_connect_error() to debug. Commented Feb 17, 2017 at 11:11
  • Which of the echos did you get when you try to connect? Commented Feb 17, 2017 at 11:14
  • 1
    Make sure your database connection credentials are correct. Commented Feb 17, 2017 at 11:15

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

do not forget to bind your statements. PDO is much better with prepared statements
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.