A PHP scripting block is executed on the server side, and the html result is sent to the browser.
Understand with Example
The Tutorial illustrate an example from PHP SQL Example. To understand and grasp the example we create a table 'stu' in Mysql that include the required 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`)
);
|
Insert data into Stu:
The insert into is used to add the records or rows to the table 'Stu'.
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); |
php_sql_example.shtml:
The PHP code is executed on the server side and sent the HTML result code to the browser. Before access the database records from table 'stu', you need to establish a connection with database. The PHP code include the host, user and database from which the table 'stu' records are retrieved. Once your connection is built, it returns the result obtain from select query in variable sql_result. The While Loop is used to execute the loop till the condition remains true. Otherwise it exists from the loop. The echo is used to print the records to the output text. To run the PHP code, the file must be saved with php extension.
<html> <body> <?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 * from stu"; $sql_result=mysql_query($sql,$connection)
or exit("Sql Error".mysql_error());
$sql_num=mysql_num_rows($sql_result); echo "<table width =\"20%\" bgcolor=\"#F5F5FF\">";
echo "<tr>";
echo "<td ><b>Id</b></td> <td><b>Name</b></td>
<td><b>Class</b></td>";
echo "</tr>";
while($sql_row=mysql_fetch_array($sql_result))
{
$id=$sql_row["id"];
$name=$sql_row["name"];
$class=$sql_row["class"];
echo "<tr><td>".$id."</td>"; echo "<td>".$name."</td>"; echo "<td>".$class."</td></tr>"; } echo "</table>" ?> </body> </html>
|
Result
| Id | Name | Class |
| 1 | Ajay | 12 |
| 2 | Bhanu | 12 |
| 3 | Komal | 12 |
| 4 | Rakesh | 12 |
| 5 | Santosh | 12 |
| 6 | Tanuj | 12 |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: PHP SQL Example
Post your Comment