• My PHP Pages

    This is a complete and free PHP programming course for beginners. Everything you need to get started is set out in section one below.

Jun 29, 2013

Posted by Unknown
No comments | 5:57 AM

In the last lesson we learned about how to make a connection to mysql database. To create either database or table first we need to make a connection to the database server.


Please read last post if you don't know how to create the connection to mysql server.

Creating  a Database

We have to use new method to execute sql queries.
mysql_query(connection,sql query sting)
  • connection- return value of mysql_connect() function
  • Sql query string - sql query that you need to execute

mysql_query() function returns a Boolean value if query execute successfully it will return true value else false value. Lets look at the code


//make connection
$con = mysql_connect("localhost","root","123");
//check connection
if(!$con)
{
die('Could not connect to the database:'.mysql_error());
}
//making sql query string
$sql="CREATE DATABASE my_database";

//Execute the mysql query and check is execution process is succeeded
if(mysql_query($con,$sql))
{
echo "Database Created..!";
}
else
{
echo "Error occurred while creating database :".mysql_error($con); 
}

//close connection
mysql_close($con);




Creating a table

Difference between creating table and database is just sql query sting value and you have to select database to create table using mysql_select_db() function. lets make simple code..



//make connection
$con = mysql_connect("localhost","root","123");
//check connection
if(!$con)
{
die('Could not connect to the database:'.mysql_error());
}

//select database
$db=mysql_select_db("my_database",$con);
 if(!$db)
{
die('Could not connect to the database:'.mysql_error());

}
//making sql query string
$sql="CREATE TABLE my_table(name varchar(10),phone int)";

//Execute the mysql query and check is execution process is succeeded
if(mysql_query($con,$sql))
{
echo "Table Created..!";
}
else
{
echo "Error occurred while creating table :".mysql_error($con); 
}

//close connection
mysql_close($con);


Try to make your own database and create some simple tables using it. in next post i will explain how to insert data using php..

Cheers 




0 comments :

Post a Comment