Friday, October 10, 2008
PHP short-hand IF statement
Lightweight IF Syntax
Any programmer will agree that the IF/ELSE statements are a fundamental part of any language. The basic syntax is pretty universal between languages but many dont realise that there is a shorthand version that allows switching to be done inline.
The syntax is simply statement ? if-true : if-false
$variable = (statement) ? "return if true" : "return if false";
Compared to
if(statement) {
$variable = "return this if true";
}
else {
$variable = "return this if false";
}
As you can see, you save a lot of coding by using this lightweight syntax for simple IF/ELSE statements. It can also be used inline within strings which is where I find the most benefit of using it. Here is an example that has a real world use for a simple output that changes between "there is 1 item", "there are X items", and "there are no items" using multiple statements.
$text = "There ".
($total==1 ? "is 1 item" :
"are ".($total == 0 ? "no items" : "$total items")
);
Compared to:
if($total==0) {
$text = "There are no items";
}
else if($total==1) {
$text = "There is 1 item";
}
else if($total > 0) {
$text = "There are $total items";
}
Posted by
guru
at
3:43 PM
280
comments
Labels: PHP
Thursday, March 13, 2008
Downloading Files From MySQL Database
Downloading Files From MySQL Database
When we upload a file to database we also save the file type and length. These were not needed for uploading the files but is needed for downloading the files from the database.
The download page list the file names stored in database. The names are printed as a url. The url would look like download.php?id=3. To see a working example click here. I saved several images in my database, you can try downloading them.
more info: http://www.php-mysql-tutorial.com/php-mysql-upload.phpUploading Files To MySQL Database
More info : http://www.php-mysql-tutorial.com/php-mysql-upload.php
Using PHP to upload files into MySQL database sometimes needed by some web application. For instance for storing pdf documents or images to make som kind of online briefcase (like Yahoo briefcase).
For the first step, let's make the table for the upload files. The table will consist of.
- id : Unique id for each file
- name : File name
- type : File content type
- size : File size
- content : The file itself
For column content we'll use BLOB data type. BLOB is a binary large object that can hold a variable amount of data. MySQL have four BLOB data types, they are :
- TINYBLOB
- BLOB
- MEDIUMBLOB
- LONGBLOB
Since BLOB is limited to store up to 64 kilobytes of data we will use MEDIUMBLOB so we can store larger files ( up to 16 megabytes ).
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
content MEDIUMBLOB NOT NULL,
PRIMARY KEY(id)
);
More info : http://www.php-mysql-tutorial.com/php-mysql-upload.php
Posted by
guru
at
12:16 AM
0
comments
Labels: how to file upload, how to uploading or save a image to database, MySQL, PHP, upload a file, upload image, upload image to database
Thursday, March 6, 2008
In and out of PHP before they even knew what hit 'em
When embedding PHP within HTML, you can close your PHP tag whenever you want to output HTML. This enables speedier processing of your PHP. For instance:
Hey Turkeys! Behind ya!
I just drop by with present for warming of house, instead find you grappling with
Hopefully that last one didn't confuse you as much it confused me, the example is a bit extreme. However look over it a few times and you will understand exactly what is going on.
Posted by
guru
at
11:52 PM
0
comments
Labels: PHP
They true did false, they were the trueiest bunch of falses that ever trued
If all you are trying to test for is a boolean (true/false) of a variable or function then instead of laying down a bunch of code like this:
if ($blackbeard == true) echo 'Arr, this chair be high, says I.';
elseif ($seacaptain == false) echo 'Yar, I'm not attractive.';You can omit == and != with:
if ($blackbeard) echo 'Arr, this chair be high, says I.';
elseif (!$seacaptain) echo 'Yar, I'm not attractive.';This same format can apply to functions and multiple conditions. For example:
if ($benedict_arnold != true && strpos($photo,'map') == true)
echo 'You idiot, you can't read!';
if (high_chair($blackbeard) == false)
echo 'Aye, 'tis true. My debauchery was my way of compensating.';The following is the same exact statement (except with less code):
if (!$benedict_arnold && strpos($photo,'map'))
echo 'You idiot, you can't read!';
if (!high_chair($blackbeard))
echo 'Aye, 'tis true. My debauchery was my way of compensating.';
Posted by
guru
at
11:51 PM
0
comments
Labels: PHP
One control structure to rule them all, One constant to find them, One set of conditional brackets to bring them all and in the darkness bind them
Not anymore! If you have a single expression following a control structure, you do not need to waste your time with brackets { }.
if ($gollum == 'halfling') {
$height --;
}Is the same as:
if ($gollum == 'halfling') $height --;This can be applied to any control structure statement. For example:
if ($gollum == 'halfling') $height --;
else $height ++;
if ($frodo != 'dead')
echo 'Gosh darnit, roll again Sauron';
foreach ($kill as $count)
echo 'Legolas strikes again, that makes' . $count . 'for me!';The fewer brackets you have cluttering up your code, the easier it may be to read.
Posted by
guru
at
11:50 PM
0
comments
Labels: PHP
Single Quotes versus Double Quotes
Any time you put something in "double" quotes, you are asking PHP to check that content for a variable. So even though the following lines do not contain variables within the double quotes, PHP will still waste precious computing time scanning them anyway.
$mytext = "Dental Plan";
if ($mytext == "Dental Plan") {
echo "Lisa needs braces"; }Those same three lines of code could be executed much faster if 'single' quotes were used in place of "double" quotes.
$mytext = 'Dental Plan';
if ($mytext == 'Dental Plan') {
echo 'Lisa needs braces'; }Now that may not seem like much, but having PHP check for variables where it doesn't need to over the course of a larger script, can certainly impede run-time. Just to clarify my point, PHP will not read a variable if it is within 'single' quotes.
echo '$mytext, Lisa needs braces.';
// Will output: $mytext, Lisa needs braces.
echo "$mytext, Lisa needs braces.";
// Will output: Dental Plan, Lisa needs braces.What is the the super-secret of keeping those scripts speeding along the rusty pipes of your server? Avoid double quotes at all costs. Even if you are working with a variable and think you need double quotes, it is more efficient for PHP to execute this:
echo $mytext . 'Lisa needs braces.';As opposed to this bit of molasses-like code:
echo "$mytext Lisa needs braces.";
Posted by
guru
at
11:49 PM
0
comments
Labels: PHP
It All Adds Up
$variable = $variable + 1;Is the same as:
$variable ++;This method also works for subtraction:
$variable --;You can also apply a similar method for concocting strings. So instead of:
$mytext = 'Done and Done.';
$mytext = "$mytext And I mean Done!"; // $mytext = 'Done and Done And I mean Done!';Use this shorthand method of adding another string of text onto the end of the first string:
$mytext = 'Done and Done.';
$mytext .= ' And I mean Done!'; // $mytext = 'Done and Done And I mean Done!';
Posted by
guru
at
11:45 PM
0
comments
Labels: PHP
Monday, February 11, 2008
Method GET y POST
In the previous page we have indicated that data in a form is sent through the method indicated in the attribute METHOD of the tag FORM, the two possible methods are GET and POST.
The difference between these two methods is in the way of sending data to the page, while the GET method sends data using URL, the POST method sends them through the standard entrance STDIO
more details: http://www.webestilo.com/en/php/php09b.phtml
Posted by
guru
at
5:00 PM
0
comments
Labels: PHP
Wednesday, February 6, 2008
Beautify Javascript - Javascript Online Beautifier
Javascript Online Beautifierhttp://elfz.laacz.lv/beautify/ Online beautifier for javascript (js beautify, pretty-print)source:http://elfz.laacz.lv/beautify/beautify.php
Posted by
guru
at
7:57 PM
0
comments
Labels: PHP
Sunday, November 4, 2007
PHP and Classes
The simplest way to learn about classes in PHP:
Well let's start by defining what is a class:
A generalized category in object-oriented programming that describes a group of more specific items called objects.
A class provides a template for defining the behavior of a particular type of object. Objects of a given class are identicalto each other in form and behavior.
A class is a descriptive tool used in a program to define a set of attributes or servicesthat characterize any member (object) of the class.
Now let's define a class in PHP and use some of the objects function. Let's assume that our object is an associative array having its indexes named after a product table. having fields: ID, NAME, DESCRIPTION.
So we should start by creating the table called products:
CREATE TABLE `products` (
`id` TINYINT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 20 ) NOT NULL ,
`description` VARCHAR( 20 ) NOT NULL ,
PRIMARY KEY ( `id` )
)
CODE
//let's define our class, and a set of functions inside this class.
class productdb
{
//this function create an empty instance of an associative array
function EmptyObject()
{
$product=array('ID'=>NULL,'NAME'=>NULL,'DESC'=>NULL);
return $product;
}
//this function takes a primary key as an input and returns the complete set of values corresponding to that primary key
function GetRow($id)
{
$result=mysql_query("SELECT id,name,description from products WHERE id='$id'");
while($row=mysql_fetch_assoc($result))
{
$product['ID']=$row['id'];
$product['NAME']=$row['name'];
$product['DESC']=$row['description'];
return $product;
}
}
}
//Now let's learn how to use those classes....
//first let's create an instance of that class....
$myobj= new productdb;
//now let's create an empty object, that has the specification of the object described above...
$myproduct=$myobj->EmptyObject();
//Suppose our product table is filled with values....
$myproduct=$myobj->GetRow($id)
echo $myproduct['ID'] . $myproduct['NAME'] . $myproduct['DESC'];
?>
And basicaly that is the simplest way to understanding classes and using them.
Posted by
guru
at
8:15 PM
0
comments
Labels: PHP
Validity of username and passwords
We have assumed that you have created a table called "users", and that table contain as much fields as you want, you can insert recordsinto that table using a form in html. But be sure to include two fields:
name= it is the username of the user
password= it is the password of each user
Simply create a form, using html, and set the action of that forum to a php file where you will include this small piece of code:
- //First lets get the username and password from the user
- $username=$_POST["username"];
- $password=$_POST["password"];
- //Second let's check if that username and password are correct and found in our database
- $sql1=mysql_query("SELECT name, password FROM users WHERE name='$username' AND password='$password'")
- if (mysql_num_rows($sql1)==0 mysql_num_rows($sql1)>1)
- {
- echo "Sorry, the username and password you submitted are not present in our database";
- }
- //if there are found in our database, and there is only one occurence of that username and password
- //thus making them valid, so inside, you can include the webpage you want to open
- if(mysql_num_rows($sql1)==1){include("the webpage");
- //open up the secure page
- //instead of "the webpage" type in the path your secure website is located in
- }
- ?>
Posted by
guru
at
4:51 PM
2
comments
Labels: PHP
File-upload-with-PHP
Here are the steps :
1. Set up an html page with a form.
2. upload the file to the server.
3. Move the file to it's destination.
4. Let the user know if the upload was successful or not.
Posted by
guru
at
4:03 PM
0
comments
Labels: PHP










