Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, July 11, 2018

constants , final and autoload functions [BCA Sem-3]


Q: What is Class constants ?
A constant is, just like the name implies, a variable that can never be changed. When you declare a constant, you assign a value to it, and after that, the value will never change. Normally, simple variables are just easier to use, but in certain cases constants are preferable, for instance to signal to other programmers (or your self, in case you forget) that this specific value should not be changed during runtime.
Class constants are just like regular constants, except for the fact that they are declared on a class and therefore also accessed through this specific class. Just like with static members, you use the double-colon (Scope resolution) operator to access a class constant. Here is a basic example
class user
{
    const DefaultUsername = "RAJARAM";
    const MinimumPasswordLength = 6;
}

echo "The default username is " . user::DefaultUsername;
echo "The minimum password length is " . user::MinimumPasswordLength;
?>

As you can see, it's much like declaring variables, except there is no access modifier - a constant is always publically available. As required, we immediately assign a value to the constants, which will then stay the same all through execution of the script. To use the constant, we write the name of the class, followed by the double-colon operator and then the name of the constant.

Q: Explain The "final" keyword
In some cases you may want to prevent a class from being inherited from or a function to be overridden. This can be done with the final keyword, which simply causes PHP to throw an error if anyone tries to extend your final class or override your final function.
A final class could look like this:
final class Animal
{
    public $name;
}
A class with a final function could look like this:
class Animal
{
    final public function Greet()
    {
        return "The final word!";   
    }
}
The two can be combined if you need to, but they can also be used independently, as seen in the examples above.

Q:EXPLAIN Autoloading Classes
The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.
If one class depends on another, if your application ever changes, you have to work extra hard to be sure that the relationships between your classes are maintainable. But with autoloading classes in PHP this may not be necessary.
·         __autoload( ) — Attempt to load undefined class , void __autoload ( string $class )
·         spl_autoload_register() - Register given function as __autoload() implementation


Example #1 Autoload example
This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>
Example #2 Autoloading with exception handling
This example throws an exception and demonstrates the try/catch block.
spl_autoload_register(function ($name) {
    echo "Want to load $name.\n";
    throw new Exception("Unable to load $name.");
});

try {
    $obj = new NonLoadableClass();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>
Example #3
Image.php
  class Image {
       
      function __construct() {
          echo 'Class Image loaded successfully
';
      }

  }
?>
Test.php
  class Test {
       
      function __construct() {
          echo 'Class Test working
';
      }

  }
?>
Myprg.php
function __autoload($class_name) {
    if(file_exists($class_name . '.php')) {
        require_once($class_name . '.php');   
    } else {
        throw new Exception("Unable to load $class_name.");
    }
}

try {
    $a = new Test();
    $b = new Image();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>

Wednesday, August 6, 2014

PAGING BY NUMBERS LENGTH

<?php
include("./connections/connect.php");
$sql="SELECT count(student.grno) from student";
$res=mysql_query($sql);

while($row=mysql_fetch_array($res,MYSQL_NUM))
{

$pages=$row[0]/5;
}
echo "No of pages....:",$pages;
echo "<table><TR>";
for($x=0;$x<=($pages*5);$x=$x+5)
{
echo "<TD><a href='paging.php?nor=".$x."'>",$x,"-",$x+5,"</a> | </td>";
}
echo "</table></TR>";

$sql = "SELECT STUDENT.GRNO,STUDENT.NAME,CITY.CNAME FROM STUDENT,CITY WHERE STUDENT.CITY=CITY.CID ORDER BY student.GRNO ASC LIMIT ".($_REQUEST["nor"]+1).", 5 ";
$res=mysql_query($sql);
echo "<table>";
while($row=mysql_fetch_row($res))
{
echo "<TR>";
foreach($row as $k=>$v)
{
echo "<TD>",$v,"</td>";
}
echo "</tr>";

}
echo "</table>";
?>


Tuesday, August 5, 2014

PAGING USING LETTERS

<html>
<head>
<title>Paging Using PHP</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';

echo "<table><TR>";
for($x=65;$x<91;$x++)
{
echo "<td><a href='pagingbyletter.php?letter=",chr($x),"'>".chr($x)."</a></td>";
}
echo "</tr></table>";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbpractice');
/* Get total number of records */
if(!isset($_REQUEST['letter']))
{
$_REQUEST['letter']='a';
}

$sql = "SELECT eid, ename,phone ".
"FROM tblemp where ename like '".$_REQUEST['letter']."%'";
echo $sql,"<BR>";
$retval = mysql_query( $sql, $conn );

while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "EMP ID :{$row['eid']} <br> ".
"EMP NAME : {$row['ename']} <br> ".
"EMP SALARY : {$row['phone']} <br> ".
"--------------------------------<br>";
}
mysql_close($conn);
?>

PAGING IN PHP

<html>
<head>
<title>Paging Using PHP</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';
$rec_limit = 5;

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbpractice');
/* Get total number of records */
$sql = "SELECT count(eid) FROM tblemp ";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
//record counter
$rec_count = $row[0];

if( isset($_GET{'page'} ) )
{
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}
else
{
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);

$sql = "SELECT eid, ename,phone ".
"FROM tblemp ".
"LIMIT $offset, $rec_limit";

$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "EMP ID :{$row['eid']} <br> ".
"EMP NAME : {$row['ename']} <br> ".
"EMP SALARY : {$row['phone']} <br> ".
"--------------------------------<br>";
}

if( $page > 0 )
{
$last = $page - 2;
echo "<a href=\"$_PHP_SELF?page=$last\">Last 10 Records</a> |";
echo "<a href=\"$_PHP_SELF?page=$page\">Next 10 Records</a>";
}
else if( $page == 0 )
{
echo "<a href=\"$_PHP_SELF?page=$page\">Next 10 Records</a>";
}
else if( $left_rec < $rec_limit )
{
$last = $page - 2;
echo "<a href=\"$_PHP_SELF?page=$last\">Last 10 Records</a>";
}
mysql_close($conn);
?>

Saturday, July 12, 2014

how to add facebook like button on your website

It's Simplest way of add facebook button in website

step 1: open this path http://www.howtoaddlikebutton.com/
step 2 : in that web page put your url in  input box
step 3 : Choose Your Design for facebook button or facebook box
step 4 : click on generate my code button and copy that code then enter it in your web page.

 
run your page you will find that facebook button is available in your page

Thursday, July 3, 2014

INSERT INTO MYSQL USING PHP SCRIPT


database name:student
tablename:stud
fields : name, email, gender

<form name = "frm1" action="#" method="post">
enter name : <input type="text" name="sname"><br>
enter email : <input type="text" name="email"><br>
enter gender :<input type="radio" name="sex" value="m">male <input type="radio" name="sex" value="f">female<br>
<input type="submit" name="submit" value="insert">
</form>

<?php
if(isset($_POST["submit"]))
{
$link=mysql_connect("localhost","root","");
mysql_select_db("student");
$name=$_POST["sname"];
$email=$_POST["email"];
$gender=$_POST["sex"];
$sql="insert into stud(name,email,gender) values('$name','$email','$sex')";
$res=mysql_query($sql);
if($res)
{
echo "<font color='green'>record inserted successfully";
}
else
{
echo "<font color='red'>Record not Inserted....";
}

}
//print_r($_POST);
?>


Thursday, June 26, 2014

print data by reusable code in PHP


database namd : student table name : stud table name : course Def: print data by reusable code and table name as per given can have any fields

<?php
$link=mysql_connect("localhost","root","");
mysql_select_db("student");
$res=mysql_query("select * from stud");
printdata($res);

echo "<hr>";
$res=mysql_query("select * from tblcourse");
printdata($res);

function printdata($datas)
{
echo "<table border=1>";
while($row=mysql_fetch_array($datas,MYSQL_NUM))
{
echo "<tr>";
foreach($row as $k=>$v)
{
echo "<td>",$v,"</td>";
}
echo "</tr>";
}
echo "</table>";

}
?>


Monday, June 23, 2014

mysql with php connection sample programme


database name :dbstud
table name : tblstud
fields
rno tinyint autoincrement and primary key
name varchar 20
gender enum "m","f"
city varchar 20

<?php
$link=mysql_connect("localhost","root","");

$db=mysql_select_db("dbstud");

$res=mysql_query("select *from tblstud");
echo $res,"<BR>";
echo "<table border=1>";
while($row=mysql_fetch_array($res,MYSQL_NUM))
{
echo "<TR bgcolor='yellow'>";
foreach($row as $k=>$v)
{

if($k == 2)
{
if($v=="f")
{
echo "<td bgcolor='pink'>Female</td>";
}
else
{
echo "<td bgcolor='cyan'>Male</td>";
}
}
else
{
echo "<td>",$v,"</td>";
}

}

echo "</TR>";
}
echo "<table>";
?>


Monday, September 20, 2010

queue by javascript




::queue using array::



::queue using array::


Friday, May 25, 2007

Read xml file using simplexml functions in PHP

first you have to create xml file


<ReportData>

<Record>

<CCode>client 2</CCode>

<DESTINATION>USA</DESTINATION>

<AIRWAYBILL>A222</AIRWAYBILL>

<AWB>AQ222</AWB>

<SUB>

<DATE>5/21/2007</DATE>

<TIME>12:24:04 PM</TIME>

</SUB>

</Record>



<Record>

<CCode>client 2</CCode>

<DESTINATION>USA</DESTINATION>

<AIRWAYBILL>A222</AIRWAYBILL>

<AWB>AQ222</AWB>

<SUB>

<DATE>5/21/2007</DATE>

<TIME>12:24:04 PM</TIME>

</SUB>

</Record>



<Record>

<CCode>client 2</CCode>

<DESTINATION>USA</DESTINATION>

<AIRWAYBILL>A222</AIRWAYBILL>

<AWB>AQ222</AWB>

<SUB>

<DATE>5/21/2007</DATE>

<TIME>12:24:04 PM</TIME>

</SUB>

</Record>

</ReportData>


now user this code for parsing read in with simplexml functions


 


if(!$xml=simplexml_load_file('report.xml'))

{

trigger_error('Error reading XML file',E_USER_ERROR);

echo "file loaded";

}

echo 'Displaying contents of XML file...<br />';

foreach($xml as $records){

echo '<B>CLINET CODE: </b>'.$records->CCode.'<B> DESTINATION: <b>'.$records->DESTINATION.'

<B>AIRWAY BILL: </b>'.$records->AIRWAYBILL.'<br />';

}


run it this will display result of cccode and destination and airwaybill

Tuesday, May 22, 2007

Read xml file using DOM in PHP

<ReportData>

<Record>

<CCode>client 2</CCode>

<DESTINATION>USA</DESTINATION>

<AIRWAYBILL>A222</AIRWAYBILL>

<AWB>AQ222</AWB>

<SUB>

<DATE>5/21/2007</DATE>

<TIME>12:24:04 PM</TIME>

</SUB>

</Record>

</ReportData>


save above as report.xml file and than


run below script its script using dom how


you can read data from an xml file


 


<?php

$doc = new DOMDocument();

$doc->load( 'report.xml' );



$Record = $doc->getElementsByTagName( "Record" );

foreach( $Record as $rec )

{

$ccode = $rec->getElementsByTagName( "CCode" );

$ccode= $ccode->item(0)->nodeValue;



$destination = $rec->getElementsByTagName("DESTINATION");

$destination = $destination->item(0)->nodeValue;



$airwaybill = $rec->getElementsByTagName("AIRWAYBILL");

$airwaybill = $airwaybill->item(0)->nodeValue;



$awb = $rec->getElementsByTagName("AWB");

$awb = $awb->item(0)->nodeValue;



$SUB = $rec->getElementsByTagName( "SUB" );

$SUB = $SUB->item(0)->nodeValue;





$date = $rec->getElementsByTagName( "DATE" );

$date = $date->item(0)->nodeValue;

$time = $rec->getElementsByTagName( "TIME" );

$time = $time->item(0)->nodeValue;



echo "$ccode - $destination - $airwaybill - $awb - $SUB - $date - $time <BR>";

}

?>

Monday, May 21, 2007

connect with ms-access and print the table of data in php

<?php

$db_conn = new COM("ADODB.Connection");

$connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("thedata.mdb").";";

$db_conn->open($connstr);

if($db_conn)

{

echo "connected";

}

else

{

echo "not conected";

}

$rS = $db_conn->execute("SELECT * FROM main1");


$cnt=0;

echo"<table>";

while (!$rS->EOF)

{



if($cnt%2 == 0 )

{

print "<tr bgcolor='#C0C0C0'><td>".$rS->Fields(0)."</td><td>". $rS->Fields(1)."</td><td>".$rS->Fields(2)."</td><td>".$rS->Fields(3)."</td><td>".$rS->Fields(4)."</td><td> ".$rS->Fields(5)."</td><td>".$rS->Fields(6)."</td></tr>\n";

}

else

{

print "<tr><td>".$rS->Fields(0)."</td><td>". $rS->Fields(1)."</td><td>".$rS->Fields(2)."</td><td>".$rS->Fields(3)."</td><td>".$rS->Fields(4)."</td><td> ".$rS->Fields(5)."</td><td>".$rS->Fields(6)."</td></tr>\n";

}

$cnt++;

$rS->MoveNext();

}

echo"</table>";

$rS->Close();

$db_conn->Close();

?>



its eassy that you have to just change your database name for run this script

Tuesday, April 24, 2007

Send Mail using PHP mail() function with Html Content

<?php


$headers = 'MIME-Version: 1.0' . "\r\n";

$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers

$headers .= 'From: Kals[sender] <krakholiya@gmail.com>' . "\r\n";

// Mail it

$sendx = mail($to, $subject, $content, $headers);


if( $sendx )

{



echo "<font color='red'>Mail Sended.</font>";



}

else

{

$message = "Not Sended. please try again.";

}


?>

upload images in PHP

<body>

<br>

<?php

include("../db_connection_xcart.php");


if($_POST['submit'])

{

$sql = "SELECT image_id FROM `xcart_products_images` ORDER BY `image_id` DESC";

$result = mysql_query($sql);

$num = mysql_num_rows($result);

$row = mysql_fetch_array($result);

if($num)

{

$image_id = $row['image_id'];





}

else

{

$image_id = "1_x";

}





$productid = $_POST['productid'];

$image_name = $image_id."_".$_FILES['location']['name'];

$location = "../images/T/".$image_name;

if(move_uploaded_file($_FILES['location']['tmp_name'], $location))

{



$insert = "insert into xcart_products_images values('null','".$_POST['productid']."','".$image_name."')";

mysql_query($insert);

echo "<div align='center'><font color='#00FF00'>File is successfully uploaded.</font></div>\n";





}

else

{

echo "Possible file upload attack!\n";

}

if($result = mysql_query($query_insert))

{

echo"<div align='center'><font color='#00FF00'>Added Succesfully</font></div>";

}

}

?>






<br>

<div align="center">

<table bgcolor="#FFFFFF" border="0"><form name="images" action="<?php $_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">

<tr>

<td height="66" colspan="2" class="sectionheading" align="center"><b>ADD Multiple images</b></td>

</tr>

<tr>



<td height="26" align="left">

<b>product id :&nbsp;</b>

<?php



$query = "SELECT productid , product FROM xcart_products";

$product= mysql_query($query);

echo "<select name='productid' >";



while ($row = mysql_fetch_array($product))

{



echo "<option value='".$row[0]."'>".$row['product']."</option>";

}

echo"</select>";

?>

</tr>

<tr>

<td height="26" align="left" colspan="2">

<b>Image Location :&nbsp;</b>

<br>

<input type="file" name="location" size="40"></td>

</tr>

<tr>

<td>&nbsp; </td>

</tr>



<td align="center"><input type="button" name="close" value="Close" onClick="javascript:void(window.close())">&nbsp;&nbsp;



<input type="submit" name="submit" value="Upload Image" />

</td>

</tr></form>

</table>

</div>

</body>

session register checking and redirecting pages...

logging script session is registered and than checked


<?php


if(session_is_registered ('user'))

{

session_destroy();

}

session_start();

session_name('user');


//session is registered and than checked....


session_register("reguser");

$reguser="$member_id";


?>


//check for user or webmasters.....


<?php



session_start();

if($_SESSION['reguser'])

{

$msg= "Logged in&nbsp;".$_SESSION['reguser'];

echo $msg;


exit();



}

if($_SESSION['webmaster'])

{

$msg= "Logged in Web Master Id no:".$_SESSION['webmaster'];

echo $msg;


exit();

}




?>


//redirect page by the header funtion as per user category


<?php


session_destroy();

if(session_is_registered('reguser'))

{

header("location: ./index.php");

}





if(session_is_registered('webmaster'))

{

header("location: ./index.php");

}
?>

Monday, April 16, 2007

How to treat table as data grid in the PHP

if(session_is_registered("admin"))

{

function showBookingList($sb,$m,$p,$offs,$orderstate)

{

$offset = $offs;

$querySelect = "select count(*) from tblordermanage";

$queryResult = query_select($querySelect,$nRows);

$count = mysql_result($queryResult,0,0);

$maxt = round($count/$offset,2);

$last = ceil($maxt);



if($p==1)

{

$start = 0;

$n = $p+1;

$first = "<a href=\"viewQuoted.php?page=1&orderstate=$orderstate\"><span class='w_text'><u>First</u></span></a>";

$next = "<a href=\"viewQuoted.php?page=$n&orderstate=$orderstate\"><span class='w_text'><u>Next</u></span></a>";

$previous = "<span class='caption'>Previous</span>";

$last = "<a href=\"viewQuoted.php?page=$last&orderstate=$orderstate\"><span class='w_text'><u>Last</u></span></a>";

$stp = $start+1;



if ($count==0)

{

$stp = 0;

$ltp = 0;

}

else if ($count<=$offset)

{

$ltp = $count;

$next = "<span class='caption'>Next</span>";

}

else

{

$ltp = $stp+$offset-1;

}

}

else if($p==$last)

{

$start = $p*$offset-$offset;

$pr = $p-1;

$first = "<a href=\"viewQuoted.php?page=1&orderstate=$orderstate\" class='caption'>First</a>";

$next = "<span class='caption'>Next</span>";

$previous = "<a href=\"viewQuoted.php?page=$pr&orderstate=$orderstate\" class='caption'>Previous</a>";

$last = "<a href=\"viewQuoted.php?page=$last&orderstate=$orderstate\" class='caption'>Last</a>";

$stp = $start+1;

$ltp = $count;

}

else if($p>1 and $p<$last)

{

$start = $p*$offset-$offset;

$n = $p+1;

$pr = $p-1;

$first = "<a href=\"viewQuoted.php?page=1&orderstate=$orderstate\" class='caption'>First</a>";

$next = "<a href=\"viewQuoted.php?page=$n&orderstate=$orderstate\" class='caption'>Next</a>";

$previous = "<a href=\"viewQuoted.php?page=$pr&orderstate=$orderstate\" class='caption'>Previous</a>";

$last = "<a href=\"viewQuoted.php?page=$last&orderstate=$orderstate\" class='caption'>Last</a>";

$stp = $start+1;

$ltp = $stp+$offset-1;

}





if(empty($orderstate))

{

$orderstate='Q';

}

$query1Select = "select * from tblordermanage where orderstate='".$orderstate."' and processstate='".Q."' order By arrivedate limit ". $start .",".$offset;



$query1Result = query_select($query1Select,$nRows);

$nch = 0;



if(mysql_num_rows($query1Result)>=1)

{

$str.="<tr>



<td align=\"right\">&nbsp&nbsp $first &nbsp&nbsp $previous &nbsp&nbsp $next &nbsp&nbsp $last</td>

</tr>

<tr>

<td align='left' colspan='2'>

<table border='0' width='100%'>

<tr>

<td width='22%' bgcolor='#FFFFFF' class='title' align='left'><font color='#000000'>Customer Name</font></td>

<td width='15%' bgcolor='#FFFFFF' class='title' align='center'><font color='#000000'>Arrive date</font></td>

<td width='10%' bgcolor='#FFFFFF' class='title' align='center'><font color='#000000'>Quoted</font></td>

<td width='10%' bgcolor='#FFFFFF' class='title' align='center'><font color='#000000'>Process State</font></td>



<td width='15%' bgcolor='#FFFFFF' class='title' align='center'><font color='#000000'>E-Mail</font></td>

<td width='10%' bgcolor='#FFFFFF' class='title' align='center'><font color='#000000'>Arrive Station</font></td>



</tr>";



while($arr = mysql_fetch_array($query1Result))

{

$yquery="select * from tblyear ORDER BY yid";

$yresult=query_select($yquery,$totalYearRecFound);



$cId = $arr['id'];

$name = $arr['name'];

$ostate=$arr['orderstate'];

$pstate=$arr['processstate'];



if($ostate == 'B')

{

$ostate ="Booking";

}

if($ostate == 'Q')

{

$ostate ="Quoted";

}

//$pstate=$arr['processstate'];

$arrivedate = $arr['arrivedate'];

$datearr = split("-",$arrivedate);

$year=$datearr[0];

$month=$datearr[1];

$day=$datearr[2];



$yquery="select * from tblyear where yid = $year";

$yresult=query_select($yquery,$totalYearRecFound);

$yrow=mysql_fetch_array($yresult);

$year=$yrow['caption'];

$monquery="select * from tblmonth where mid = $month";

$monresult=query_select($monquery,$totalMonRecFound);

$monrow=mysql_fetch_array($monresult);

$month=$monrow['caption'];

$adate="$year-$month-$day";

$email = $arr['email'];

$contactno = $arr['contactnumber'];

$arrivestation = $arr['arrivestation'];

$cquery = "select * from tblcity where cityid = $arrivestation";

$cresult=query_select($cquery,$totalMonRecFound);

$crow=mysql_fetch_array($cresult);

$city=$crow['caption'];



$str.="<tr>



<td class='w_text' align='center' valign='top'>$name</td>

<td class='w_text' align='center' valign='top'>$adate</td>

<td class='w_text' align='center' valign='top'>$ostate</td>

<td class='w_text' align='center' valign='top'>$pstate</td>

<td class='w_text' align='center' valign='top'><a href='mailto:$email'>

<span class='w_text'><u>$email</u></span></a></td>

<td class='w_text' align='center' valign='top'>$city</td>





</tr>";

}

$str.="</table></td></tr>";

}

else

{

$str = "

<tr>

<td valign='top' class='w_text'>There are no records !</td>

</tr>";

}

return $str;

}

if($message)

{

$message="$message";

}


if($mode == "delete" and $cid)

{

$query2Delete = "delete from tblordermanage where id=$cid";

$query2Result = query_delete($query2Delete);



if ($query2Result)

{

$message = "Order deleted successfully.";

}

}


if($page)

{

$page = $page;

}

else

{

$page = 1;

}

$bookingList = showBookingList($sortby,$mode,$page,25,$_GET['orderstate']);


this function will be sort data in both mode and and up to 25 record from table and
delete and edit opetions you can add..

Fetch data from the tables

There is Mainly Four ways to fetch data from the tables

  • mysql_fetch_array($query_result)

this function will fetch data from the query result by array you can access this array by the key which is table's field name and also by the id start with [0] and upto no. of filed in the table.

eg:

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_NUM))

{

printf("ID: %s Name: %s", $row[0], $row[1]);

// printf("ID: %s Name: %s", $row['id'], $row['name']);

}

  • mysql_fetch_object($query_result)

this function will fetch data from the query result by object you can access this object memebers bye the -> arrow operator and its key value .

$result = mysql_query("select * from mytable");

while ($row = mysql_fetch_object($result))

{

echo $row->id; echo $row->name;

}

  • mysql_fetch_row($query_result)

mysql_fetch_row( ) fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_row($result))
{
echo $row[0]; echo $row[1];
}

  • mysql_fetch_assoc($query_result)

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc( ) is equivalent to calling mysql_fetch_array( )with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

while ($row = mysql_fetch_assoc($result))

{

echo $row["id"]; echo $row["name"]; echo $row["user"];

}

Friday, April 13, 2007

PHP conection to Mysql database

as simple as eating chochobar.......


function mysql_dbconnect($server,$user,$pass,$db)
{
mysql_connect($server,$user,$pass);
if (!
$link) {
die(
'Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db($db, $link);
if (!
$db_selected) {
die (
'Can\'t use database : ' . mysql_error());
}

}

?>
Save above file as mysqlconnect.php you can use above function for the
any time establish mysql-php connection by including that file. and using
function you have to just call when you need

Syntax:

mysql_dbconnect('mysql serve rname','user of database','password for that user','database you wish to connect');
mysql_dbconnect('localhost','root','password','dbany');
?>