PHP

Build a MySQL Database Using PHP

1. Create a MySQL database:

CREATE DATABASE mydatabase;

2. Create a MySQL user and grant access to the database:

CREATE USER ‘myuser’@’localhost’ IDENTIFIED BY ‘mypassword’;

GRANT ALL PRIVILEGES ON mydatabase.* TO ‘myuser’@’localhost’;

3. Create a PHP file and establish a connection to the MySQL database:

<?php

$servername = “localhost”;

$username = “myuser”;

$password = “mypassword”;

$dbname = “mydatabase”;

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {

die(“Connection failed: ” . $conn->connect_error);

}

echo “Connected successfully”;

?>

4. Create a table in the database:

CREATE TABLE users (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

firstname VARCHAR(30) NOT NULL,

lastname VARCHAR(30) NOT NULL,

email VARCHAR(50),

reg_date TIMESTAMP

);

5. Insert data into the table:

INSERT INTO users (firstname, lastname, email)

VALUES (‘John’, ‘Doe’, ‘john@example.com’);

6. Retrieve data from the table:

SELECT * FROM users;

7. Close the connection:

$conn->close();

PHP Functions

A PHP function is a block of statements that can be used repeatedly in a program. It is not executed when page is loaded, instead implemented when a function is called.

 

Function Syntax

Function function _name ()
{
Code to be executed;
}
 

Example

Function test()
{
Echo “hello”;
}
Test();
 

Function with arguments

Arguments or parameters are a piece of information, which is passed to function for executing the code. Functions can have any number of arguments, just separate them by comma.

 

Function test($fname)
{
Echo $fname;
}
Test(“janani”);

 

Default Argument Value

The default argument will be set, if a function is called without parameters.

 
Function test($fname=50)
{
Echo $fname;
}
Test();
 

Return value function

Return value function is used when a function has to return a value after code execution.

 
Function test ($a, $b)
{
Return $a+$b;
}
Echo Test(2,3);

PHP Form Validation

<?php
// define variables and set to empty values
$nameError = $emailError= $genderError = $websiteError = “”;
$name = $email = $gender = $comment = $website = “”;

if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
if (empty($_POST[“name”])) {
$nameError = “Name is required”;
} else {
$name = test_input($_POST[“name”]);
// check if name only contains letters and whitespace
if (!preg_match(“/^[a-zA-Z ]*$/”,$name)) {
$nameError = “Only letters and white space allowed”;
}
}

if (empty($_POST[“email”])) {
$emailError = “Email is required”;
} else {
$email = test_input($_POST[“email”]);
// check if e-mail address syntax is valid
if (!preg_match(“/([\w\-]+\@[\w\-]+\.[\w\-]+)/”,$email)) {
$emailError = “Invalid email format”;
}
}

if (empty($_POST[“website”])) {
$website = “”;
} else {
$website = test_input($_POST[“website”]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match(“/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i”,$website)) {
$websiteError = “Invalid URL”;
}
}

if (empty($_POST[“comment”])) {
$comment = “”;
} else {
$comment = test_input($_POST[“comment”]);
}

if (empty($_POST[“gender”])) {
$genderError = “Gender is required”;
} else {
$gender = test_input($_POST[“gender”]);
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation</h2>
<p><span class=”error”>* required field.</span></p>
<form method=”post” action=”<?php echo htmlspecialchars($_SERVER[“PHP_SELF”]);?>“> 
   Name: <input type=”text” name=”name”>
   <span class=”error”>* <?php echo $nameError;?></span>
   <br><br>
   E-mail: <input type=”text” name=”email”>
   <span class=”error”>* <?php echo $emailError;?></span>
   <br><br>
   Website: <input type=”text” name=”website”>
   <span class=”error”><?php echo $websiteError;?></span>
   <br><br>
   Comment: <textarea name=”comment” rows=”5″ cols=”40″></textarea>
   <br><br>
   Gender:
   <input type=”radio” name=”gender” value=”female”>Female
   <input type=”radio” name=”gender” value=”male”>Male
   <span class=”error”>* <?php echo $genderError;?></span>
   <br><br>
   <input type=”submit” name=”submit” value=”Submit”> 
</form>

<?php
echo “<h2>Your Input:</h2>”;
echo $name;
echo “<br>”;
echo $email;
echo “<br>”;
echo $website;
echo “<br>”;
echo $comment;
echo “<br>”;
echo $gender;
?>


</body>
</html>


 

PHP Form Validation

* required field.

Name:
*
E-mail:
*
Website:

Comment:

Gender:
Female
Male
*


Your Input:

Name
Test@gmail.com
www.example.com
Test Comment
Female

Simple Capcha using php

Capcha Code:

Save this code as “capcha.php”

[php]

<?php
session_start();
$text = rand(10000,99999);
$_SESSION[“vercode”] = $text;
$height = 25;
$width = 65;

$image_p = imagecreate($width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 14;

imagestring($image_p, $font_size, 5, 5, $text, $white);
imagejpeg($image_p, null, 80);
?>
[/php]

——————————————————————————————————
HTML:

<img src=”capcha.php” alt=”” align=”top” /> <input id=”vercode” class=”cap” name=”vercode” type=”text” align=”texttop” />
<div>

<input class=”sub” name=”subi” type=”submit” value=”Register” />

</div>

 

Must set session to use the capcha

PHP Code for the html page:

[php]
<?php if ($_POST[“vercode”] != $_SESSION[“vercode”])
{
header(“location:contact.php?ver”); //incorrect verification code }
?>
[/php]

PHP Sessions

Starting a PHP Session

  • The session_start() function must appear BEFORE the <html> tag:

[php]

<?php session_start(); ?>

<html>
<body>
</body>
</html>
[/php]

  • The above code is used to register the user session in server.

Destroying a Session

[php]
<?php
session_destroy();
?>
[/php]

  • The above code is used to destroy the complete session from the server.

NOTE :  The session is very very important to save the current user information on the server. Using UID(user id), The server saves the user information on the server.

Hide/Show using JavaScript

To hide the Div : style=”display:none”;

To visible the Div : style=”display:block”;

[php]
<html><head><script type="text/javascript">
function showdiv()
{
if(document.getElementById(‘child’).checked)
{
document.getElementById(‘adu’).style.display = "block";
}
else
{
document.getElementById(‘adu’).style.display = "none";
}
if(document.getElementById(‘adult’).checked)
{
document.getElementById(‘adu’).style.display = "none";
}
}
</script>
</head>
<table border="0">
<tbody>
<tr>
<td>Member Type</td>
<td>
<input id="adult" onclick="showdiv();" type="radio" name="member" value="Adult" />
<input id="child" onclick="showdiv();" type="radio" name="member" value="Child" /></td>
</tr>

<div id="adu" style="display:none">
<tr><td>Name</td><td><input type="text" value=""></td></tr>
</div>
</tbody>
</table>
</html>

[/php]

Output:

When you Click the Adult , you will not see the text box below.

When you click the child, the below text box will be visible.

Member Type Adult
 Child
Name   *

 

Validation Using Javascript

 [php]
<html>
<head>
<script type="text/javascript">
function vali()
{
if(document.myform.FirstName.value=="")
{
alert("Please enter the FirstName");
document.myform.FirstName.focus();
return false;
}
}
</script>
</head>
<form method="post" name="myform" onsubmit="return vali();">
Name : <input type="text" name="FirstName" />
<input type="submit" value="Submit" />
</form>
</html>
[/php]

Output:
Name :

Code to get Title and Link in WordPress RSS Feed using PHP

You would often want to display the RSS feed of your blog in your personalized home page or your professional page. This can be achieved, if you have basic knowledge on PHP and HTML.

Just copy and paste the code below in the section where you want the feed to appear:

[php]
<?PHP

$con = file_get_contents(‘http://www.xxxxxx.com/blog/feed/’);/* Feed Url */
$title = getlinks("<title>", "</title>", $con); // gets Title and stored in array
$url = getlinks("<link>", "</link>", $con); // gets Url and stored in array

echo "<ul>";
for($i=0; $i < 6; $i++) {
echo ‘<li><a href="’.$url[$i].’" title="’.$title[$i].’" >’.urldecode($title[$i]).'</a></li>’;
}
echo "</ul>";

function getlinks($s1,$s2,$s) {
$myarray=array();
$s1 = strtolower($s1);
$s2 = strtolower($s2);
$L1 = strlen($s1);
$L2 = strlen($s2);
$scheck=strtolower($s);

do {
$pos1 = strpos($scheck,$s1);
if($pos1!==false) {
$pos2 = strpos(substr($scheck,$pos1+$L1),$s2);
if($pos2!==false) {
$myarray[]=substr($s,$pos1+$L1,$pos2);
$s=substr($s,$pos1+$L1+$pos2+$L2);
$scheck=strtolower($s);
}
}
}
while (($pos1!==false)and($pos2!==false));
return $myarray;
}

?>

[/php]

Tags:

Explode function in php

How to split a name using explode function?
1. Get the name in a variable
2. Specify the position from which you need to split the name.
3. If you need to split the name after an underscore, use “_”.
4. If you need to split the name after @, use “@”.

[php]

<?php

$name  = "john_abraham@gmail.com";
$pieces = explode("_", $name);
echo "firstname = $pieces[0]"."<br />";

$pieces = explode("@", $name);
echo "username = $pieces[0]";

?>

[/php]

Output will be displayed as:
firstname = john
username = john_abraham

Tags:

IF Statement In PHP

[php]

<html>

<head>
<title>IF statements in PHP.</title>
</head>
<body>

<?php

$name = "Rose";

if ( $name == "Rose" )

echo "Your name is Rose!<br />";

else

echo "Welcome to my homepage!";
?>
</body>
</html>

[/php]

Output:

If the Given input is Rose,the output will be

Your name is Rose!

Else

Welcome to my homepage!

Request a Free SEO Quote