PHP SQL Table

PHP SQL Table is used to create table in PHP. To create a table in PHP, we use Mysql_function () that include create table keyword which is used to create a table in PHP.

PHP SQL Table

PHP SQL Table

     

PHP SQL Table is used to create table in PHP. To create a table in PHP, we use Mysql_function () that include create table keyword which is used to create a table in PHP.

Understand with Example

The Tutorial covers an example on 'PHP SQL Table'. To grasp the example we create a sql_table.php begins with <?php and end  with ?>. The variable 'con' is used to assign the value of mysql_connect () function that accept the parameter like user, password and host. This helps you to authenticate the connection between the PHP and MySQL database. Once a successful connection is built between the PHP and database, you can create a table in PHP. 

 We must add and create a table statement. The Table "emp_table" create with three fields, "emp_id", "emp_name" and "emp_designation". The "emp_id" is integer type, not null, auto increment and primary key define, "emp_name" is varchar type and "emp_designation" has also varchar datatype define. We add records to the corresponding columns using insert into query.  The Select query fetches the records from table 'emp_table'. The echo print a table with required table fieldname ID, Name and Designation. The While loop execute and continue executing while the specified condition is true. In this example the while loop fetches the records corresponding to each column till the condition remains true. Finally the echo print the fetched rows values in table.

This example illustrates how to create table in php.

Table: emp_table

 

Source Code of sql_table.php 

<?php
  $mysql_db = "test";
  $mysql_user = "root";
  $mysql_pass = "root";
  $con = mysql_connect("localhost", $mysql_user, $mysql_pass);
  mysql_select_db($mysql_db, $con);

  $create_query = "CREATE TABLE emp_table (emp_id INT NOT NULL AUTO_INCREMENT, 
  emp_name VARCHAR(50),  emp_designation VARCHAR(50), PRIMARY KEY (emp_id))";
  mysql_query($create_query, $con);
  echo "Table <b>emp_table</b> Created Successfully!<br>";

  $insert = "INSERT INTO emp_table VALUES (1, 'sandeep', 'programmer')";
  $insert1 = "INSERT INTO emp_table VALUES (2, 'suman', 'sr. Gr Designer')";
  $insert2 = "INSERT INTO emp_table VALUES (3, 'ravi', 's/w developer')";
  mysql_query($insert, $con);
  mysql_query($insert1, $con);
  mysql_query($insert2, $con);
  echo "Data inserted successfull<br><br>";

  $result = mysql_query("SELECT * FROM emp_table");
  echo "<table border='1'>
  <tr>
  <th>ID</th>
  <th>Name</th>
  <th>Designation</th>
  </tr>";
  while ($row = mysql_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['emp_id'] . "</td>";
  echo "<td>" . $row['emp_name'] . "</td>";
  echo "<td>" . $row['emp_designation'] . "</td>";
  echo "</tr>";
  }
  echo "</table>";

  mysql_close($con);
?>

Download Source Code

Output: