Updating records in php

In this php tutorial we will learn how to update records in php using database of mysql. To update records in php is quite easy, let's have a look over below mentioned example to learn how to update records in php.

edit-recs.php


=========(Code)edit-recs.php=========

<?php
require_once('conn.php');
$select_query="select * from student";
$result=mysql_query($select_query);
?>

<body>
<table width="100%" cellpadding="2" cellspacing="2" class="fontclass">
<tr>
<td width="12%">
<strong>Roll No</strong></td>
<td width="16%">
<strong>First Name</strong></td>
<td width="20%">
<strong>Last Name</strong></td>
<td colspan="2">
<strong>Father Name</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result))
{
?>
<tr>
<td width="12%">
<?php echo $rows['rollno'];?></td>
<td width="16%">
<?php echo $rows['fname'];?></td>
<td width="20%">
<?php echo $rows['lname'];?></td>
<td width="12%">
<?php echo $rows['fathername'];?></td>
<td width="40%"><strong><a href="update-recs.php?rollno=<?php echo $rows['rollno'];?>">Edit</a></strong></td>
</tr>
<?php
}
?>
</table>
</body>

update-recs.php



=========(Code)update-recs.php=========
<?php
require_once('conn.php');
$rollno=$_GET['rollno'];
$select_query="select * from student where rollno='$rollno'";
$result=mysql_query($select_query);
$rows=mysql_fetch_array($result);
?>

<table width="600" cellpadding="2" cellspacing="2">
<tr>
<form name="form1" method="post" action="do-update.php">
<tr>
<td>First Name</td><td><input type="text" name="fname" value="<?php echo $rows['fname'];?>"/></td>
</tr>
<tr>
<td>Last Name</td><td><input type="text" name="lname" value="<?php echo $rows['lname'];?>" /></td>
</tr>
<tr>
<td>Father Name</td><td><input type="text" name="fathername" value="<?php echo $rows['fathername'];?>" /></td>
</tr>
<tr>
<td><input type="hidden" name="rollno" value="<?php echo $rollno;?>" /></td><td><input type="submit" value="Update Records" /></td>
</tr>
</form>
</tr>
</table>

do-update.php

<?php
require_once('conn.php');
$rollno=$_POST['rollno'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$fathername=$_POST['fathername'];
$sql="update student set fname='$fname',lname='$lname',fathername='$fathername' where rollno='$rollno'";
$result=mysql_query($sql);
if($result)
{
header("location:display.php");
}
else{
mysql_error();
}
?>


So this is the way to update records in php. Read more...

Getting complete web page url from address bar in php

In this tutorial you will learn how to get full web page url from address bar.

<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>

We are using these two php functions to get complete web page url from address bar. These two functions are
  1. $_SERVER['HTTP_HOST']
  2. $_SERVER['REQUEST_URI']
$_SERVER['HTTP_HOST'] this builtin php function will show you only server name, e.g www.yoursite.com .
$_SERVER['REQUEST_URI'] this builtin php function will show you the path to file of your url e.g www.yoursite.com/yourpage.php

So this is the way to get complete web page url from address bar in php

Read more...

Storing data in notepad or in ms word

In php you can store data in text file such as notepad and even in microsoft word too.

The following code will make you able to store form data(user name in my example ) in microsoft word file. It will create ms word file too that if file is not created before.

<?php
$username = $_POST['username'];
$fp = fopen("myfile.doc","a+") or exit("unable to open the file");
if($fp != null)
{
fwrite($fp,$username);
}
fclose($fp);

?> Read more...

Pagination with php

Pagination is used to display results of your query over multiple pages, rather than displaying on just one page. Pagination prevents user to scroll the webpage. For example if your query is bringing 1000 rows and you want to display these rows in php page then it will be done quite fine but it will disturb the user alot because he/she will tired after scrolling the page Repeatedly.

So to display records properly and to avoid scrolling, we use pagination. So let's look how we can do pagination with php.

*******Pagination.php*********



This is what i want to developed. This pagination offers the facility to Move Next Page, Previous Page, First Page and Last Page.

Pagination.php

<?php
require_once('conn.php');


// how many rows to show per page
$rowsPerPage = 15;

// by default we show first page
$pageNum = 1;

// if $_GET['page'] defined, use it as page number
if(isset($_GET['page']))
{
$pageNum = $_GET['page'];
}

// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;

$query = "select * from student" .
" LIMIT $offset, $rowsPerPage";
//print $query;
$result=mysql_query($query);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Pagination in php</title>
<style type="text/css">

.fontclass
{font-family:Verdana;
font-size:12px;
}

</style>
</head>
<body>
<table width="100%" cellpadding="2" cellspacing="2" class="fontclass">
<tr>
<td width="12%">
<strong>Roll No</strong></td>
<td width="16%">
<strong>First Name</strong></td>
<td width="20%">
<strong>Last Name</strong></td>
<td colspan="2">
<strong>Father Name</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result))
{
?>
<tr>
<td width="12%">
<?php echo $rows['rollno'];?></td>
<td width="16%">
<?php echo $rows['fname'];?></td>
<td width="20%">
<?php echo $rows['lname'];?></td>
<td width="12%">
<?php echo $rows['fathername'];?></td>
<td width="40%"><strong><a href="delete-rec.php?rollno=<?php echo $rows['rollno'];?>">Delete</a></strong></td>
</tr>
<?php
}
?>
</table>

<?php
$query = "SELECT COUNT(rollno) AS numrows FROM student";

$result = mysql_query($query) or die('Error, query failed');

$row = mysql_fetch_array($result, MYSQL_ASSOC);

$numrows = $row['numrows'];

// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);

// print the link to access each page
$self = $_SERVER['PHP_SELF'];

// creating previous and next link
// the first and last page
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " <a href=\"$self?page=$page\">[Prev]</a> ";
$first = " <a href=\"$self?page=1\">[First Page]</a> ";
}
else
{
$prev = ' '; // we're on page one, don't print previous link
$first = ' '; // nor the first page link
}
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " <a href=\"$self?page=$page\">[Next]</a> ";
$last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> ";
}
else
{
$next = ' '; // we're on the last page, don't print next link
$last = ' '; // nor the last page link
}
// print the navigation link
echo $first . $prev .
" Showing page $pageNum of <B>$maxPage</B> pages " . $next . $last;
?>


</body>

</html>


Explaination

$rowsPerPage = 15;
I am specifying number of rows that will be shown per page .

$pageNum = 1;
By default i will show first page.


if(isset($_GET['page']))
{
$pageNum = $_GET['page'];
}

if page number is coming from query string then i will display that page. Else by default we will show first page.

$offset = ($pageNum - 1) * $rowsPerPage;
Counting the offset, offset is the main thing in whole pagination process. Offset is an integer indicates the distance from beginning until a given element or point.

$query = "select * from student" .
" LIMIT $offset, $rowsPerPage"

Then i apply limit on my query, the above query will look like same if you print it
select * from student LIMIT 0, 15 it means to display number of records that lies in the given range.

After this i am executing the query and displaying rows one by one from result set.

Now again look at some important code snippet in pagination module. After while loop we are counting total number of records by executing this query
$query = "SELECT COUNT(rollno) AS numrows FROM student";
and then i find out the max page, means how many pages will become during whole pagination process and then i find out the first, previous, last and next pages and display them in a proper manner where they need to display.

Read more...

Get number of days between two given dates in php

To get number of days between two given dates is quite easy in php. Let's look below the code to get number of days between two given dates

<?php


$days = (strtotime(date("Y-m-d"))-strtotime("2009-1-20") ) / (60 * 60 * 24);

//$days_proc_time = (strtotime(date("Y-m-d")) - strtotime("2005-11-20") ) / (60 * 60 * 24);

print $days;

?> Read more...

Multiple records deletion in php using my sql

Now a days while developing web applications it is common requirement to delete multiple records same as gmail is offering deletion of multiple records. So lets have a look how to delete multiple records in php using my sql as a database server.

Create view-recs.php file to select and display all records



======(CODE) view-recs.php)======

<html>
<head>
<title>Multiple Deletion in php</title>
<?php
require_once('conn.php');
$sql="select * from $tbl_name";
$result=mysql_query($sql);
?>
</head>
<body>
<table width="600" cellpadding="2" cellspacing="2" style="font-family:Verdana; font-size:12px;">
<tr>
<form name="form1" method="post" action="do-delete.php">
<tr bgcolor="#eaeaea">
<th>Roll No</th>
<th>Name</th>
<th>Father Name</th>
<th> </th>
<th> </th>
</tr>
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><?php echo $row[0]; ?> </td>
<td align="center"><?php echo $row[1]; ?> </td>
<td align="center"><?php echo $row[2]; ?> </td>
<td align="center"> <input type="checkbox" name="del[]" value="<?php echo $row[0]; ?>"> </td>
</tr>
<?php
}
?>
<tr>
<td colspan="3">
<input type="submit" value="Delete">
</td>
</tr>
</form>
</table>
</body>
</html>

This is simple code, you have already learned this code in previous posts, but the most important part of this code is
, this code is responsible for making array for checkboxes that contains value which is unique for every checkbox and coming from database too.

Now we want to develop a php file that will perform multiple deletion process, in this example i use name for this php file is do-delete.php, so lets have a look over the code that how multiple deletion process will occur after selecting multiple check boxes and then clicking on Delete button.

======do-delete.php======


<?php
require_once('conn.php');
if (isset($_POST['del']) && is_array($_POST['del']))
{
foreach ($_POST['del'] as $num => $value)
{
$sql="delete from $tbl_name where rollno='$value'";
$result=mysql_query($sql);
}
}
header("location:view-recs.php");
?>

In this above mentioned code, the most important code snippet is

foreach ($_POST['del'] as $num => $value)
{
$sql="delete from $tbl_name where rollno='$value'";
$result=mysql_query($sql);
}


we apply foreach loop that will go through the array of checkboxes and perform deletion process against selected checkboxes.

====== conn.php======



<?php
$host="localhost";
$user="root";
$db_pass="";
$db_name="tutorials";
$tbl_name="student";
mysql_connect("$host","$user","$db_pass") or die("cannot connect to the database server");
mysql_select_db("$db_name") or die("cannot select the database");
?>
Read more...

How to avoid connection error in php when ms sql server database name contains special characters

Suppose your database name is my-db-name, you can observe that this database name contains special character hyphen (-), Now if you want to connect with ms sql server in php using this code then you will get error because database name here contains special characters and such special characters need special care :), All you need to do is just put this database name in square brackets []. Now if you assign database name to $db_name like this way $db_name="[my-db-name]"; then you will not get any error and you will be successfully connected with ms sql server database else you will get error if you simply copy/paste the below code and your database name contains special characters.

<?php

$host="localhost"; \\name of the web server

$user="root"; \\username of ms sql server will come here

$pass="yourpassword"; \\password of ms sql server will come here with respect to username

$db_name="my-db-name"; \\name of your database will come here

mssql_connect("$host","$user","$pass") or die("cannot connect to the database server");

mssql_select_db("$db_name") or die("cannot select the database");


?>

so this is the proper way to avoid connection error in php when ms sql server database name contains special characters. Read more...

Connecting php with ms sql server

Suppose you have ms sql server and php installed, also both are configured with each other then here is the connection file that u have to developed in order to interact with the database of ms sql server in php.


$host="localhost"; \\name of the web server



$user="adeel"; \\username of ms sql server will come here



$pass="yourpassword"; \\password of ms sql server will come here with respect to username



$db_name="yourdatabase"; \\name of your database will come here



mssql_connect("$host","$user","$pass") or die("cannot connect to the database server");



mssql_select_db("$db_name") or die("cannot select the database");



save this code and give name to the php file such as conn.php and include in every file where which u want database interaction. Read more...

Configuring php with ms sql server

Yeah you read correct title of this post, i m going to configure ms sql server with php so that those people can take advantage who want to develop website using ms sql server and php.

People want to use ms sql server with php when they have web application that is dealing with very big database, means there are almost un countable records and also they have their own web server.

So lets follow these basics step to configure php with ms sql server accurately.

One thing more, There are two methods to configure microsoft sql server with php, But i recommend you to use Method 1 because it is too simple and it don't care whether you have configuration tools like SQL SERVER CONFIGURATION MANAGER installed or not?

Method 1 to configure php with ms sql server

1) Download the latest version of ntwdblib.dll from reliable resource aviliable in the internet.

2) Put this ntwdblib.dll in C:\Windows and C:\Windows\System32 folders.

3) Go to php.ini file that you placed in the C:\Windows folder during the installation of php and un comment this line extension=php_mssql.dll by removing preceeding semi-colon.

4) Reboot your system

Method 2 to configure php with ms sql server

1)Go to your windows start up Microsoft Sql Server 2005 ->Configuration Tools-> SQL Server Configuration Manager

2) Now expand Sql Server 2005 Network Configuration and then Click Over "Protocols for MSSQL SERVER" then Enable Piplelines and TCP/IP

3) Repeat this process for Protocols for SQLEXPRESS

4) Now click over refresh button and Close the Configuration Manager

5) Go to Run > CMD > and then write NET START SQLBROWSER

6) Go to php.ini file that you placed in the C:\Windows folder during the installation of php and un comment this line extension=php_mssql.dll by removing preceeding semi-colon.

7) Reboot your system Read more...

Installing and configuring mysql with php

To install mysql and then confihure it with php is not a big deal. Just follow the following steps and then mysql will be installed and also will be work accurately with php.

1) Download mysql 5.0 setup and then install mysql.

2) Now after installing mysql you have to configure an instance, for this go to MySQL Server Instance Configuration Wizard and Click Detailed Configuration->Developer Machine-> Non Transactional Database Only->Decision Support (DSS)/OLAP->Check Enable TCPIP Netwokring->Port 3306->Standard Character Set->Install as a Windows Service Now its time for you to give a password, you can give any password that you can easily remember but for the first time it is prefered that you should use root as a password. And then Click Execute, if you don't see any red X then its mean mysql is configured accurately.

Configuring PHP to work accurately with MYSQL

Please follow the steps to configure php with mysql

1) Go to C:\PHP folder copy the dll libmysql.dll to your C:\Windows\System32 folder.

2) Edit php.ini file that you place in C:\Windows during the installation of PHP, Open php.ini file in notepad and then find this line extension_dir = "./" and replace this line with the exact path of the extensions folder in C:/PHP which is ext, now the new path will be extension_dir = "c:\php\ext", i mentioned this step during the installation of php, if you didn't follow this step before then please do follow this important point now.

3)In the same php.ini file, please un comment two lines by removing semi-colon (;) . Find these lines extension=php_mysql.dll, extension=php_mysqli.dll and un comment both lines by removing preceeding semi-colon

4) Reboot your System

So this is the way to install and configure mysql with php Read more...

Displaying random records using ms sql server and php

To get random records in ms sql server using php is also very easy process, just you need to write this query in order to get the random records in ms sql server.

SELECT * FROM YOURTABLE ORDER BY newid()

Displaying random records using ms sql server and php

In php you cannot use select * statement for ms sql server, if you try to use it then it will give u error mention below

message: Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier. (severity 16)

So to overcome this problem and to get random records too, use this query

$select_query="SELECT id,CAST(question AS TEXT) AS question,CAST(answer_one AS TEXT) AS answer_one,CAST(answer_two AS TEXT) AS answer_two,CAST(answer_three AS TEXT) AS answer_three,CAST(answer_two AS TEXT) AS answer_four,CAST(correct_answer AS TEXT) AS correct_answer FROM $tbl_name order by NEWID()";
$resultset=mssql_query($select_query);


Note:- For those columns you use varchar datatype it is better to convert then into TEXT in order to avoid the Unicode error.

So this is the way to Select and Display the Random Records in MS SQL SERVER using PHP
Read more...

Installing php on windows

Installing php on windows is a basic requirements of those programmers who want to use php with IIS in windows plateform. For users who want to use php on windows with apache and my sql, it is better for them to install WAMP using WAMP setup. But for people who want to install php on windows and want to run php with IIS and any database they want then it is better to install php manually.

Following are the steps to install php

1) First of all go to www.php.net/download and download the php version that you want but for this tutorial it is better to download the version less than 5.3 because the versions starting from 5.3 doesn't have any php5isapi.dll file, for these latest versions you have to install php with IIS via FastCGI. Near future i will write a tutorial for installing php on windows with IIS 6.0 and 5.1 via FastCGI, right now i have written a tutorial for
Installing PHP on Windows 7 with IIS 7 via FastCGI

2)Download the Windows binary instead of Windows installer.


3)Extract the zip files and make a folder in C:(Where your windows is install), use PHP for folder name and copy/paste all the extracted files and folder in the PHP folder, now you will see that your PHP folder contains bunch of dll files and sub folders like "ext","dev","extras","PEAR" with files in there as well.

4)Now open the php.ini-recommended in a notepad and find this line extension_dir = "./" and give the path to the ext folder that place in PHP folder, for example you made folder in C: then then it must be extension_dir = "c:\php\ext"

5) Save as this php.ini-recommended file as php.ini in c:\windows and also in PHP folder too

6) Now Open IIS Manager by going to Control Panel -> Administrative Tools -> Internet Information Services.

7) Now right click on Default Website->Properties-> Home Directory-> Configuration, Now check whether .php is avilaible in Extensions, if not then Click on Add Button and then Click on Browse Button and give path of php5isapi.dll that is located in your C:\PHP folder , write .php in Extension text box, Press OK and Then OK.

8) Create a test php file in the root directory(C:\Inetpub\wwwroot) and save it as test.php

9) Reboot your system

10) Now write http://localhost/test.php

See Visual Demonstration of installing php on windows








Read more...

Getting size of mysql database in php

Sometimes we want to get the size of the database. In php, it is quite easy to get the size of mysql database. Just you need to copy/paste the following code and replace the database name with your database name

Code to get mysql database size in php:-
<?php


require_once('conn.php');

function getfilesize( $data ) {

// For bytes
if( $data < 1024 ) {

return $data . " bytes";

}
// For kilobytes
else if( $data < 1024000 ) {

return round( ( $data / 1024 ), 1 ) . "k";

}
// For megabytes
else {

return round( ( $data / 1024000 ), 1 ) . " MB";

}

}

$result = mysql_query( "SHOW TABLE STATUS" );
$dbsize = 0;

while( $row = mysql_fetch_array( $result ) ) {

$dbsize = $row[ "Data_length" ] + $row[ "Index_length" ]+$dbsize;

}


echo "The size of the database is " . getfilesize( $dbsize );

//You just need to change the dbname in connection file

?>

So this is the way to Get size of mysql database in php

Read more...

Getting width and height of an image in php

There is a builtin function in php to get the width and height of an image. The getimagesize()function determines the size of image also including flash file(swf).

Here is the code to get basic information such as width, height, type and attribute of any image

<?php

list($width, $height, $type, $attr) = getimagesize("you_image.jpg");

echo "Image width " .$width."\n";

echo "Image height " .$height."\n";

echo "Image type " .$type."\n";

echo "Attribute " .$attr."\n";


?>

Output

Image width 749
Image height 695
Image type 2
Attribute width="749" height="695"

so this is the way to get the width and height of any image in php.

Type of the image
1 = GIF
2 = JPG
3 = PNG
4 = SWF
5 = PSD
6 = BMP
7 = TIFF(intel byte order)
8 = TIFF(motorola byte order)
9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM
Read more...

How to encode php scripts

Some times for the security purpose you want to encode your php scripts so that no one can see your php code. To perform this job there are online resources as well as softwares are avilaible.

These resources are capable to encode your php script and give u encoded form of php script, if you run and execute that encoded form of your script u will get same result.

Example:-

Normal php script

echo "Pakistan";

Encoded Version

$_F=__FILE__;$_X='Pz48P3BocCA1Y2gyICJQMWs0c3QxbiI7ID8+';eval(base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw=='));

There are both free as well as paid resources that gives you the facility to encode your php script, the best free online resource is http://www.byterun.com/free-php-encoder.php Read more...

Counting total number of rows in resultset using php and mysql

To count total number of rows in resultset using php and mysql is quite easy just to use mysql_num_rows() function, this function takes resultset as a parameter and then tell us how much rows resultset have. Let's look below the code to see its demonstration

$sql="select * from users where username='Micheal' AND password='123456'";
$resultset=mysql_query($sql);
$total=mysql_num_rows($resultset);
echo $total;


So this is the way to find out total number of rows in resultset using php and mysql. Read more...

Sending html emails using php

In this tutorial you will learn how to send html emails in php. Nowadays it is common requirement in almost every website to have contact us form or feedback form, user fill that form and email is generated to concern person.
To improve the performance, it is strongly recommended to send email in html format because it is more easy to read and understandable.

Send html emails using php

function send_email($from, $to, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n"; 
//set content type to HTML 
$headers .= "Content-type: text/html\r\n"; 

if ( mail($to,$subject,$message,$headers) ) 
{
header("location:yourdesirepage.php?msg=sent");

} 
else 
{
header("location:yourdesirepage.php?msg=notsent");
}
}

$from_email="fromyou@gmail.com";
$to_email="tosomeone@gmail.com";
$subject="Subject of Email";
$message.="<html><body>";
$message.="<strong>Your message here will be look bold when visible to reader</strong>";
$message.="Some more message";
$message.="</body></html>";
send_email($from_email,$to_email,$subject,$message);



To send html email I have written a custom function send_email() that takes four parameters and then i made a call to built-in mail() function in it to send email.


$headers is a variable containing all the headers of the email, using this variable html email will be sent to the user. Let's have a look over the code of $headers line by line


$headers = "From: ".$from."\r\n";



From header contains the email address used for sending email.
$headers .= "Reply-To: ".$from."\r\n";

Reply-To header contains the information of email address where replies should be sent.


$headers .= "Return-Path: ".$from."\r\n";

Return-Path contains the return path of the email.It is same as the Reply-To header. Some email clients require this, others create a default.
$headers .= "Content-type: text/html\r\n"; 

Now this above line of code gives you the ability to send html emails, if we use Content-type:text/html then its mean we can send email of both text and html format.


Note:-Header names are case sensitive. Each header is ended with the Return and Newline characters \r\n. There are no spaces among header name.
So that's it.


Happy coding!!!
Read more...

Deleting records from database using php and mysql

Deleting records from database using php is quite easy. You have already learn how to select and display records from database, after selecting and displaying the records you just need to have an additional column to delete the records, please see the image below


Note:- You cannot delete any single record, deletion process occurs for whole row.

As you see in above image, whenever you will put the cursor of your mouse on the hyperlink (Delete) the u will see a link with query string on the status bar, this is the best method to delete the records.

Note:- There must be unique query string for every row to delete it so that when u try to delete any specific row then only that row should be deleted.

Here is the code to develop that above page



Explaination:-
As you can see on above page that it is 99% same page as we have for selecting and displaying records page, yeah off course but one thing that is additional in this page is Delete column that i also highlight in the above snapshot of the code. Now let's understand that highlight portion

I have made a column to Delete the row, for this i use caption Delete and make it hyperlink to that page where deletion of records code is written, i pass a querystring to that page also with the help of a variable rollno, rollno is a unique key in my senario that's why i use it to delete rows.

Now let's check the code that performs whole deletion process


Explaination:-

require_once('conn.php');
$rollno=$_GET['rollno'];
$delete_query="delete from student where rollno='$rollno'";
$resultset=mysql_query($delete_query);
if($resultset)
{
header("location:display.php");
}
else{
mysql_error();
}
?>
first of all we include connection file to our php script then we get the query string value using $_GET[], query string always get using $_GET[''], after getting the query string we store its value in a variable $rollno, then we write and execute query to delete the specific row, after this we perform a check and that check is if query successfully executed then redirect to the page where all records are displaying so that we can confirm the deletion process else we are showing errors using mysql_error(); function.

So this is the way to delete the records or delete the rows using php and mysql. Read more...

applying limit on records using php and mysql

To limit records using php and mysql is very easy. Just you need to write this select query instead of simple select query.

$limit_records=2;
$select_query="select * from student limit $limit_record";


or you can also write this query like below

$select_query="select * from student limit 2";

Its up to you how much limit you apply over sql query. Normally limit apply on query during development of Pagination Module.

So this is the way to apply limit on mysql query to limit the records. Read more...

select and display random records using php and mysql

To select and display random records using php and mysql is very easy. Just we need to do is to write this query instead of simple select query.

$select_query="select * from student order by rand()";

Now every time this query after execution comes with random records. So this is the way to select and display random records. Read more...

Stop execution of code in php

Some time during debugging code at our end through programming language we want to stop the execution of code at some desired place. In asp, Response.End() is used for this purpose and in php exit; is used for this same purpose.

Example:-

echo "Hello World";

exit;

echo "Hello Readers";

Now just first line will be executed and Hello World will be displayed, the reason why Hello Readers will not be executed and displayed is the word exit, when compiler compile this word(exit) the execution of php script will be stopped. So whenever you want to stop the execution of php code just use exit; for this purpose. Read more...

Encrypting password in php

some time due to security reason it is necessary to store encrypted password in database. In php we normally use md5() function to encrypt the password. md5() fucntion generates 32 characters hash.
It is very simple to use md5() function to encrypt the data, no matter whether it is password or something else. Following code is encrypting the password using md5()

$pass="world";

$pass_encrypt=md5($pass);

echo $pass_encrypt;

Case Study:- We want to make a develop a module that will allow user to register by providing just two things, one is username and other is password, and then we have to encrypt the same password, insert the encrypted password in database and then whenevr user want to signin then then he can signin easily with the password he choosed using registration process.

Solution:- Following are the steps to develop such module
  1. Make a form having fields like name, email, username and password.
  2. Develop anotherpage that will deal with all encryption process, in that page you just have to recieve the form data using post or get method and assign username to some variable, let us suppose $username=$_POST['username']; and for password    $pass=$_POST['password'];
  3. Now make another variable to store the encrypted password after performing encryption process like  $encrypt_pass=md5($pass);
  4. Now simply insert the information in the database using query like this $insert_query="insert into user values('$username','$encrypt_pas')";
Now when user wants to signin just perform these two following steps
  1. Recieve form values and encrypt the password that user provide.
  2. Execute sql query that will match the username and password from the database.
Please see below the images to check full demonstration of this module









Read more...

Redirection in php

There are two ways for redirection in php.
  1. Use Header function
  2. Use meta tag
The best one is header function but there are some things that must be in your mind if you want to redirect user successfully to the required page. Below is the working demonstration of header function

1) Redirection using header function

header("location:yourdesiredpage.php");

Now when this line of code is executed it will redirects user to the your desired webpage. But what if you want delay? For example you want to display some msg and then want to redirect the user, following code is the solution for this problem, it will redirect user after some time delay.

header("refresh:2;url=yourdesiredpage.php");

The above code will redirect user after 2 seconds.

Sending query string from header function
You can also send query string from header function, here is the code for this 

header("location:yourdesiredpage.php?msg=somemessagehere");

Steps that must be in your mind while using header function

1) Try not to use head tag if you want to use header function to redirect the user. Just print message using echo and then redirect the user, there is no need for any html tag.

2) Do not print any thing before header function, it will give error in some cases, infact in some php versions less than 5.4

Suggestion
If you want to redirect user to any webpage after delay of 5 seconds so that a message should be also display to user then you just follow this code

header("refresh:2;url=yourdesiredpage.php");
echo "You are redirecting to another page";

Just you see above, you should use echo after header function, it avoids errors in all cases and also it will do job!!!!

2) Use meta tag to redirect the user or refresh the page



The above meta tag will redirect user to the page u want. http-equiv='refresh' will capable to redirect user using meta tag, content='5 means it will redirect after 5 seconds, url='yourdesiredpage.php' is the url where user will be redirected.

Note:- meta tag must be use inside head tag

Suggestion:- It is better to use header function to redirect the user instead of meta tag.






Read more...

Selecting and Displaying records from database using php and mysql

Selecting and Displaying records from mysql table using php is quite easy.

These are the steps that should be followed.
  1. Include connection file.
  2. Write and execute query.
  3. Apply while loop to get all results

Please see the images in order to completely understand how to select and display the records using php and mysql



Code




mysql_fetch_array() is used to fetch regular array, row by row from the result set and this process goes on until it reaches the last row if this function is inside while loop, if this function is not inside while loop then it fetchs only one row from the result set and focus move to the next code segment of the php program.

In our php program we need to display all the records that match our query so we use mysql_fetch_array() inside the while loop and also display every row one by one using echo statement.

Let's understand php code use for selecting and displaying records from mysql database

require_once('conn.php');
we first include the connection file in our php program. In this connection file we define host which is localhost, user which is by default root, database name and then mysql_connect() function to establish connection with database and then mysql_select_db() function to select the database. To know exactly how to create connection with database using php please read this post.

$select_query="select * from student";
We write a query to select all the records from the student table and then assign this query to a variable $select_query

$result=mysql_query($select_query);

mysql_query($select_query) is used to execute the query, it takes query as a parameter, in the above line the query is executed and result set is store inside the variable $result. and then we apply mysql_fetch_array() to display rows from resultset one by one. mysql_fetch_array() takes result set as a parameter.




Output


Read more...

Insertion of records in database using php and mysql

In this tuorial we will learn how to insert records in mysql database.


To insert records in a database table, required these steps


  1. First of all create the database if you want to use new database.
  2. create tables if u want to use new table in which values will be inserted.
  3. create connection file.
  4. create a php file that contains a form using this form values will be inserted to the database.

Process of Inserting Records in a database table

Values goes to the next page, the page defined in the action attribute, after the form is submitted.

  1. Values are recieved by using $_GET or $_POST
  2. Write SQL Query.
  3. Execute the Query.

Please see the images to clearify the data insertion concept and then check explaination of all this process.

insert-records.php

In this php file we creates a form that contains two fields one is Name and other is FatherName.

To get Name, we have textbox and the name attribute of textbox is name. I think you are confusing???

Ok Listen, the name attribute of the field is the really big boss who stores the value whatever user writes in the textbox, for the Name of user, i place a textbox and give its name attribute a value called name, now this textbox will be accessed in the next page, whenever form is submitted by its name attribute, in this case its name=name.

Same for Father Name, we have a textbox whose name attribute is fname and this fname make it possible to access the value of this textbox in the next page.

action="do-insert.php", this is the page where form elements will be accessed and insertion will placed.

method=post means that form values will be transfered using post method.



do-insert-records.php

In this php file, first of all i include the connection file, then form elements that are coming from previous page are accessed and stored in the variables.

Then i write the sql query and save it in a variable called $queryinsert. and for executing this query, i passed $queryinsert as a parameter and execute the query.

Note:- mysql_query() is used to execute the mysql query.

After executing the insertion query i save the resultset in a variable $resultset and then check whether resultset is true or not, if resultset is true then its mean our query has been successfully executed, else we are going to print the error to find out why query is not executed.



conn.php



Output

Read more...

How to make connection with mysql

Suppose you have mysql and php installed, also you they both are interacting with each other then here is the connection file that u have to made in order to interact with the database of mysql.


$host="localhost"; \\ if the database you want to interact is on your pc.



$user="root"; \\ mysql username, by default is root



$pass="yourpassword"; \\ pass of mysql, if there is no password then $pass="";



$db_name="yourdatabase";



mysql_connect("$host","$user","$pass") or die("cannot connect to the database server");



mysql_select_db("$db_name") or die("cannot select the database");



save this in any file, such as conn.php and include in every file over which u want database interaction.



Read more...

File handling in php

php gives u facility to read, write, open, close and perform various operation over files.

The function use to open the files in php is fopen().

It contains two parameters. The first determines the name of the file with extension and second parameter determines the mode in which the file should open. Like read, write etc.

Example:- Opening of file using fopen()

$file_open=fopen("myfile.txt","r");

The above code is responsible for opening the text file in readonly mode, means u cannot perform any write operation on this file.

Different modes for opening the file are

  1. r+ (Read/Write. Start Reading Writing from the beginning of the file)
  2. w (Write. Open the file and write over file, if file doesn't exist then also creates the file)
  3. w+ (Read/Write.Open the file and write over file, if file doesn't exist then also creates the file)
  4. a (Append. Open the file and write at the end of the file, if file doesn't exist then also creates the file)
  5. a+ (Append/Read. Preserves the contents of the file by writing at the end of the opened file)
  6. x (Write. Creates the new file. Send error as well as return false if the file has been already created).
  7. x+ (Read/Write. Creates the new file. Send error as well as return false if the file has been already created)

If fopen() function unable to open the file it returns false.

Displaying message if file is not opening

$file_open=fopen("myfile.txt","r") or exit("unable to open the file");

Checking End-Of-File (EOF)

Sometime u doesn't know how many lines the file contains that u want to read, for this you use feof() that checks if the End-Of-File has been reached or not. It is better approach to use this during looping process.

if(feof($file_open))

{

echo "End of file has been reached";

}

Closing of file

$file_open=fopen("myfile.txt","r") or exit("unable to open the file");

fclose($file_open);

Reading data line by line from file

The fgets() function is used to read a single line from opened file.

Example:-

$file_open=fopen("myfile.txt","r") or exit("unable to open the file");

while(!feof($file_open))

{

echo fgets($file_open)."\n";

}

fclose($file_open);

Reading a file Character by Character

The fgetc() function is used to read a single line from opened file.

Example:-

$file_open=fopen("myfile.txt","r") or exit("unable to open the file");

while(!feof($file_open))
{
echo fgetc($file_open)."\n";
}
fclose($file_open);



.txt file

.php file


Output

Read more...