Sunday, July 1, 2012

PHP Database Access


Create the database in MySQL



PHP with databases access, we have chosen MySQL database because it is free and also because it is the most widely used in UNIX environment. To this end, the server where the pages are hosted must provide us with tools to create the database or have access to Telnet.
The command to create a MySQL database is the following: mysqladmin -u root create data_base

To create the table you can use your web server's MySQL administration tool or you can write a text file with the content of the equivalent SQL and then indicate the database engine to execute it with the following instruction: mysql -u root base_datos <test.sql

Connection to the database


<html> 
<head> 
   <title>PHP SWT Example</title> 
</head> 
<body> 
<?php
function Connect()
{
   if (!($link=mysql_connect("localhost","root","")))
   {
      echo "Error connecting to server.";
      exit();
   }
   if (!mysql_select_db("base_datos",$link))
   {
      echo "Error Selecting database.";
      exit();
   }
   return $link;
}

$link=Conectarse();
echo "Connection Success.<br>";

mysql_close($link); //cierra la conexion
?>
 
</body> 
</html> 


Querying the database


<?php 
function Connect() 

   if (!($link=mysql_connect("localhost","root",""))) 
   { 
       echo "Error connecting to server.";   
      exit(); 
   } 
   if (!mysql_select_db("base_datos",$link)) 
   { 
       echo "Error Selecting database.";  
       exit(); 
   } 
   return $link; 

?>


<html> 
<head> 
   <title>PHP SWT Example</title> 
</head> 
<body> 
<H1>Ejemplo de uso de bases de datos con PHP y MySQL</H1> 
<?php
   include("connection.phtml");
   $link=Conect();
   $result=mysql_query("select * from users",$link);
?>
 
   <TABLE BORDER=1 CELLSPACING=1 CELLPADDING=1> 
      <TR><TD>&nbsp;ID</TD><TD>&nbsp;Username&nbsp;</TD></TR> 
<?php     

   while($row = mysql_fetch_array($result)) {
      printf("<tr><td>&nbsp;%s</td><td>&nbsp;%s&nbsp;</td></tr>", $row["id"],$row["username"]);
   }
   mysql_free_result($result);
   mysql_close($link);
?>
 
</table> 
</body> 
</html> 


Inserting records to the database


<?php
   include("connection.phtml");
   $link=Conect();
   $id=$_GET['id'];
   $username=$_GET['username'];  
   mysql_query("insert into users(id,username) values ('$id','$username')",$link);
  
   header("Location: thanks.phtml");
?>
 




Thursday, June 28, 2012

Introduction to Preg in PHP

The PHP function, preg_grep, is used to search an array for specific patterns and then return a new array based on that filtering. There are two ways to return the results. You can return them as is, or you can invert them (instead of only returning what matches, it would only return what does not match.) It is phrased as: preg_grep ( search_pattern, $your_array, optional_inverse ) The search_pattern needs to be a regular expression. If you are unfamiliar with them This Article gives you an overview of the syntax.
 <? 
 $data = array(0, 1, 2, 'three', 4, 5, 'six', 7, 8, 'nine', 10); 
 $mod1 = preg_grep("/4|5|6/", $data); 
 $mod2 = preg_grep("/[0-9]/", $data, PREG_GREP_INVERT); 
 print_r($mod1); 
 echo "<br>"; 
 print_r($mod2); 
 ?> 
This code would result in the following data:
Array ( [4] => 4 [5] => 5 ) 
Array ( [3] => three [6] => six [9] => nine )



First we assign our $data variable. This is a list of numbers, some in alpha form, others in numeric. The first thing we run is called $mod1. Here we are searching for anything that contains 4, 5, or 6. When our result is printed below we only get 4 and 5, because 6 was written as 'six' so it did not match our search.
Next we run $mod2, which is searching for anything that contains a numeric character. But this time we include PREG_GREP_INVERT. This will invert our data, so instead of outputting numbers, it outputs all of our entries that where not numeric (three, six and nine).
Preg_Match : 
The Preg_Match PHP function is used to search a string, and return a 1 or 0. If the search was successful a 1 will be returned, and if it was not found a 0 will be returned. Although other variables can be added, it is most simply phrased as: preg_match(search_pattern, your_string). The search_pattern needs to be a regular expression.

 <? 
 $data = "I had a box of cerial for breakfast today, and then I drank some juice.";
 if (preg_match("/juice/", $data))
 {
 echo "You had juice.<br>";
 }
 else
 {
 echo "You had did not have juice.<br>";
 }
 if (preg_match("/eggs/", $data))
 {
 echo "You had eggs.<br>";
 }
 else
 {
 echo "You had did not have eggs.<br>";
 } 
 ?>
The code above uses preg_match to check for a key word (first juice then egg) and replies based on whether it is true (1) or false (0). Because it returns these two values it is most often used in a conditional statement
Preg_Match_All :
Preg_Match_All is used to search a string for specific patterns and stores the results in an array. Unlike preg_match which stops searching after it finds a match, preg_match_all searches the entire string and records all matches. It is phrased as: preg_match_all (pattern, string, $array, optional_ordering, optional_offset)
 <? $data = "The party will start at 10:30 pm and run untill 12:30 am"; 
 preg_match_all('/(\d+:\d+)\s*(am|pm)/', $data, $match, PREG_PATTERN_ORDER);
 echo "Full: <br>"; 
 print_r($match[0]); 
 echo "<p>Raw: <br>"; 
 print_r($match[1]); 
 echo "<p>Tags: <br>"; 
 print_r($match[2]); 
 ?> 
In our first example we use PREG_PATTERN_ORDER. We are searching for 2 things; one is the time, the other is it's am/pm tag. Our results are outputted to $match, as an array where $match[0] contains all matches, $match[1] contains all data matching our first sub-serach (the time) and $match[2] contains all data matching our second sub-search (am/pm).
 <? $data = "The party will start at 10:30 pm and run untill 12:30 am"; 
 preg_match_all('/(\d+:\d+)\s*(am|pm)/', $data, $match, PREG_SET_ORDER); 
 echo "First: <br>"; 
 echo $match[0][0] . " , " . $match[0][1] . " , ". $match [0][2] ."<br>"; 
 echo "Second: <br>"; 
 echo $match[1][0] . " , " . $match[1][1] . " , ". $match [1][2] ."<br>";
 ?> 
In our second example we use PREG_SET_ORDER. This puts each full result into an array. The first result is $match[0], with $match[0][0] being the full match, $match[0][1] being the first sub-match and $match[0][2] being the second sub-match.

Preg_replace :
The preg_replace function is used to do a find-and-replace on a string or an array. We can give it one thing to find and replace (for example it seeks out the word 'him' and changes it to 'her') or we can give it a full list of things (an array) to search for, each with a corresponding replacement. It is phrased as preg_replace ( search_for, replace_with, your_data , optional_limit, optional_count ) The limit will default to -1 which is no limit. Remember your_data can be a string or an array.
<? 
 $data = "The cat likes to sit on the fence. He also likes to climb the tree."; 
 
 $find ="/the/"; 
 $replace ="a"; 
 
 //1. replace single word 
 Echo "$data <br>"; 
 Echo preg_replace ($find, $replace, $data); 
 
 //create arrays 
 $find2 = array ('/the/', '/cat/'); 
 $replace2 = array ('a', 'dog'); 
 
 //2. replace with array values 
 Echo preg_replace ($find2, $replace2, $data); 
 
 //3. Replace just once
 Echo preg_replace ($find2, $replace2, $data, 1); 
 
 //4. Keep a count of replacements 
 $count = 0; 
 Echo preg_replace ($find2, $replace2, $data, -1, $count); 
 Echo "<br>You have made $count replacements"; 
 
 ?> 
In our first example we simply replace 'the' with 'a'. As you can see these are cAse seNsiTIvE. Then we set up an array, so in our second example we are replacing both the words 'the' and 'cat'. In our third example, we set the limit to 1, so each word is only replaced one time. Finally in our 4th example, we keep count of how many replacements we have made.
Preg_Spilit :
The function Preg_Spilit is used to take a string, and put it into an array. The string is broken up into different values in the array based upon your input. It is phrased as preg_split ( split_pattern, your_data, optional_limit, optional_flags )
 <?php 
 $str = 'I like goats. You like cats. He likes dogs.'; 
 $chars = preg_split('//', $str); 
 print_r($chars); 
 echo "<p>"; 
 $words= preg_split('/ /', $str); 
 print_r($words); 
 echo "<p>"; 
 $sentances= preg_split('/\./', $str, -1 , PREG_SPLIT_NO_EMPTY); 
 print_r($sentances); 
 ?> 
In the code above we preform three splits. In our first, we split the data by each character. In the second, we split it with a blank space, thus giving each word (and not each letter) an array entry. And in our third example we use a '.' period to split the data, therefor giving each sentence it's own array entry.
Because in our last example we use a '.' period to split, a new entry is started after our final period, so we add the flag PREG_SPLIT_NO_EMPTY so that no empty results are returned. Other available flags are PREG_SPLIT_DELIM_CAPTURE which also captures the character you are splitting by (our "." for example) and PREG_SPLIT_OFFSET_CAPTURE which captures the offset in characters where the split has occurred.




Send Mail using SMTP with PHPMailer and GMail


Website owners can use their own SMTP server for sending email messages from their website, but it makes sense even than to use GMail for sending mail. The chance is big that your websites IP address is on a blacklist if your site is on hosted by a shared web hosting provider. If not or you host your site on your own server, there is always a risk that your IP address get blacklisted. Because of some limitations, the SMTP server from Google is a good choice applications with less than 500 recipients a day


Requirements

You need for this PHPMailer code example a PHP5 enabled web host (I did tests only on Linux), the port 465 need to be open and of course you need a GMail or Google Apps account.


PHPMailer tutorial for GMail and Google Apps

GMail account or setup your domain for Google applications.
Download a recent version of PHPMailer (I’m using the version 5.02)
Check with your web hosting provider that port 465 (TCP out) is open, if not ask him to open that port
Include the PHPMailer class file: require_once('phpmailer/class.phpmailer.php');
Create those two constant variables to store your GMail login and password. Use the login for your Google Apps mail account if you have one.
define('GUSER', 'you@gmail.com'); // GMail username
define('GPWD', 'password'); // GMail password
Use the following function to send the e-mail messages (add the function in one of your included files):

function smtpmailer($to, $from, $from_name, $subject, $body) { 
global $error;
$mail = new PHPMailer();  // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;  // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465; 
$mail->Username = GUSER;  
$mail->Password = GPWD;           
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo; 
return false;
} else {
$error = 'Message sent!';
return true;
}
}


Call the function within your code:
smtpmailer('to@mail.com', '', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!');
Use this more “advanced” usage inside your application:

if (smtpmailer('to@mail.com', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!')) {
// do something
}
if (!empty($error)) echo $error;




Tuesday, June 26, 2012

Optimizing PHP Code


Optimized and more efficient PHP code

  1. echo is faster than print.
  2. require_once() is expensive
  3. If a method can be static, declare it static. Speed improvement is by a factor of 4.
  4. Unset your variables to free memory, especially large arrays.
  5. Use echo's multiple parameters instead of string concatenation.
  6. Set the maxvalue for your for-loops before and not in the loop.
  7. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
  8. Avoid magic like __get, __set, __autoload
  9. Use full paths in includes and requires, less time spent on resolving the OS paths.
  10. If you need to find out the time when the script started executing, INSERT:CONTENT:END SERVER['REQUEST_TIME'] is preferred to time()
  11. See if you can use strncasecmp, strpbrk and stripos instead of regex
  12. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
  13. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
  14. It's better to use select statements than multi if, else if, statements.
  15. Error suppression with @ is very slow.
  16. Turn on apache's mod_deflate
  17. Close your database connections when you're done with them
  18. $row['id'] is 7 times faster than $row[id]
  19. Error messages are expensive
  20. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
  21. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
  22. Incrementing a global variable is 2 times slow than a local var.
  23. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
  24. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  25. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  26. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
  27. Methods in derived classes run faster than ones defined in the base class.
  28. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++operations. A similar method call is of course about 15 $localvar++ operations.
  29. Surrounding your string by ' instead of “ will make things interpret a little faster since php looks for variables inside ”..." but not inside '...'. Of course you can only do this when you don't need to have variables in the string.
  30. When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
  31. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
  32. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
  33. Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
  34. When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.

    Example:if (strlen($foo) < 5) { echo "Foo is too short"; }



    vs.

    if (!isset($foo{5})) { echo "Foo is too short"; }

    Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.
  35. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
  36. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
  37. Do not implement every data structure as a class, arrays are useful, too
  38. Don't split methods too much, think, which code you will really re-use
  39. You can always split the code of a method later, when needed
  40. Make use of the countless predefined functions
  41. If you have very time consuming functions in your code, consider writing them as C extensions
  42. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
  43. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%

Tuesday, June 19, 2012

PHP Array Functions


array_chunk() Definition and Usage
The array_chunk() function splits an array into chunks of new arrays. Syntax
array_chunk(array,size,preserve_key)
Parameter Description
array Required. Specifies the array to use
size Required. Specifies how many elements each new array will contain
preserve_key Optional. Possible values:
  • true - Preserves the keys from the original array.
  • false - Default. Does not preserve the keys from the original array.

Example 1

<?php
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow");
print_r(array_chunk($a,2));
?>

The output of the code above will be:

Array (
[0] => Array ( [a] => Cat [b] => Dog )
[1] => Array ( [c] => Horse [d] => Cow )
)

Example 2

<?php
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow");
print_r(array_chunk($a,2,true));
?>

The output of the code above will be:

Array (
[0] => Array ( [a] => Cat [b] => Dog )
[1] => Array ( [c] => Horse [d] => Cow )
)
Function Description PHP
array() Creates an array 3
array_change_key_case() Returns an array with all keys in lowercase or uppercase 4
array_chunk() Splits an array into chunks of arrays 4
array_combine() Creates an array by using one array for keys and another for its values 5
array_count_values() Returns an array with the number of occurrences for each value 4
array_diff() Compares array values, and returns the differences 4
array_diff_assoc() Compares array keys and values, and returns the differences 4
array_diff_key() Compares array keys, and returns the differences 5
array_diff_uassoc() Compares array keys and values, with an additional user-made function check, and returns the differences 5
array_diff_ukey() Compares array keys, with an additional user-made function check, and returns the differences 5
array_fill() Fills an array with values 4
array_filter() Filters elements of an array using a user-made function 4
array_flip() Exchanges all keys with their associated values in an array 4
array_intersect() Compares array values, and returns the matches 4
array_intersect_assoc() Compares array keys and values, and returns the matches 4
array_intersect_key() Compares array keys, and returns the matches 5
array_intersect_uassoc() Compares array keys and values, with an additional user-made function check, and returns the matches 5
array_intersect_ukey() Compares array keys, with an additional user-made function check, and returns the matches 5
array_key_exists() Checks if the specified key exists in the array 4
array_keys() Returns all the keys of an array 4
array_map() Sends each value of an array to a user-made function, which returns new values 4
array_merge() Merges one or more arrays into one array 4
array_merge_recursive() Merges one or more arrays into one array 4
array_multisort() Sorts multiple or multi-dimensional arrays 4
array_pad() Inserts a specified number of items, with a specified value, to an array 4
array_pop() Deletes the last element of an array 4
array_product() Calculates the product of the values in an array 5
array_push() Inserts one or more elements to the end of an array 4
array_rand() Returns one or more random keys from an array 4
array_reduce() Returns an array as a string, using a user-defined function 4
array_reverse() Returns an array in the reverse order 4
array_search() Searches an array for a given value and returns the key 4
array_shift() Removes the first element from an array, and returns the value of the removed element 4
array_slice() Returns selected parts of an array 4
array_splice() Removes and replaces specified elements of an array 4
array_sum() Returns the sum of the values in an array 4
array_udiff() Compares array values in a user-made function and returns an array 5
array_udiff_assoc() Compares array keys, and compares array values in a user-made function, and returns an array 5
array_udiff_uassoc() Compares array keys and array values in user-made functions, and returns an array 5
array_uintersect() Compares array values in a user-made function and returns an array 5
array_uintersect_assoc() Compares array keys, and compares array values in a user-made function, and returns an array 5
array_uintersect_uassoc() Compares array keys and array values in user-made functions, and returns an array 5
array_unique() Removes duplicate values from an array 4
array_unshift() Adds one or more elements to the beginning of an array 4
array_values() Returns all the values of an array 4
array_walk() Applies a user function to every member of an array 3
array_walk_recursive() Applies a user function recursively to every member of an array 5
arsort() Sorts an array in reverse order and maintain index association 3
asort() Sorts an array and maintain index association 3
compact() Create array containing variables and their values 4
count() Counts elements in an array, or properties in an object 3
current() Returns the current element in an array 3
each() Returns the current key and value pair from an array 3
end() Sets the internal pointer of an array to its last element 3
extract() Imports variables into the current symbol table from an array 3
in_array() Checks if a specified value exists in an array 4
key() Fetches a key from an array 3
krsort() Sorts an array by key in reverse order 3
ksort() Sorts an array by key 3
list() Assigns variables as if they were an array 3
natcasesort() Sorts an array using a case insensitive "natural order" algorithm 4
natsort() Sorts an array using a "natural order" algorithm 4
next() Advance the internal array pointer of an array 3
pos() Alias of current() 3
prev() Rewinds the internal array pointer 3
range() Creates an array containing a range of elements 3
reset() Sets the internal pointer of an array to its first element 3
rsort() Sorts an array in reverse order 3
shuffle() Shuffles an array 3
sizeof() Alias of count() 3
sort() Sorts an array 3
uasort() Sorts an array with a user-defined function and maintain index association 3
uksort() Sorts an array by keys using a user-defined function 3
usort() Sorts an array by values using a user-defined function 3

PHP Array Constants

Constant Description PHP
CASE_LOWER Used with array_change_key_case() to convert array keys to lower case  
CASE_UPPER Used with array_change_key_case() to convert array keys to upper case  
SORT_ASC Used with array_multisort() to sort in ascending order  
SORT_DESC Used with array_multisort() to sort in descending order  
SORT_REGULAR Used to compare items normally  
SORT_NUMERIC Used to compare items numerically  
SORT_STRING Used to compare items as strings  
SORT_LOCALE_STRING Used to compare items as strings, based on the current locale 4
COUNT_NORMAL    
COUNT_RECURSIVE    
EXTR_OVERWRITE    
EXTR_SKIP    
EXTR_PREFIX_SAME    
EXTR_PREFIX_ALL    
EXTR_PREFIX_INVALID    
EXTR_PREFIX_IF_EXISTS    
EXTR_IF_EXISTS    
EXTR_REFS    

PHP HTML basic tips, tricks


PHP HTML basic tips and tricks

PHP is an HTML-embedded scripting language. The goal of the language is to allow web developers to write dynamically generated pages quickly. In the course of web development of using PHP PHP and HTML interact a lot. PHP can generate HTML, and HTML can pass information to PHP.

Encoding/decoding when passing a data through a form or URL
Certain characters, for example ‘&’, have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages.

Passing a value through HTML FORM you must include it in double quotes, and htmlspecialchars() the whole value. For exampe see the code below

<?php echo “<input name=’data’ type=’hidden’ value=’” . htmlspecialchars($data) . “‘>”; ?>

While passing a value through URL you must encode it with urlencode(). It will convert all non-alphanumeric characters except -_. with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. See example below.
<?php echo “<a href=’” . htmlspecialchars(“/nextpage.php?stage=23&data=” .urlencode($data) . “‘>\n”; ?>

Creating a PHP arrays in a HTML form

To get your FORM result sent as an array to your PHP script you name the INPUT, SELECT, TEXTAREA elements like this:
<input name=”MyArray[]“>
<input name=”MyArray[]“>
<input name=”MyArray[]“>
<input name=”MyArray[]“>

If you do not specify the keys, the array gets filled in the order the elements appear in the form. Above example will contain keys 0, 1, 2 and 3. Notice the square brackets after the variable name, that’s what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:
<input name=”MyArray[]“>
<input name=”MyArray[]“>
<input name=”MyOtherArray[]“>
<input name=”MyOtherArray[]“>
This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It’s also possible to assign specific keys to your arrays:
<input name=”AnotherArray[]“>
<input name=”AnotherArray[]“>
<input name=”AnotherArray[email]“>
<input name=”AnotherArray[phone]“>

The AnotherArray array will now contain the keys 0, 1, email and phone.

Getting results from a select multiple HTML tag.
The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.
<select name=”var” multiple=”yes”>
Each selected option will arrive at the action handler as var=option1, var=option2, var=option3. Each option will overwrite the contents of the previous $var variable. The solution is to use PHP’s “array from form element” feature. The following should be used:
<select name=”var[]” multiple=”yes”>
Now first item becomes $var[0], the next $var[1], etc.

Passing a variable from Javascript to PHP
Since Javascript is a client-side technology, and PHP is a server-side technology, the two languages cannot directly share variables. It is, however, possible to pass variables between the two. One way of accomplishing this is to generate Javascript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. The example below shows precisely how to do this — it allows PHP code to capture screen height and width, something that is normally only possible on the client side.
<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  // output the geometry variables
  echo “Screen width is: “. $_GET['width'] .”<br />\n”;
  echo “Screen height is: “. $_GET['height'] .”<br />\n”;
} else {
  // pass the geometry variables
  // (preserve the original query string
  //   — post variables will need to handled differently)

  echo “<script language=’javascript’>\n”;
  echo “  location.href=\”${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}”
            . “&width=\” + screen.width + \”&height=\” + screen.height;\n”;
  echo “</script>\n”;
  exit();
}
?> 

PHP Arrays Tutorials


PHP Arrays Tutorial and PHP Array Examples

An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.

PHP Array Syntax: Create an Array
language-construct array() is used to create an array in PHP. See example below

array( [key =>] value
  , …
  )
key: key may be an integer or string
value: A value can be of any PHP type

Examples
$arr = array(“foo” => “bar”, 12 => true);
echo $arr["foo"]; this will print bar
echo $arr[12]; this will print 1

if you provide the brackets with no key specified, then the maximum of the existing integer indices +1 is taken as key. see below

$arr = array(5 => 1, 12 => 2); This will create an array with 2 elements
$arr[] = 56;     new key will be maximum key + 1 i.e $arr[13] = 56
$arr["x"] = 42;  This adds a new element to the array with key “x”

array(5 => 43, 32, 56, “b” => 12); This array is the same as following.
array(5 => 43, 6 => 32, 7 => 56, “b” => 12);

Handling arrays from html form inputs to php scripts
Following example will show we can use an array from html form inputs.

HTML form with array
<input type=”checkbox” name=”selected_ids[]” value=”1?>
<input type=”checkbox” name=”selected_ids[]” value=”2?>
<input type=”checkbox” name=”selected_ids[]” value=”3?>
<input type=”checkbox” name=”selected_ids[]” value=”11?>
<input type=”checkbox” name=”selected_ids[]” value=”12?>
<input type=”checkbox” name=”selected_ids[]” value=”13?>

When we submit above form, it will generate $_POST['selected_ids'][] array to the form handling php script. This array holds all selected checkbox values from above html form. foreach() construct can be used to extract values from the array. Following code example will show how we can extract those values from the returning array.

foreach ($_POST['selected_ids'] as $key => $value) {
    echo “Key: $key; Value: $value<br>”;
}
for example if 1,2 and 12 is selected from the above html form then above code will print
Key: 0 Value: 1
Key: 1 Value: 2
Key: 2 Value: 12