Create a Connection to a MySQL Database
Before
you can access data in a database, you must create a connection to the
database.
In PHP,
this is done with the mysql_connect() function.
Syntax
mysql_connect(servername,username,password);
|
Parameter
|
Description
|
|
servername
|
Optional. Specifies the
server to connect to. Default value is "localhost:3306"
|
|
username
|
Optional. Specifies the
username to log in with. Default value is the name of the user that owns the
server process
|
|
password
|
Optional. Specifies the
password to log in with. Default is ""
|
Note: There are more available parameters, but the ones listed above
are the most important. Visit our full PHP
MySQL Reference for more
details.
Example
In the
following example we store the connection in a variable ($con) for later use in
the script. The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
Closing a Connection
The
connection will be closed automatically when the script ends. To close the
connection before, use the mysql_close() function:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
Create
table and database
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
Insertion
mysql_query("INSERT
INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin',35)");
VALUES ('Peter', 'Griffin',35)");
selection
$result
= mysql_query("SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}






0 comments:
Post a Comment