PHP

Insert and Update using function

$Order=array('id'=>'1');

mysql_insert_update($Order,'order','order_id',$_POST['order_id']); //for update

$id=mysql_insert_update($Order,'order'); //for insert

function mysql_insert_update($data, $table, $pid = '', $id = '') {
$sql = '';
if ($id == '') {
$key_arr = @implode ( ",", array_keys ( $data ) );
$val_arr = @implode ( "','", array_values ( $data ) );
$sql = "insert into ". $table ." ( " . $key_arr . " ) values ('" . $val_arr . "' )";
//echo $sql;exit;
$result = mysql_query ( $sql );
if (mysql_errno ()) {
echo $error = "MySQL error " . mysql_errno () . ": " . mysql_error () . "\n<br>When executing:<br><font color='red'>\n$sql\n</font><br>";
exit ();
} else {
return mysql_insert_id ();
}
} else {
$sql = "update " . $table . " set ";
foreach ( $data as $key => $value ) {
$sql .= $key . "='" . $value . "',";
}
$sql = substr ( $sql, 0, - 1 );
$sql .= " where " . $pid . " = '" . $id . "' ";
$result = mysql_query ( $sql );
if (mysql_errno ()) {
echo $error = "MySQL error " . mysql_errno () . ": " . mysql_error () . "\n<br>When executing:<br><font color='red'>\n$sql\n</font><br>";
exit ();
}
}
}
--------------------------------------------------------------------------------------------------------------

mysql_execute("enter query whatever") //insert update,delete

function mysql_execute($sql) {
$result = mysql_query ( $sql );
if (mysql_errno ()) {
echo $error = "MySQL error " . mysql_errno () . ": " . mysql_error () . "\n<br>When executing:<br><font color='red'>\n$sql\n</font><br>";
exit ();
}
return $result;
}
---------------------------------------------------------------------------------------------------------------
$array=mysql_fetch_data("enter select query") //get all data from table

function mysql_fetch_data($sql) {
$result = mysql_query ( $sql );
if (mysql_errno ()) {
echo $error = "MySQL error " . mysql_errno () . ": " . mysql_error () . "\n<br>When executing:<br><font color='red'>\n$sql\n</font><br>";
exit ();
}
$data = array ();
$cnt = 0;
while ( $row = mysql_fetch_assoc ( $result ) ) {
foreach ( $row as $key => $value ) {
$row [$key] = am_display ( $value );
}
// my_print_r($row);
$data [$cnt] = $row;
$cnt ++;
}
return $data;
}

--------------------------------------------------------------------------------------------------------------
encryption and decryption

function encrypt($sData, $sKey = 'PhpwebsiteDeveloper') {
$sResult = '';
for($i = 0; $i < strlen ( $sData ); $i ++) {
$sChar = substr ( $sData, $i, 1 );
$sKeyChar = substr ( $sKey, ($i % strlen ( $sKey )) - 1, 1 );
$sChar = chr ( ord ( $sChar ) + ord ( $sKeyChar ) );
$sResult .= $sChar;
}
return base64_encode ( $sResult );
}
function decrypt($sData, $sKey = 'PhpwebsiteDeveloper') {
$sResult = '';
$sData = base64_decode ( $sData );
for($i = 0; $i < strlen ( $sData ); $i ++) {
$sChar = substr ( $sData, $i, 1 );
$sKeyChar = substr ( $sKey, ($i % strlen ( $sKey )) - 1, 1 );
$sChar = chr ( ord ( $sChar ) - ord ( $sKeyChar ) );
$sResult .= $sChar;
}
return $sResult;
}

------------------------------------------------------------------------------------------------


EVERY 3 SECOND CHANGE THE IMAGE FROM DATABASE

Do connection with database itself then do.........
Table name >> cms_banner_master with this fields id,imagenm,onclick_url


//http://websitename/
//uploadfiles Stored images

$imageDir = '/websitename/uploadfiles/';
define('SERVERPATH', $_SERVER['DOCUMENT_ROOT'].$imageDir);
define('HTTPPATH', 'http://'.$_SERVER['HTTP_HOST'].$imageDir);


$array=array();
$linkarray=array();
$query=getdata("select imagenm,onclick_url from  cms_banner_master" );
while($rs=mysql_fetch_array($query))
{
$image=$rs['imagenm'];
$link=$rs['onclick_url'];
$array[]=$rs['imagenm'];
$linkarray[]=$rs['onclick_url'];
}

$dir = opendir(SERVERPATH);
$javascriptArray = null;
$JLINK=null;
$i = null;


foreach($array as $imagevalue)
{
   if (eregi('\.(gif|png|jpg)$',$imagevalue)){
  $javascriptArray .= $i.'"'.HTTPPATH.$imagevalue.'"';
       $i = ',';
    }
}
foreach($linkarray as $linkvalue)
{
$JLINK.=$linkvalue.',';
}
$JLINK=substr($JLINK, 0, -1);

closedir($dir);

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
        <title>Rotate Images</title>

<script type="text/javascript">
         function rotateImage(){
var linkImages='<?php echo $JLINK;?>'.split(',');
    rotatingImages = new Array(<?php echo $javascriptArray; ?>);
            imageCount = rotatingImages.length;
            firstTime = true;
            duration = "3"; //seconds
                // Cycle through images sequencially starting with a random image
                // Do not update the image if loading is not yet completed
                if (document.getElementById('rotatingImage').complete || firstTime){
                    if (firstTime) {
                        thisImage = Math.floor((Math.random() * imageCount))
                        firstTime = false
                    }else{
                        thisImage++
                        if (thisImage == imageCount) {
                            thisImage = 0
                        }
                    }
document.getElementById('rotatingImage').src = rotatingImages[thisImage]
for (var k=0;k<linkImages.length;k++)
{
  var a=document.getElementById('href').href=linkImages[thisImage];
}
 setTimeout("rotateImage()", duration * 1000)
                }
            }
        </script>


 </head>
    <body>
        <div id="slideshow">
<a id="href" target="_blank"><img  height="186" width="308"   id="rotatingImage"  alt="" /></a>
        </div>
        <script type="text/javascript">
            rotateImage();
        </script>
    </body>
</html>






------------------------------------------------------------------------------------------------------------------------
EVERY 3 SECOND CHANGE THE IMAGE FROM DIRECTORY
<?php
// PHP section

// set some variables
// Image directory! fill in! relative to root

//http://localhost/time/
//slides  stored images

$imageDir = '/time/slides/'; 
define('SERVERPATH', $_SERVER['DOCUMENT_ROOT'].$imageDir);
define('HTTPPATH', 'http://'.$_SERVER['HTTP_HOST'].$imageDir);
// read the names of images from the image directory

$files=array('1.jpg','2.jpg');

$dir = opendir(SERVERPATH);
$javascriptArray = null;
$i = null;
foreach($files as $imagevalue)
{
   if (eregi('\.(gif|png|jpg)$',$imagevalue)){
 $javascriptArray .= $i.'"'.HTTPPATH.$imagevalue.'"'; 
       $i = ',';
    }
}

closedir($dir);

// Html section
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
        <title>Rotate Images</title>
        <script type="text/javascript">
            rotatingImages = new Array(<?php echo $javascriptArray; ?>);
            imageCount = rotatingImages.length;
            firstTime = true;
            duration = "3"; //seconds
        
            function rotateImage(){
                // Cycle through images sequencially starting with a random image
                // Do not update the image if loading is not yet completed
                if (document.getElementById('rotatingImage').complete || firstTime){
                    if (firstTime) {
                        thisImage = Math.floor((Math.random() * imageCount))
                        firstTime = false
                    }else{
                        thisImage++
                        if (thisImage == imageCount) {
                            thisImage = 0
                        }
                    }
                    document.getElementById('rotatingImage').src = rotatingImages[thisImage]
                    setTimeout("rotateImage()", duration * 3000)
                }
            }
        </script>
      
    </head>
    <body>
        <div id="slideshow">
            <img id="rotatingImage" src="" alt="" height="200" width="200">
        </div>
        <script type="text/javascript">
            rotateImage();
        </script>
    </body>
</html>
--------------------------------------------------------------------------------------------------------------------------
DYNAMIC FORM PROCESSING WITH PHP
http://techstream.org/Web-Development/PHP/Dynamic-Form-Processing-with-PHP
-------------------------------------------------------------------------------------------------------------------------
ADD HTTP IN URL IF DOES NOT EXIST
<?

if (preg_match("#^http://www\.[a-z0-9-_.]+\.[a-z]{2,4}$#i",$link))

{

      $link=$link;

}

if (preg_match("#^www\.[a-z0-9-.]+\.[a-z]{2,4}$#i",$link) || (preg_match("#^[a-z0-9-.]+\.[a-z]{2,4}$#i",$link)))

{

      $link="http://".$link;



 ?>
------------------------------------------------------------------------------------------------------
AJAX WITH POST
<script language="JavaScript" type="text/javascript">
function sendmail()
{
var xmlhttp;

    var name1 = document.getElementById("name").value;
    var email1 = document.getElementById("email").value;
  
    var par="?name="+name1+"&email="+email1";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    alert(xmlhttp.responseText);
    return false;
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("POST","email.php,true);
xmlhttp.send(par);
}
</script>

------------------------------------------------------------------------------------------------------------
if (isset($_FILES["img_upload"]))
if ($_FILES["img_upload"]["name"] != "")
{
//$ext = strrev(substr(strrev($_FILES["img_upload"]["name"]),0,3));

$parts=explode(".", $_FILES["img_upload"]["name"]);
     $ext=$parts[count($parts)-1];

$destfilenm = "p1_id".$action.".$ext";
copy($_FILES["img_upload"]["tmp_name"],"../storeuploadfiles/product/store_$current_store_id/". $destfilenm);
   
    
      $destfilenm_small = "p1_thumb_id".$action. ".$ext";
      $image = new SimpleImage();
      $image->load($_FILES['img_upload']['tmp_name']);
      $image->resizeToWidth(90);
      $image->resizeToHeight(90);
      $image->save("../storeuploadfiles/product/store_$current_store_id/thumbnail/".$destfilenm_small);


 $sSQL = "update ".$storeproductmaster." set photo2='$destfilenm',photo2_thumbnail='$destfilenm_small' where productid=$action";

 execute($sSQL);

}




---------------------------------------------------------------------

delete all files and folders within, and then finally removes the directory. 

function delete_directory($dirname) {
       if (is_dir($dirname))
          $dir_handle = opendir($dirname);
       if (!$dir_handle)
          return false;
       while($file = readdir($dir_handle)) {
          if ($file != "." && $file != "..") {
             if (!is_dir($dirname."/".$file))
                unlink($dirname."/".$file);
             else
                delete_directory($dirname.'/'.$file);    
          }
       }
       closedir($dir_handle);
       rmdir($dirname);
       return true;
    }
---------------------------------------------------------------------------------------------------

How to store array in mysql?

This is one of the mostly asked question by php programmer because mysql doesn't has any array data type. So we can not store array directly into mysql database.
To do this we have to first convert array into string using php serialize() function then save it into mysql database.

php code to store array in database

1
2
3
4
5
6

<?
$array = array("foo", "bar", "hello", "world");
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$array_string=mysql_escape_string(serialize($array));
mysql_query("insert into table (column) values($array_string)",$conn);
?>

 

 

 

 To retrieve array from database

1
2
3
4
5
6
7
8
9
10
<?
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$q=mysql_query("select column from table",$conn);
while($rs=mysql_fetch_assoc($q))
{
$array= unserialize($rs['column']);
print_r($array);
}
?>









-------------------------------------------------------------------------------
GET THE IMAGE EXTENSION

$parts=explode(".", $_FILES["img_upload"]["name"]); echo $parts[count($parts)-1];

------------------------------------------------------------------------------
PIN PAYMENT CREDIT CARD CODE
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://test-api.pin.net.au/1/charges");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_CERTINFO, true);

// downloaded from http://curl.haxx.se/docs/caextract.html
$crt = getcwd() . '/cacert.pem';

// specify CAINFO to allow HTTPS
curl_setopt($ch, CURLOPT_CAINFO, $crt);
curl_setopt($ch, CURLOPT_USERPWD, "YOUR_TEST_SECRET_API_KEY");

$fields = array(
  'amount' => '400',
  'description' => 'test charge',
  'email' => 'roland@pin.net.au',
  'ip_address' => '203.192.1.172',
  'card' => array(
    'number' => '5520000000000000',
    'expiry_month' => '05',
    'expiry_year' => '2013',
    'cvc' => '123',
    'name' => 'Roland Robot',
    'address_line1' => '42 Sevenoaks St',
    'address_city' => 'Lathlain',
    'address_postcode' => '6454',
    'address_state' => 'WA',
    'address_country' => 'AU'
  )
);


$postData = json_encode($fields);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

$response = curl_exec($ch); curl_close($ch);
$jsonResponse = json_decode($response, true);
$sucess = $jsonResponse["response"]["status_message"];

echo "Response: ";
var_dump($response);

--------------------------------------------------------------------------------
CRAWLING DATA FETCH FROM SITE
function getHTML($url,$timeout)
{
       $ch = curl_init($url); // initialize curl with given url
       curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set  useragent
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any
       curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
       curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
       return @curl_exec($ch);
}

function getHTML($url,$timeout)

{

       $ch = curl_init($url); // initialize curl with given url

       curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set  useragent

       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable

       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any

       curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute

       curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error

       return @curl_exec($ch);

}

$html=getHTML("http://www.website.com",10);
// Find all images on webpage
foreach($html->find("img"as $element)
echo $element->src . '<br>';
// Find all links on webpage
foreach($html->find("a"as $element)
echo $element->href . '<br>';


I hope this working

-----------------------------------------------------------------------------------------------------

CURL REQUEST WITH PHP

------------------------------------------------------------------------------------------------------

WRITE TO EXCEL SHEET FROM MYSQL 

<?php
//db.php connection to your database

 CREATE CONNECTION FIRST

// Query to get results from mysql table
$res =getdata("SELECT s_id,s_name FROM school_tbl where currentstatus=0 order by s_id");
//$res = mysql_query($query);

// Functions for export to excel.
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
return;
}
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
// Unique file name with datetime
$file_name = "csv-".date('dmy-His');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=$file_name.xls ");
header("Content-Transfer-Encoding: binary ");

xlsBOF();

// Top of the excel sheet to write header
//xlsWriteLabel(0,0,"User Data - CSV");
// Make column labels. (at line 3)
xlsWriteLabel(0,0,"School");
xlsWriteLabel(0,1,"Address");

// To start writing from row three from top
$xlsRow = 1;

// Put data records from mysql by while loop.
while($row=mysql_fetch_array($res)){
xlsWriteNumber($xlsRow,0,$row['s_id']);// 0 indicates column number
xlsWriteLabel($xlsRow,1,$row['s_name']);
$xlsRow++;
}
xlsEOF();
exit();
?>
------------------------------------------------------------------------------------------------

GET THE YOU TUBE VIDEO FROM DATABASE

$link=$rs['link']; //you tube url from database
$vid_url = $link;
$wdth='300';
$hth='300';
preg_match('/(?<=v=)[^&]+/', $vid_url, $vid_id);
$url=$vid_id[0];
echo  ('<iframe src="http://www.youtube.com/embed/'.$url.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');

--------------------------------------------------------------------------------------------------

How to Create a PHP AutoLogin (‘Remember Me’) Feature using Cookies

http://www.bitrepository.com/php-autologin.html

-----------------------------------------------------------------------------------------------------

HTML/PHP Dynamic DropDown with countries

http://www.bitrepository.com/category/php-mysql/page/4

---------------------------------------------------------------------------------------------------------

PHP: Detecting Google Chrome Browser

http://www.bitrepository.com/category/php-mysql/page/5

PHP: How to extract numbers from a string (text)

http://www.bitrepository.com/category/php-mysql/page/5


How to extract domain name from an e-mail address string

<?php
function getDomainFromEmail($email)
{
// Get the data after the @ sign
$domain = substr(strrchr($email, "@"), 1);

return $domain;
}

// Example

$email = 'the_username_here@yahoo.com';

$domain = getDomainFromEmail($email);

echo $domain; // yahoo.com
?>

How to remove an extension from a filename

<?php
/* 
Source: Bit Repository (http://www.bitrepository.com/)
*/
function remove_filename_extension($filename)
{
$extension = strrchr($filename, ".");

$filename = substr($filename, 0, -strlen($extension));

return $filename;
}

$filename = 'This-is-a-photo-description.jpeg';

$str = remove_filename_extension($filename);

echo $str;
?>

How to make a selection based on the ending value

SELECT * FROM `your_table_here` WHERE field_table REGEXP 'string_here$';

For begining

SELECT * FROM `your_table_here` WHERE field_table REGEXP 'string_here$';


Get filename extension

<?php
... some code here ...
// Filename
$filename = 'public_html/root/internet.gif';
// Extension
$ext = strrchr($filename, ".");
echo $ext; // will return ".gif"
?>

DOWNLOADING CODE


//Please give the Path like this

$file = '../uploadresource/'.$_GET['file'];



if (file_exists($file)) {

header('Content-Description: File Transfer');

header('Content-Type: application/octet-stream');

header('Content-Disposition: attachment; filename='.basename($file));

header('Content-Transfer-Encoding: binary');

header('Expires: 0');

header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

header('Pragma: public');

header('Content-Length: ' . filesize($file));

ob_clean();

flush();

readfile($file);

exit;

}

Create a Basic Web Service Using PHP, MySQL, XML, and JSON

http://davidwalsh.name/web-service-php-mysql-xml-json


Create a Zip File Using PHP

http://davidwalsh.name/create-zip-php

CREATE THUMBLE IMAGE
http://davidwalsh.name/create-image-thumbnail-php


Checking For Leap Year Using PHP

function is_leap_year($year)
{
 return ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0)));
}


PHP Function – Calculating Days In A Mont

function get_days_in_month($month, $year)
{
   return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}

GET IMAGE WIDTH,HEIGHT
<?php

$test=list($width, $height, $type, $attr) = getimagesize("../images/Banner-WebResSharp/IMG_4018.jpg");
echo "Image width " .$width;
echo "<BR>";
echo "Image height " .$height;
echo "<BR>";
echo "Image type " .$type;
echo "<BR>";
echo "Attribute " .$attr;

?>

Test php mail function on your localhost

http://www.phpeasystep.com/phptu/23.html


Delete multiple rows from mysql with checkbox

http://www.phpeasystep.com/mysql/8.html


Create Captcha Verification in PHP

http://sharp-coders.com/web-development/create-captcha-verification-in-php


How to Process Credit Cards with PayPal Payments Pro Using PHP


http://net.tutsplus.com/tutorials/php/how-to-process-credit-cards-with-paypal-payments-pro-using-php/


Send Email Using PHPMailer

http://www.computersneaker.com/send-email-using-phpmailer/

Pagination IN PHP

http://papermashup.com/easy-php-pagination/#


GOOLE WEBSITE  TRANSLATOR

https://translate.google.com/manager/website/


No comments:

Post a Comment