Ten Things You Might Want to Do Using PHP Functions
One of the strongest aspects of PHP is its many built-in
functions. In this article, I list the PHP functions that I use most often. The
PHP language has many hundreds of functions. For a complete list of PHP
functions, see the PHP documentation at www.php.net/manual/en/funcref.php.
Communicate with MySQL
PHP has many functions designed specifically for interacting
with MySQL. Some of them include:
mysqli_connect();
mysqli_fetch_assoc()
mysqli_num_rows();
mysqli_query()
The following functions could be useful, but I either don’t
discuss them or discuss them only
briefly:
✓ mysqli_insert_id($cxn): For use with an AUTO-INCREMENT
MySQL column. This function gets the
last number inserted into the column.
✓ mysqli_select_db($cxn,$database): Selects a database. The
currently selected database is changed to the specified database. All
succeeding queries are executed on the selected database.
✓ mysqli_fetch_row($result): Gets one row from the
temporary results location. The row is
put into an array with numbers as keys.
✓ mysqli_affected_rows($result): Returns the number of rows
that were affected by a query — for
instance, the number of rows deleted or updated.
✓ mysqli_num_fields($result): Returns the number of fields
in a result.
✓ mysqli_field_name($result, N): Returns the name of the
row indicated by N. For instance, mysqli_field_name($result,1)returns the name
of the second column in the result. The first column is (zero).
Send E-Mail
PHP provides a function that sends e-mail from your PHP
program. The format is mail(address,subject,message,headers);
These are the values that you need to fill in:
✓ address: The e-mail address that will receive the message.
✓ subject: A string that goes on the subject line of the
e-mail message.
✓ message: The content that goes inside the e-mail message.
✓ headers: A string that sets values for headers. For
instance, you might have a headers string as follows:
“From: member-desk@petstore.com\r\nbcc: mom@hercompany.com”
The header would set the From header to the given e-mail
address, plus send a blind copy of the
e-mail message to mom.
The following is an example of PHP statements that you can
use in your script to set up and send an e-mail message:
$to = “me@test1.com”;
$subj = “Test”;
$mess = “This is a test of
the mail function”;
$headers =
bcc:techsupport@mycompany.com\r\n
$mailsend =
mail($to,$subj,$mess,$headers);
Sometimes you might have a problem with your e-mail. PHP has
a configuration setting that must be
correct before the mail function can connect to your system e-mail software.
Your Web host has the correct settings. On other computers, the default is
usually correct, but if your e-mail doesn’t seem to be getting to its
destination, check the PHP configuration mail setting by looking for the
following in the output of phpinfo():
Sendmail_path (on Unix/Linux)
SMTP (on Windows)
You can change the setting by editing the php.ini file. If
you’re using Windows, look for the following lines:
[mail function]
; For Win32 only.
SMTP = localhost
; For Win32 only.
sendmail_from =
me@localhost.com
The first setting is where you put the name of your outgoing
mail server. However you send e-mail — using a LAN at work, a cable modem at
home, an ISP via a modem — you send your mail with an SMTP server, which has an
address that you need to know.If you send directly from your computer, you
should be able to find the name of the outgoing mail server in your e-mail
software. For instance, in Microsoft Outlook Express, choose Tools➪Accounts➪Properties
and then click the Servers tab. If you can’t find the name of your outgoing
mail server, ask your e-mail administrator for the name. If you use an ISP, you
can ask the ISP. The name is likely to be in a format similar to the following:
mail.ispname.net
The second setting is the return address sent with all your
e-mail. Change the setting to the e-mail address that you want to use for your
return address, as follows:
sendmail_from = me@myhome.com
If you’re using Unix or Linux, looking for these lines in
your php.inifile:
; For Unix only.
;sendmail_path =
This default is usually correct. If it doesn’t work, talk to
your system administrator about the correct path to your outgoing mail server.Don’t
forget to remove the semicolon at the beginning of the lines. The semicolon
makes the line into a comment, so the setting isn’t active until you remove the
semicolon.
Use PHP Sessions
The functions to open or close a session follow. Two of them
are:
session_start();
session_destroy()
Stop Your Program
Sometimes you just want your program to stop, cease, and
desist. Two functions do this: exit()and die(). Actually, these are two names
for the same function, but sometimes it’s just more fun to say “die.” Both
print a message when they stop if you provide one. The format is
exit(“message string”);
When exit executes, message string is output.
Handle Arrays
Arrays are useful in PHP, particularly for getting the
results from database
functions and for form variables. Some of useful array
functions are:
array(); extract(); sort();
asort();
rsort(); arsort(); ksort();
krsort();
Here are some other useful functions:
✓ array_reverse($varname): Returns an array with the values
in reverse order.
✓ array_unique($varname): Removes duplicate values from an
array.
✓ in_array(“string”,$varname): Looks through an array
$varname for a string “string”.
✓ range(value1,value2): Creates an array containing all the
values between value1 and value2. For instance, range(‘a’,’z’)creates an array
containing all the letters between aand z.
✓ explode(“sep”,”string”): Creates an array of strings in
which each item is a substring of string, separated by sep. For example,
explode(“ “,$string)creates an array in which each word in $string is a
separate value. This is similar to split in Perl.
✓ implode(“glue”,$array): Creates a string containing all
the values in $array with glue between them. For instance, implode(“,
“,$array)creates a string: value1, value2, value3, and so on. This is similar
to the join function in Perl.
Many more useful array functions are available. PHP can do
almost anything with an array.
Check for Variables
Sometimes you just need to know whether a variable exists.
You can use the following functions to test whether a variable is currently
set:
isset($varname); // true if
variable is set
!isset($varname); // true if
variable is not set
empty($varname); // true if
value is 0 or is not set
Format Values
Sometimes you need to format the values in variables. In
this section, I describe additional capabilities of sprintf().The function
sprintf()allows you to format any string or number, including variable values.
The general format is
$newvar =
sprintf(“format”,$varname1,$varname2,...);
where format gives instructions for the format and $varname
contains the value(s) to be formatted. Format can contain both literals and
instructions for formatting the values in $varname. In addition, a format
containing only literals is valid, such as the following statement:
$newvar = sprintf(“I have a
pet”);
This statement outputs the literal string. However, you can also add
variables, using the following statements:
$ndogs = 5;
$ncats = 2;
$newvar = sprintf(“I have %s
dogs and %s cats”,$ndogs,$ncats);
The %sis a formatting instruction that tells sprint to insert the value
in the variable as a string. Thus, the output is I have 5 dogs and 2 cats.
The %character signals sprint that a formatting instruction starts here.
The formatting instruction has the following format:
%pad-width.dectype
These are the components of the formatting instructions:
✓
%: Signals the start of the formatting instruction.
✓
pad: A padding character used to fill out the number when necessary. If you
don’t specify a character, a space is used. padcan be a space, a 0, or any
character preceded by a single quote (’). It’s common to pad numbers with 0—
for example, 01or 0001.
✓
-: A symbol meaning to left-justify the characters. If this isn’t included, the
characters are right-justified.
✓
width: The number of characters to use for the value. If the value doesn’t fill
the width, the padding character is used to pad the value. For instance, if
width is 5, pad is 0(zero), and the value is 1, the output is 00001.
✓
.dec: The number of decimal places to use for a number.
✓
type: The type of value. Use sfor most values. Use for numbers that you want to
format with decimal places.
Some possible sprint statements are sprintf(“I have $%03.2f. Does %s have
any?”,$money,$name);
sprintf(“%’.-20s%3.2f”,$product,$price);
The output of these statements is
I have $030.00. Does Tom have
any?
Kitten.............. 30.00
Compare Strings to Patterns
In earlier chapters in this book, I use regular expressions
as patterns to match strings. (I explain regular expressions in Chapter 6.) The
following functions use regular expressions to find and sometimes replace
patterns in strings:
✓ preg_match(“pattern”,$varname): Checks whether the
pattern is found in $varname.
✓ preg_replace(“pattern”,”string”,$varname): Searches for
pattern in $varname and replaces it with string.
Find Out about Strings
Sometimes you need to know things about a string, such as
its length or whether the first character is an uppercase O.PHP offers many
functions for checking out your strings:
✓ strlen($varname): Returns the length of the string.
✓ strpos(“string”,”substring”): Returns the position in
string where substring begins. For instance, strpos(“hello”,”el”) returns 1.
Remember that the first position for PHP is 0. strrpos() finds the last
position in stringwhere substringbegins.
✓ substr(“string”,n1,n2): Returns the substring from string
that begins at n1and is n2characters long. For instance,
substr(“hello”,2,2)returns ll.
✓ strtr($varname,”str1”,”str2”): Searches through the
string $varnamefor str1and replaces it with str2every place that it’s found.
✓ strrev($varname): Returns the string with the characters
reversed.
Many more string functions exist. See the documentation at www.php.net.
Change the Case of Strings
Changing uppercase letters to lowercase and vice versa is
not so easy. Bless PHP for providing functions to do this for you:
✓ strtolower($varname): Changes any uppercase letters in
the string to lowercase letters
✓ strtoupper($varname): Changes any lowercase letters in
the string to uppercase letters
✓ ucfirst($varname): Changes the first letter in the string
to uppercase
✓ ucwords($varname): Changes the first letter of each word
in the string to uppercase
No comments:
Post a Comment