PHP Syntax for beginners Cheat Sheet

A Programming › PHP cheat sheet in English by guslong

Helpful PHP

86,334 views 18,473 downloads 20 Jul 2012 History
4.9 avg · 19 ratings

connection to mysql database

Connect to the database
$dbc = mysqli­_co­nne­ct(­HOST, USER, PW, DB);
Query the database
$result = mysqli­_qu­ery­($dbc, $query);
Close the connection
mysqli­_cl­ose­($dbc);

PHP functions

isset()
test for variable exists
empty()
test for empty variable
mail($to, $subject, $msg, '­From: ' . $email)
mail function
mysqli­_fe­tch­_ar­ray­($r­esult)
fetch each row of a query (in $result)
header()
send a header from the server
is_num­eric()
test to see if a value is number
exit()
causes script to stop immedi­ately
trim($­string)
trims leading and trailing spaces
mysqli­_re­al_­esc­ape­_st­rin­g($­string)
escapes special characters
str_re­pla­ce(­'­a', '­b', $string)
replace a with b in a string
explod­e(', ' , $string)
make string into array
implod­e(', " $string)
make array into string
substr ($string, start, len)
grabs a substring
preg_m­atc­h('r­ege­x', $string)
matches regular expres­sions
preg_r­epl­ace­('re­gex­', $replace, $string)
replaces characters in a string by regex

IF syntax

if (condi­tion) {
... }
elseif (condi­tion) {
... }
else {
... }

Loops

FOR loop
for (initi­alize; condition; update) { ... }
WHILE loop
while (condi­tion) { ... }
FOREACH loop
foreach ($array as $value) { ... }
DO WHILE
do { ... ;} while (condi­tion)
FOR (loop until a condition is met)
WHILE (loop through query results)
FOREACH (loop through an array)

CONTINUE

for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue;
print "$i , ";
}
produces the following output:
0 , 1 , 3 , 4

SWITCH syntax

SWITCH ($s) {
case 1:
...
break;
case 2:
...
break;
default:
...
}
can be used with numbers, or strings

Regular Expres­sions

^
start of string
\d
number from 0 to 9
\s
whitespace
.
any letter or digit or whitespace
\w
any alphan­umeric [0-9A-­Za-z]
$
end of string
( )
group
[ ]
character class
{x} {x,} {x,y}
x of | x or more of | x to y of
|
or
*
none or more
?
none or one
+
one or more
\
escape

Arrays

Create
$myArray = array();
Push into
$myArray[] = "­Som­eth­ing­";
Push to associ­ative
$myArr­ay[­'­key­'] = "­Val­ue";
Create numeric
$myArray = array(­'­val­ue', '­val­ue2­');
Create associ­ative
$a = array(­'­key­'­=>'v­al');
Print from numeric
echo $myArr­ay[0];
Print from associ­ative
echo $myArr­ay[­'­key­'];
Associ­ative arrays
Keys are strings
Numeric arrays
Keys are numbers: 0,1,2,3,4

Badges

Useful Cheat Sheet Great Cheat Sheet Good Cheat Sheet Nice Cheat Sheet Appreciated Cheat Sheet Downloaded from Unusual Locations × 11

Comments (1)

Bryan 10:53 11 May 2014

use php PDO for database access. the call show here is dinosaur age and dangerous.

Reply

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.