PHP Mysql Database Connection
PHP Mysql Database Connection is used to build a connection between the PHP on the server-side and Mysql on the backend.
Understand with Example
The Tutorial illustrate an example from PHP Mysql Database Connection. To understand and grasp the example we create a table 'Stu' with specified fieldnames and datatypes respectively. The table 'Stu' has a primary key id.
Create table Stu:
CREATE TABLE `stu` (
`id` int(11) NOT NULL ,
`name` varbinary(10) default NULL,
`class` int(11) default NULL,
PRIMARY KEY (`id`)
);
|
Create table Lib:
The create table is used to create a table 'lib'.
CREATE TABLE `lib` ( `Id` int(11) default NULL, 'libno` int(11) default NULL); |
Insert data into Stu:
The insert into adds the records or rows value into table Stu and lib.
INSERT INTO `stu` VALUES (1,'Ajay',12); INSERT INTO `stu` VALUES (2,'Bhanu',12); INSERT INTO `stu` VALUES (3,'Komal',12); INSERT INTO `stu` VALUES (4,'Rakesh',12); INSERT INTO `stu` VALUES (5,'Santosh',12); INSERT INTO `stu` VALUES (6,'Tanuj',12); |
Insert data into lib:
INSERT INTO `lib` VALUES (1,101); INSERT INTO `lib` VALUES (2,102); INSERT INTO `lib` VALUES (3,103); INSERT INTO `lib` VALUES (4,104); INSERT INTO `lib` VALUES (5,105); |
php_sql_group_by.php:
The PHP server side include the code for server side scripting that is used to connect Mysql database. The server side scripting include a user and password that connect to the database. Before you can access data in a database, you must create a connection to the database.
<?php $host = "localhost"; $user = "root"; $password = "root"; $database = "komal"; $connection = mysql_connect($host,$user,$password)
or die("Could not connect: ".mysql_error());
mysql_select_db($database,$connection)
or die("Error in selecting the database:".mysql_error());
$sql="select s.id,s.name,s.class,l.libno from stu as s left join lib as l on s.id = l.id "; $sql_result=mysql_query($sql,$connection)
or exit("Sql Error".mysql_error());
$sql_num=mysql_num_rows($sql_result); echo "<table width =\"25%\" bgcolor=\"#F5F5FF\">";
echo "<tr>";
echo "<td ><b>Id</b></td> <td><b>Name</b></td>
<td><b>Class</b></td><td><b>libno</b></td>";
echo "</tr>";
while($sql_row=mysql_fetch_array($sql_result))
{
$id=$sql_row["id"];
$name=$sql_row["name"];
$class=$sql_row["class"];
$libno=$sql_row["libno"];
echo "<tr><td>".$id."</td>"; echo "<td>".$name."</td>"; echo "<td>".$class."</td>"; echo "<td>".$libno."</td></tr>"; } echo "</table>" ?> |
Result
| Id | Name | Class | libno |
| 1 | Ajay | 12 | 101 |
| 2 | Bhanu | 12 | 102 |
| 3 | Komal | 12 | 105 |
| 4 | Rakesh | 12 | 103 |
| 5 | Santosh | 12 | 104 |
| 6 | Tanuj | 12 |


