PHP Tutorial


Working with MySQL database


What is MySQL?

MySQL is an open source fast, reliable, and easy to use relational database management system. By relational it means that it stores data in separate tables rather than putting all the data in one. Database is required to be used in many application for example you want to store the information asked in the online form by the customer, online store or forums. To use MySQL download for free here: http://www.mysql.com/downloads/index.html. or if you have installed xampp which is also free then it is already there. And to access the MySql database you can either go through the command prompt or use phpMyAdmin which is installed with xampp. You can access the same through http://localhost/phpmyadmin

PHP and MySQL

PHP and MySQL both are open source and if used together creates a cross-platform program i.e. you can develop in Windows and serve on a Unix platform server.


Connecting to the database server

Lets start working with the database using PHP. To work with database one needs to connect with the MySQL Server. And once the work with the database is complete you need to close the connection with the database.


Following is the code example to open and close the MySQL connection using PHP

<?php

//Connects to your Database Server
$connection = mysql_connect(“localhost”,”root”,”xyz123”);
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}

//Disconnect from your Database Server
mysql_close($connection);

?>




Connecting to the database

After the connection with the database server is open you need to select the database you want to work with


Following is the code example to connect with the database using PHP

<?php

//Connects to your Database Server
$connection = mysql_connect(“localhost”,”root”,”xyz123”);
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}

//Connects to your Database
mysql_select_db("Database_Name") or die(mysql_error());

//Disconnect from your Database Server
mysql_close($connection);

?>




Create new database

if the database is not already created you can create the same through phpMyAdmin, command line of MySQL and through php code itself.


Following is the code example to create new database using PHP

<?php

//Connects to your Database Server
$connection = mysql_connect(“localhost”,”root”,”xyz123”);
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}

//Create New Database
if (mysql_query("CREATE DATABASE db",$connection))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

//Disconnect from your Database Server
mysql_close($connection);

?>




Back - PHP Tutorial : First PHP Program Next - PHP Tutorial : Working with Tables