Create a Connection to a MySQL Database:
Before you can get content out of your MySQL database, you must know how to establish a connection to MySQL from inside a PHP script. The following code explained the following concepts,
1. Connection to the database
2. Select a database
3. Execute the query
4. Fetch tha data
5. Close the connection
Sample Code:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect 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: ".
$row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>
Before you can get content out of your MySQL database, you must know how to establish a connection to MySQL from inside a PHP script. The following code explained the following concepts,
1. Connection to the database
2. Select a database
3. Execute the query
4. Fetch tha data
5. Close the connection
Sample Code:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect 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: ".
$row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>
0 comments:
Post a Comment
Share your thoughts here...