Home / Archive by category 'PHP/MySQL Tutorials'

PHP/MySQL Tutorials

hypertext pre processor – php

Selecting a MongoDB database in PHP

After connecting to the database server, you can obtain a handle to the database using the following syntax.

$db = $connection->selectDB('databasename');

A shorthand way to selecting a database is as follows:

$db = $connection->databasename;

If there is no database with the specified name, MongoDB will automatically create it.


Connecting to a MongoDB Database Server in PHP

After installing the MongoDB database, use the following code to connect to the MongoDB database.

$connection = new Mongo();

The above code connects to the database using default credentials.i.e host is localhost and port is 27017.

To explicitly connect to a remote host where MongoDB is housed, use the following syntax.

$connection = new Mongo( "172.20.10.8:65018" );

Connect to MySql and select database using PHP

The following code is an example of how to connect to a mysql server and select a database to query. We should always free up resources you don’t need anymore i.e make sure that mysql_close() executes at the end. This makes your code more efficient and reduces the possibility of errors.

<?php
$DB_HOST = "localhost";
$DB_NAME = "db";
$DB_USER = "user";
$DB_PASSWORD = "pass";
$con = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD);
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db($DB_NAME , $con);
mysql_close($con);
?>

Google Maps API to calculate location distance in PHP

This example shows how to use the Google maps API to calculate distance between two places in PHP

$result = file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Raleigh,NC&sensor=false');
$result = json_decode($results);
$distance = $result->routes->legs->distance['text'];
echo $distance // Outputs: "xxx mi"

Read JSON from file in PHP

$file = new File('/path/to/file');
$myjson = $file->read(true, 'r');
$myjsonarray = json_decode($json);

Write JSON to file in PHP

$json = '{"key":"value"}';
$file = new File('/path/to/file', true);
$file->write($json);

Type Validation Functions in PHP

is_array() – Test for Arrays
is_bool() – Test for Booleans (TRUE, FALSE)
is_float() – Test for Floating-point numbers
is_int() – Test for Integers
is_null() – Test for NULLs
is_numeric() – Test forNumeric values, even as a string (e.g., ‘ 20′ )
is_resource() – Test for Resources, like a database connection
is_scalar() – Test for Scalar (single-valued) variables
is_string() – Test for Strings


Urlencoding in PHP using urlencode

<?php
$myurlparam = "hello this is a test message";
$site = "http://www.w3mentor.com";
$query = $site;
$query .= "&message=".urlencode( $myurlparam );
echo $query;
?>

Compare two arrays to see if value from form post exists in PHP

<?php
$choices = array('my choice 1', 'my choice 2', 'my choice 3');
 
$valid = true;
if (is_array($_GET['inputArray'])) {
    $valid = true;
    foreach($_GET['inputArray'] as $input) {
        if (!in_array($input, $choices)) {
           $valid = false;
        }
    }
 
	if ($valid) {
       echo "Input Value were found in choices";
    }
}
?>

Using Radio buttons in PHP Form

<html>
<body>                                  
 
<form action="mychoice.php" method="post">                                                
   <b>Enter Name:</b>           
   <input type="text" size="45" name="username">  <br>
   <b>Please select your favorite animal:</b> <br>             
   <input type="radio" name="animal" value="dog">Dog           
   <input type="radio" name="animal" value="cat">Cat
   <input type="radio" name="animal" value="fish">Fish <br>
   <input type="submit" value="Submit">
</form>            
 
</body>
</html>

File: mychoice.php

<html>
 <head>
  <title>Form submission</title>
 </head>
 <body>
 <br>
 
 <?php
  $username = $_POST['username'];
  $animal =    $_POST['animal'];
 
  if(($animal != null))
  {
    $msg = "The animal you chose is $animal <br>";
    echo($msg);
  }
 ?>
 
 </body>
</html>

Radio button validation in PHP using array_key_exists

<?php
$animals = array('dog' => 'D',
                 'cat' => 'C',
                 'bird' => 'B');
foreach ($animals as $key => $animal) {
   echo "<input type='radio' name='animal' value='$key'/> $animal \n";
}
 
if (!array_key_exists($_POST['animal'], $animals)) {
    echo "You must select a valid animal.";
}
?>

Traversing Arrays Using foreach in PHP

$users = array("Mani", "Nani", "Item", "Raja");
print "The users are:\n";
foreach ($users as $key => $value) {
print "#$key = $value\n";
}

Output:
The players are:
#0 = Mani
#1 = Nani
#2 = Item
#3 = Raja


Accessing string offsets in PHP

$str = "M";
$str{2} = "n";
$str{1} = "a";
$str = $str . "i";
print $str;

The above code will output “Mani”. Individual characters in a string can be accessed using the $str{offset} notation. You can use it to both read and write string offsets.


Output large amount of text in PHP

ob_start();         
 
echo 'Put your text here';
 
$body = ob_get_contents();
ob_end_clean(); 
 
echo $body;

Determine user’s IP Address with proxy in PHP

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

Strip defined HTML tags from PHP input

function strip_html_tags( $text )
{
    $text = preg_replace(
        array(
          // Remove invisible content
            '@<head[^>]*?>.*?</head>@siu',
            '@<style[^>]*?>.*?</style>@siu',
            '@<script[^>]*?.*?</script>@siu',
            '@<object[^>]*?.*?</object>@siu',
            '@<embed[^>]*?.*?</embed>@siu',
            '@<applet[^>]*?.*?</applet>@siu',
            '@<noframes[^>]*?.*?</noframes>@siu',
            '@<noscript[^>]*?.*?</noscript>@siu',
            '@<noembed[^>]*?.*?</noembed>@siu',
          // Add line breaks before and after blocks
            '@</?((address)|(blockquote)|(center)|(del))@iu',
            '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
            '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
            '@</?((table)|(th)|(td)|(caption))@iu',
            '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
            '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
            '@</?((frameset)|(frame)|(iframe))@iu',
        ),
        array(
            ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
            "
$0", "
$0", "
$0", "
$0", "
$0", "
$0",
            "
$0", "
$0",
        ),
        $text );
 }

Generate Random String of desired length in PHP

function getCode($length=12) {
 
    //Ascii Code for number, lowercase, uppercase and special characters
    $no = range(48,57); 
    $lo = range(97,122);
    $up = range(65,90); 
 
    //exclude character I, l, 1, 0, O
    $eno = array(48, 49);
    $elo = array(108);
    $eup = array(73,79);
    $no = array_diff($no,$eno);
    $lo = array_diff($lo,$elo);
    $up = array_diff($up,$eup);
    $chr = array_merge($no, $lo, $up);
 
 
    for ($i=1;$i<=$length;$i++) {
 
        $code.= chr($chr[rand(0,count($chr)-1)]);   
    }
    return $code;
}

Codeigniter escape_like_str() function

This function is useful when strings are used in the LIKE portion of your query. This enables the wildcards to be correctly escaped along with the string. Here’s
an example of its usage:

$like = 'w3m' ;
$sql = " SELECT id FROM table
  WHERE column LIKE ' %" . $this- >db->escape_like_str($like) . "%' ";
$this->db- >query($sql) ;

Codeigniter escape_str() function

This function will escape all data, regardless of type.

$sql = " INSERT INTO table (name)
  VALUES(" . $this->db->escape_str( $name) . " ) " ;
$this->db- >query($sql) ;

Codeigniter escape() function

This function will determine the data type so that it can properly escape only string data. It will automatically add single quotes around the data so you don’t have to.
Here’s how you would use it:

$sql = " INSERT INTO table (name)
  VALUES(" . $this->db->escape($name) . ") ";
$this->db- >query($sql) ;