Thursday, May 30, 2013

Get data from MySQL in PHP



To get data from MySQl is a base for PHP programming.
First we create a table in XAMPP: (go to http://localhost/phpmyadmin/
or http://localhost/xampp if you installed XAMPP)
CREATE TABLE income
(
   username VARCHAR(20) NOT  NULL,
   income_type CHAR(1) NOT NULL,
    income DECIMAL(18,2)NOT NULL
   ) ENGINE  =  MYISAM;


Then insert some data:
INSERT INTO income(username,income_type,income) VALUES
 ('j1','A','2000.0' ),
 ('j2','B','2050.5' ),
 ('j3','A', '300.0'),
 ('j4','B', '400.0');


Now we fetch  this 2d array data using PHP:
<?php
//Connect to MySQL server
   $conn = @mysql_connect("localhost","root","") || die("MySQL connection error");
//Connect to database test
  @mysql_select_db("test") || die("test database not exist!"); 
   $income_data = Array();

 $sql = 'SELECT * FROM income';
  $result = mysql_query($sql);
   while($row = mysql_fetch_assoc($result)){
      // Assign  MySQL result to a multi-dimensional array
       $income_data[] = $row;
    }
//Extract data from the multi-dimensional  array
echo '<h2>';
echo 'username, income_type, income <br />';
foreach($income_data as $my_data){
       foreach($my_data as $key=>$data) echo  $data.',   ';
        echo '<br />';
}
echo '</h2>';
?>

No comments:

Post a Comment