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

Tuesday, 3 December 2019

How to Display MySQL Results in PHP

In this article, we will learn about different functions that MySQLi provides in PHP. We will learn the syntax of these functions, what kind of errors these functions can give, under what situation these functions can give errors, and how can we resolve these errors. We will also see how these functions work and in what order do these functions display their results.

MySQLi

PHP is a scripting language that uses the MySQLi extension to connect to MySQL databases. PHP provides three different ways to connect to MySQL database which are MySQLi extension, MySQL extension, and PHP Data Objects (PDO). 

MySQLi_query

MySQLi_query is a function of the PHP MySQLi extension that runs the queries against the database and retrieves the data from it. This function takes in three parameters and out of these three parameters, one is optional. The syntax of this function is
Syntax

mysqli_query (connection, query, resultmode)

Where the connection is a required parameter for this function and it specifies the database with which the connection is to be established and it is done by declaring a variable as described below.

$connection = mysqli_connect ("localhost", "username", "password", "database_name");
The query is also a required parameter for this function which specifies the operation to be performed on the database such as SELECT, INSERT, etc. Result mode is not required for this function, it is optional and specifies the type of the result of the query. The default result mode for this function is MYSQLI_STORE_RESULT which transfers the set of results from the last query executed on the database connection. The PHP code below shows the implementation of this function.

<?php
$con = mysqli_connect ("localhost", "username", "password", "database"); 
if (mysqli_connect_errno ())
  {
  echo "Failed to connect to MySQL: “. mysqli_connect_error ();
  }

mysqli_query ($con, "SELECT * FROM Persons");
mysqli_query ($con, "INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn','Quagmire',33)"); 
mysqli_close ($con);
?>

MySQLi_connect_error

This is a function of the MySQLi extension that returns a string which tells the user about the error that occurs during the connection to the database. This function does not take in any value as a parameter and just needs to be called in IF Else statement to check for the error is any. If no error occurred during the connection process then it will return null, otherwise it will return a string describing the error. The image below shows how to use this function.

<?php
$link = @mysqli_connect ('localhost', 'fake_user', 'my_password', 'my_db');
 if (! $link) {
        die ('Connect Error:'. mysqli_connect_error ());
}
?>

Result of MySQLi_connect_error
Result of MySQLi_connect_error

MySQLi_error

MySQLi_error is a function provided in the PHP MySQLi extension that can return the error details of the last function called. This function takes in only the connection variable as a parameter that stores the information about the connection to the database and just needs to be called in IF Else statement to check for the error is any. If there is no error occurred during the function call process then it will return null , otherwise, it will return a string describing the error. The image below shows how to use this function.

<?php
$mysqli = new mysqli ("localhost", "my_user", "my_password", "world"); 
if ($mysqli->connect_errno) {
        printf ("Connect failed: %s\n", $mysqli->connect_error);
        exit ();
if (! $mysqli->query ("SET a=1")) {
        printf ("Error message: %s\n", $mysqli->error);
$mysqli->close ();
?>
Result of MySQLi_errorResult of MySQLi_error

MySQLi_result 

This is a function that returns the result of the query which was run against the data of the database. There are many types of this function such as.
  • MySQLi_result:: current_field  It is a function that solitary takes one value as input and returns the present offset field of the present pointer.
  • MySQLi_result:: data_seek is a function that takes in just two input values and Adjusts the outcome pointer to a subjective row in the outcome.
  • MySQLi_result:: fetch_all is a function that takes in just two input values and brings all outcome pushes as an affiliated cluster, a numeric exhibit, or both.
  • MySQLi_result:: fetch_array is a function that takes in just two input values and brings all outcome pushes as an associative cluster, a numeric array, or both.
  • MySQLi_result:: fetch_assoc is a function that just requires two input values and finds an associative array in the result line.

Monday, 5 August 2019

Why I use PHP

So a question arises why I use PHP as my scripting language for web development. I use PHP because it is easy to learn, easy to develop and easy to host. It is free of cost and has a good community support. It just get my things done and apart from that it is great when you want to add little dynamic functionalists to your static web pages. You can find lots of resources , scripts and material online which you can use as reference while creating your code. You can even buy books if your budget allows. For now I am depending on web resources they are great but not a match of paid content which is generally more organized and well written. I have a functional knowledge of HTML and CSS and php just go great with them and it for now does what i am looking for. 

Here are some good reason to use PHP
  1. It can easily works with html
  2. It is easy to learn
  3. it has lot of interactive features for visitor
  4. You can find lots of resources , scripts and material online which you can use as reference while creating your code
  5. it is a free language with no licensing fees so the cost of using it is minimal
  6. A good benefit of using PHP is that it can interact with many different database languages including MySQL.
  7. PHP also has very good online documentation with a good framework of functions in place

Can I view PHP files locally on my PC?

When I started playing around with PHP I noticed that php files can not be opened by a web browser the way HTML files do. HTML and CSS are rendered by the browser. In other words browsers know all that it takes to load and display an HTML page with or without CSS. So HTML , CSS and javascript they all are part of web browsers but PHP is not a part of a web browser. So when it comes to the task of rendering PHP files browsers fails here this is because PHP files need an interpreter or a php interpreting program.

When while browsing internet and whenever you visit a PHP file your browser make a request to a web server to interpret the PHP script. After receiving the request server takes the PHP scripts and run them, and then take the response and send it back to your browser. Your browser can then understand and handle the response send to it by the server. This how you get to see the PHP file on your browser while browsing internet.
 But what about the situation where you are developing a website using PHP and you want to interpret php files locally on your PC 
So if you are developing a website I am sure you have an access to web server where you are hosting your website but surely you do not want to upload your file or project to web server again and again while developing and testing your website. So you need a local installation pf PHP on your machine. PHP is not preloaded on every computer like web browsers are but it is easy to download PHP from the Internet, get it working on your computer and all that for free. Most of the easiest and best and easiest tools for writing PHP code are also free.
I have read many books and articles on web where people recommend WampServer Installation but I have installed Easyphp Dev Server on my computer. I find it easy to install and it is also portable. You can also install it on  removable disk. So this is what I have installed and I find it particularly easy to install and use.
You can install any program you find like installing and working with.
I am not really going into steps of installing this program as the one I use is really easy just few clicks and you are done. So now I had prepared my PC for interpreting files nest comes a text editor that you can use for writing and editing PHP file. There are many editors available you can begin with your notepad or wordpad that comes wit your PC or you can try Komodo edit or sublime text they both are great and good for general purposes like editing and weiting your PHP files and scripts.

Handling HTML forms with PHP

Today in this post, I would talk about Handling HTML forms with PHP.  A simple example would be registration form. Lets create a html form with php


<html>
<form action=”register.php” method=”post”>
<table border=0>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Username:*</b></br>
<i>It must be 3 or more characters in length <br> and may
only contain letters and number</i></td>
<td><input name=”userid” type=”text” id=”userid” maxlength=”30″>
</td>
</tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Password:*</b><br>
<i>It must be 6 or more characters in length <br> and may
only contain letters and number</i></td>
<td><input name=”password” type=”password” id=”password” maxlength=”15″>
</td>
</tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Re-type Password:*</b></td>
<td><input name=”password2″ type=”password” id=”password2″ maxlength=”15″>
</td>
</tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Firstname:*</b></td>
<td><input name=”firstname” type=”text” id=”firstname” maxlength=”15″>
</td>
</tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Lastname:*</b></td>
<td><input name=”lastname” type=”text” id=”lastname” maxlength=”15″>
</td>
</tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Your Email Atdress:*</b><br>
<i>A confirmation email will be sent to you <br>
at this address</i>
</td>
<td><input name=”email” type=”text” id=”email” maxlength=”255″>
</td>
</tr>
<tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Your Mobile No:*</b><br>
</td>
<td><input name=”mob” type=”text” id=”mob” maxlength=”10″>
</td>
</tr>
<tr>
<td><input name=”reset” type=”reset” value=”Reset”></td>
<td><input name=”register” type=”submit” value=”register”> </td>
</tr>
</table>
</form>
</html>

We can save this file as myregistration.html and When you will open it you will get below html form.
myregister
When you fill the data and click the submit button, the all the submitted data is sent to register.php through HTML Post method
All variables passed to the current script via the HTTP POST method are stored in associative array $_POST. So you can access data from each field using $_POST[‘NAME’], where NAME is the actual field name. If you submit the form above you would have access to a number of $_POST array values inside the register.php file. The vvariables
$_POST[‘userid’]
$_POST[‘password’]
$_POST[‘password2’]
$_POST[‘firstname’]
$_POST[‘lastname’]
$_POST[’email’]
$_POST[‘mob’]
Now it is the job of register.php to process these variable according to the need and return the information back to user
Let’s for example, we choose register.php like
<?php
echo ‘<html>’;
$userid=$_POST[‘userid’];
$password=$_POST[‘password’];
$password2=$_POST[‘password2’];
$firstname=$_POST[‘firstname’];
$lastname=$_POST[‘lastname’];
$email=$_POST[’email’];
$mob=$_POST[‘mob’];
/* some mysql stuff */
echo ‘You name is $userid’;
echo ‘<br>’;
echo ‘You Firstname is $firstname’;
echo ‘<br>’;
echo ‘You lastname is $lastname’;
echo ‘<br>’;
echo ‘Your registration is completed’;
echo ‘</html>’;
?>


But here we are missing very important piece of information i.e validation. Users may put bad piece and totally corrupt the things. so it is always good to validate the information
There are many ways to perform the validation and it depends on the need,I would tell here some of the basics one
htmlspecialchars()This function convert the html special character in the input to html version. So attacker cannot inject html or java code in the field
stripslashes() : It removes the backflashed in the data
trim()This function returns a string with whitespace stripped from the beginning and end of string
preg_matchThis function matches the string with the strings. This is good function to validate the character in the field
preg_match(“/[^a-zA-Z]/”,$userid) : It check for if $userid is made of letters a-z and A-Z only (no spaces, digits or any other characters)

Keeping all these validation in mind, we can write the register.php as
<?php
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function validate_email($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if (!preg_match(“/([\w\-]+\@[\w\-]+\.[\w\-]+)/”,$data))
{
die(“E-mail address not valid”);
}
return $data;
}
echo ‘<html>’;
$userid=validate_input($_POST[‘userid’]);
$password=validate_input($_POST[‘password’]);
$password2=validate_input($_POST[‘password2’]);
$firstname=validate_input($_POST[‘firstname’]);
$lastname=validate_input($_POST[‘lastname’]);
$email=validate_email($_POST[’email’]);
$mob=$_POST[‘mob’];
/* some mysql stuff */
echo ‘You name is $userid’;
echo ‘<br>’;
echo ‘You Firstname is $firstname’;
echo ‘<br>’;
echo ‘You lastname is $lastname’;
echo ‘<br>’;
echo ‘Your registration is completed’;
echo ‘</html>’;
?>


PHP echo construct

Today I had learned about PHP echo construct it is not a function , it is a language construct. By language construct I mean that meaning that it is an integral part of PHP itself. It allows us to output data on the users web browser. You can output values stored in a variable using echo or you can also output string data using echo. We can use both single quotation mark ‘ ‘ or double quotation mark ” “ while using echo. Double quotation mark are used when you want to output value of some variable to the browser in a program and your line must terminate with the semi colon ;

<?php
echo "!I am echo construct!";
?>
view rawecho-in-php1 hosted with ❤ by GitHub
Now this would output !I am echo construct! to the web browser. Now the semi-colan (;) at the end of the echo command is used to mention the end of the echo construct. Without this semi-colon PHP would report an error.
So previous example shows the use of echo with double quotation marks. As stated earlier we can also use it with single quotation marks as shown below
<?php
echo '!I am echo construct!';
?>
view rawecho-in-php2 hosted with ❤ by GitHub

Now this would also output !I am echo construct! to the web browser.
In PHP we can also use echo to do arithmetic as can be seen in following example
<?php
echo 20+20;
echo '20+20';
?>
view rawecho-in-php3 hosted with ❤ by GitHub

Here line 2 is
echo 20+20;
This would output 40. This means echo command can be used for doing arithmetic and here note that quotation marks have not been used. You can also subtract , do division and multiplication using this echo construct.
Here line 3 is
echo ’20+20′;
This would literally output 20+20. This happens because quotation marks were used, this was processed as a string instead of a mathematical operation. And same thing would happen if we use double quotation marks instead of single quotation marks.

PHP introduction and uses

It was initially created by Rasmus Lerdorf in 1994. As of today, the current version of PHP is version 5, with version 6 in the making. it is the most popular scripting language on the web.It was initially called Personal Home page

What is PHP?
PHP stands for PHP Hypertext Preprocessor. PHP is a widely-used, open source scripting language. It is similar in syntax to C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly .PHP scripts are executed on the server and return the html or plain text to the browser
PHP features
PHP is a power full language and it can do all the functions like
a) it can create, open, read, write, delete, and close files on the server
b) It can collect form data
c) it can send and receive cookies.It can set session key
d) It can connect to many database like oracle,mysql ,sql server to add, delete, modify data in your database
e) A complete username password system can be built over it to control user-access
d) It can encrypt/decrypt data
e) It has all the if else,loop construct to help generate the dynamic page content
f) It can not only generate output in HTML/text. It can output XHTML and XML.
Why PHP is useful and so famous?
There are various reason why PHP is so famous and used in all web development projects. The largest blogging platform wordpress is built over PHP
1) it runs on various platforms (Windows, Linux, Unix, Mac OS X,Solaris,Exalogic,ibm etc.)
2) it is compatible with almost all servers used today (Apache etc.)
3) it supports a wide range of databases. It can connect to oracle,mysql,sqlserver,sqllite etc
4) it is free. Download it from the official PHP resource: www.php.net
5) PHP learning curve is quite simple and we can use it quite efficiently as a language of website
As of now,  millions Internet domains had web services hosted on servers with PHP installed and mod_php was recorded as the most popular Apache HTTP Server module.
Some more Important terms in relation to php
1) php files have extension of .php
2) They are executed on the server and whatever output it generates is sent to browser.So the server is the brain here, not your browser
3) The php script can have html,java script,jquery
4) PHP is a scripting language, like HTML. That means that code does not need to be compiled before it gets used — it gets processed on the fly as necessary
5) It is similar to .net, asp , mod_perl

PHP Tutorial

PHP stands for PHP Hypertext Preprocessor. PHP is a widely-used, open source scripting language. It is similar in syntax to C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly .PHP scripts are executed on the server and return the html or plain text to the browser

There are various reason why PHP is so famous and used in all web development projects. The largest blogging platform wordpress is built over PHP

1) it runs on various platforms (Windows, Linux, Unix, Mac OS X,Solaris,Exalogic,ibm etc.)
2) it is compatible with almost all servers used today (Apache etc.)
3) it supports a wide range of databases. It can connect to oracle,mysql,sqlserver,sqllite etc
4) it is free. Download it from the official PHP resource: www.php.net
5) PHP learning curve is quite simple and we can use it quite efficiently as a language of website

HTML and CSS:
Hypertext Markup Language (HTML) is the standard markup language for creating web pages and web applications.Cascading Style Sheets (CSS) is the language to support HTML and make it look better. 

include or require function in PHP with practical examples

Website design require header,footer,side bar,right bar, ad bar on multiple pages.It is not possible to change these on thousand of web pages whenever we want to change anything. Include function in php  solve this problem. We can  use include function in PHP and include the content of a PHP file into another PHP file before the server executes it.So If there is any change required then instead of changing thousand of files just change included file.

PHP has two functions which can be used to included one PHP file into another PHP file.
The include() Function
The require() Function
Both the function has different working .
The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement
Include function in PhpRequire function in php
The include() function takes all the text in a specified file and copies it into the file that uses the include function.
Syntax
Include ‘<file_name>’
Example
<?php
include ‘/home/test/public_html/coded/fbscript.php’;
?>

The require() function takes all the text in a specified file and copies it into the file that uses the require function.
Syntax
require ‘<file_name>’
Example
<?php
Require ‘/home/test/public_html/coded/fbscript.php’;
?>

If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.
If in above example if the fbscripts.php does not exists,then still code will run  and it will just generate warning
If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.
If in above example if the fbscripts.php does not exists,then still code will halt
Useful examples for Include function in Php
<!doctype html>
<html class=”no-js” lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>Example Site</title>
<?php include ‘/home/app//public_html/comcode/stylesheets_depth.php’; ?>
<?php include ‘/home/app//public_html/comcode/javascript.php’; ?>
</head>
<body>
<?php include_once(“/home/app//public_html/comcode/analytics.php”) ?>
<?php include ‘/home/app//public_html/comcode/brow-update.php’; ?>
<?php include ‘/home/app//public_html/comcode/facebooscript.php’; ?>
<?php include ‘/home/app//public_html/comcode/header1.php’; ?>
< text here>
</body>
<?php include ‘/home/app//public_html/comcode/footer.php’; ?>
</html
The above page will still even if the php script are not present as we have used include
<?php
require_once “/home/app/public_html/header1.php”;
?>
<!doctype html>
<html class=”no-js” lang=”en”>
<head>

<TITLE> Example site </TITLE>
<META NAME=”revisit-after” CONTENT=”1″>
<?php include ‘/home/app/public_html/comcode/stylesheets.php’; ?>
<?php include ‘/home/app/public_html/comcode/javascript.php’; ?>



</head>
<body>
<?php include_once(“/home/app/public_html/comcode/analytics.php”) ?>
<?php include ‘/home/app/public_html/comcode/brow-update.php’; ?>
<?php include ‘/home/app/public_html/comcode/facebookscript.php’; ?>
<?php include ‘/home/app/public_html/comcode/header2.php’; ?>
<text here>
</body>
<?php include ‘/home/app/public_html/comcode/footer.php’; ?>
</html>
The above will fail if the first header file is not available as it uses the require function