Updating 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
<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>
- $_SERVER['HTTP_HOST']
- $_SERVER['REQUEST_URI']
Labels: php
Storing data in notepad or in ms word
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...
Labels: php
Pagination with php
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
<?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...
Labels: php
Multiple records deletion in php using my sql
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
<?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...
Labels: ms sql server, php
Connecting php with ms sql server
$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...
Labels: ms sql server, php
Configuring php with ms sql server
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...
Labels: ms sql server, php
Installing and configuring mysql 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
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...
Labels: ms sql server, php
Installing php on windows
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
Labels: php
Getting size of mysql database in php
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
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...
Labels: php
How to encode php scripts
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...
Labels: php
Counting total number of rows in resultset using php and mysql
$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
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!!!
Labels: php
Deleting records from database using php and mysql
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
$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
$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
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...
Labels: php
Encrypting password in php
- Make a form having fields like name, email, username and password.
- 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'];
- Now make another variable to store the encrypted password after performing encryption process like $encrypt_pass=md5($pass);
- Now simply insert the information in the database using query like this $insert_query="insert into user values('$username','$encrypt_pas')";
- Recieve form values and encrypt the password that user provide.
- Execute sql query that will match the username and password from the database.
Read more...
Redirection in php
- Use Header function
- Use meta tag
Read more...
Labels: php
Selecting and Displaying records from database using php and mysql
These are the steps that should be followed.
- Include connection file.
- Write and execute query.
- 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
To insert records in a database table, required these steps
- First of all create the database if you want to use new database.
- create tables if u want to use new table in which values will be inserted.
- create connection file.
- 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.- Values are recieved by using $_GET or $_POST
- Write SQL Query.
- Execute the Query.
Please see the images to clearify the data insertion concept and then check explaination of all this process.
insert-records.phpIn 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
$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
- r+ (Read/Write. Start Reading Writing from the beginning of the file)
- w (Write. Open the file and write over file, if file doesn't exist then also creates the file)
- w+ (Read/Write.Open the file and write over file, if file doesn't exist then also creates the file)
- a (Append. Open the file and write at the end of the file, if file doesn't exist then also creates the file)
- a+ (Append/Read. Preserves the contents of the file by writing at the end of the opened file)
- x (Write. Creates the new file. Send error as well as return false if the file has been already created).
- 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);
.php file
Read more...Labels: php