Thursday, May 16, 2013

How to fetch records from Mysql Databae

The important technique in php is to fetch records from the database to list the data you need to used following php functions

  1. mysql_connect : to connect the mysql server with apache server
  2. mysql_select_db : to connect to a particular database in the mysql server
  3. mysql_query  : to fire a query in the database.
  4. mysql_num_rows to find the number of records in a recordset which is derived from query fired.
  5. mysql_fetch_array to fetch array from record set.
  6. mysql_fetch_assoc  to fetch row from associative array.
  7. mysql_fetch_row  to  fetch row from record set.
  8. mysql_fetch_object  to fetch the data as object generally use to fetch large data
  9. mysql_close close mysql connection   
Step by step we can use this functions to fetch data from Database 

 Using while loop


$recordset = mysql_query("select * from DBTABLE"); 
while ($record= mysql_fetch_array($recordset ) { 
                echo "user_id: ".$record["db_field_name"]."<br />\n"; // as in database
                echo "user_id: ".$record[0]."<br />\n"; // in key value as in array
                  }


This will fetch the database values from dbtable and retrieve list of particular db_field_name


Using for while loop and mysql_fetch_object
$recordset = mysql_query("select * from DBTABLE"); 


while ($record= mysql_fetch_object($recordset )) { 
         echo $record->db_field_name


Using for loop
$record= mysql_fetch_array($recordset );
$count=count($record) ;
for($i = 0;$i< $count ; $i ++)
{ 
                 echo "user_id: ".$record[$i]["db_field_name"]."<br />\n"; // as in database
}
 we will go through other function later...





Tuesday, May 14, 2013

function mysql_connect

The most important function that is used in the php coding is mysql_connect .

This is function used to connect Mysql server with Apache server (PHP).

The syntax for it goes as

mysql_connect ( localhost,username,password)

where the localhost refers to Mysql HOST

username :Mysql username
password ;Mysql password

Example of mysql_connect

<?php
    $link = mysql_connect("localhost", "username", "password")
        or die("Could not connect");
    print ("Connected successfully");
    mysql_close($link);
?>


Similar function which is used for connecting the Mysql server is mysql_pconnect

Mysql_pconnect establishes a persistent connection

In Mysql_connect after the script that calls it has finished it will be closed. but mysql_pconnect will continue to hold the connection until it is closed manually by the user.