PHP SQL Array

PHP SQL Array is the set of collection of one or more similar variable under single name.

PHP SQL Array

PHP SQL Array

     

PHP SQL Array is the set of collection of one or more similar variable under single name. Usually we have different type of values whose datatypes are same, Array is used as substitute for those variable, which have the same datatypes and store the data as element in array.

Understand with Example

This example illustrates how to create array in the operation of sql for php application. To start with the example, we create a emp_table with given required fieldnames and values. The Select query fetches all the records from table 'emp_table'.

Table: emp_table

 

To execute the sql query in PHP, we create sql_array.php. The sql_array.php  starts with the <?php and end with ?>, which consists of con variable. The con var is used to initialized with the mysql_connect ( ) function, which accept the parameter local host, user and password in order to authenticate the connection between the PHP and MySQL. In case the specified parameter are not valid, the con fail to establish the connection between the PHP and MySQL. Otherwise the connection bridge is  built successfully between the PHP and MySQL. In this example we create a $emp_name[] and $emp_designation[] of array type. In this array type variable we put the value of row[0] and row[1] which fetched records from database table. The echo print the record details of table 'emp_table' whose emp_id is "1" in the HTML table.

Source Code of sql_array.php 

<?php
  $con = mysql_connect("localhost","root","root");
  if (!$con){
  die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("test", $con);

  $sql = "SELECT emp_name, emp_designation FROM emp_table WHERE emp_id=1";

  $result = mysql_query($sql, $con);

  while($row=mysql_fetch_row($result)){
  echo $emp_name[] = $row[0" || ";
  echo $emp_designation[] = $row[1];
  }
  mysql_free_result($result);

  mysql_close($con);
?>

Download Source Code

Output: