Thursday, 5 February 2015

Database Connection in PHP Db is mysql -- Fetch or get a single result value or single column value from a table in php


To fetch a single record: 

      $username="dbuser";
$password="dbpwd";
$database="dbname";

mysql_connect('localhost',$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

      $initqry = mysql_query("select empname from emp where empid=10");

$initchk = mysql_result($initqry, 0);   // Get single value as the empid if unique and primary key


  To get a result set  from a table method one :


           $qry="Select * from emp order by empname";
     $res=mysql_query($qry);
      $num=mysql_numrows($res);     /* Gives the number of records fetched

      $i=0;
     while($i<$monum){                       /* Reading each record */

$ename=mysql_result($res,$i,"empname");
$eid=mysql_result($res,$i,"empid");
$edesig=mysql_result($res,$i,"desig");
$esal=mysql_result($res,$i,"salary");

               if(strtoupper($ename)=='JAMES'){
            $uqry="update emp set salary=50000 where empid=$eid";
              mysql_query($uqry);
               }
$i++;
     }

  To get a result set  from a table method TWO :

Example #2 mysql_fetch_array() with MYSQL_NUM
<?php
mysql_connect
("localhost""mysql_user""mysql_password") or
    die(
"Could not connect: " mysql_error());mysql_select_db("mydb");
$result mysql_query("SELECT id, name FROM mytable");

while (
$row mysql_fetch_array($resultMYSQL_NUM)) {
    
printf("ID: %s  Name: %s"$row[0], $row[1]); 
}
mysql_free_result($result);?>
Example #3 mysql_fetch_array() with MYSQL_ASSOC
<?php
mysql_connect
("localhost""mysql_user""mysql_password") or
    die(
"Could not connect: " mysql_error());mysql_select_db("mydb");
$result mysql_query("SELECT id, name FROM mytable");

while (
$row mysql_fetch_array($resultMYSQL_ASSOC)) {
    
printf("ID: %s  Name: %s"$row["id"], $row["name"]);
}
mysql_free_result($result);?>
Example #4 mysql_fetch_array() with MYSQL_BOTH
<?php
mysql_connect
("localhost""mysql_user""mysql_password") or
    die(
"Could not connect: " mysql_error());mysql_select_db("mydb");
$result mysql_query("SELECT id, name FROM mytable");

while (
$row mysql_fetch_array($resultMYSQL_BOTH)) {
    
printf ("ID: %s  Name: %s"$row[0], $row["name"]);
}
mysql_free_result($result);?>

No comments:

Post a Comment