 | 10 basic blocks of PHP-codeCategory: PHP
|
| There are some basic and useful lines of code that you often end up using when programming in PHP. I'll put 10 common ones I often use here, partly for myself but foremost for you readers. Please feel free to complement if you have any suggestions or improvements. Redirect user to another page:| header("Location: http://www.thedomain.com/aPage.htm"); |
Include the contents of another page:include('include/aPage.php'); /* Warning message on failure */ // OR require('include/aPage.php'); /* Fatal error message on error and halt processing. */ |
Create a connection and set current active database:/* Set values of $mysql_host, $mysql_database, $mysql_username, $mysql_password */
$link = mysql_connect($mysql_host, $mysql_username, $mysql_password) or die("Could not connect to database: " . mysql_error());
mysql_select_db($mysql_database, $link) or die("Could not set database"); |
Create and execute simple select-query to SQL-database:$select_query = "SELECT * FROM someTable";
/* Perform Query */ $select_result = mysql_query($select_query);
/* Check result */ if (!$select_result) { $message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $select_query; die($message); } |
Create random string:function createRandomString($len) { $source_arr = array("0","1","2","3","4","5","6","7","8","9");
for ($i=0; $i<$len; $i++) { $random_key = array_rand($source_arr); $random_str .= $source_arr[$random_key]; } return $random_str; } |
Create time and date variables on different :$dt = date("Y-m-d"); // 2008-07-18 $dt = date("m/d/Y"); // 07/18/2007 $dt = date("F j, Y, g:i a"); // July 18, 2008, 1:22 am |
Set pointer to the first position of a mysql resultset:| mysql_data_seek($result, 0); |
Mail function:/* Send mail */ function sendMail($to, $subject, $message) { $headers = "From: \"From address\" <fromAddress@mail.com>" . "\r\n" . "Reply-To: \"Reply address\" <replyAddress@mail.com>" . "\r\n" . "X-Mailer: PHP/" . phpversion(); mail($to, $subject, $message, $headers); } |
Replace all occurrences of a search string with a replacement string:/* $string_before => 'abcdef abcdef' */ $resultString = str_replace("a", "", $string_before); /* $resultString => bcdef bcdef */ |
Url-encode a string (for use in a query part of an url for example):| $url = "http://www.domain.com/test.php?q=" + urlencode($query_part_of_url); |
|  |