After learning the basic structure of PHP, the next step is connecting to a MySQL database. This tutorial walks through every step — connecting, selecting a database, running queries, and closing the connection.
Step 1 — Connect to MySQL
Use mysql_connect(hostname, username, password) to open a database connection.
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect");
echo "Connected to MySQL";
?>
If the connection succeeds you will see Connected to MySQL. If not, verify your hostname, username, and password.
Step 2 — Select a Database
Use mysql_select_db() with the connection object to choose which database to work with.
<?php
$database = mysql_select_db("phptutorials", $conn)
or die("Could not select phptutorials");
?>
Step 3 — Run a Query
mysql_query() executes SQL and returns a result set. mysql_fetch_array() retrieves rows one at a time.
<?php
$result = mysql_query("SELECT id, name, address FROM students");
while ($row = mysql_fetch_array($result)) {
echo "ID: " . $row['id']
. " Name: " . $row['name']
. " Address: " . $row['address']
. "<br>";
}
?>
Step 4 — Close the Connection
<?php mysql_close($conn); ?>
Full Example
<?php
$hostname = "localhost";
$username = "root";
$password = "";
// Connect to MySQL
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect");
echo "Connected to MySQL";
// Select database
$database = mysql_select_db("phptutorials", $conn)
or die("Could not select phptutorials");
// Run query and fetch data
$result = mysql_query("SELECT id, name, address FROM students");
while ($row = mysql_fetch_array($result)) {
echo "ID: " . $row['id']
. " Name: " . $row['name']
. " Address: " . $row['address']
. "<br>";
}
// Close connection
mysql_close($conn);
?>
Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.