13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

114 Chapter 4 String Manipulation <strong>and</strong> Regular Expressions<br />

Table 4.2 String Case Functions <strong>and</strong> Their Effects<br />

Function Description Use Value<br />

ucwords() Capitalizes first ucwords($subject) Feedback From<br />

character of each<br />

<strong>Web</strong> Site<br />

word in the string<br />

that begins with<br />

an alphabetic<br />

character<br />

Formatting Strings for Storage: addslashes() <strong>and</strong><br />

stripslashes()<br />

In addition to using string functions to reformat a string visually, you can use some of<br />

these functions to reformat strings for storage in a database. Although we don’t cover<br />

actually writing to the database until Part II,“Using <strong>MySQL</strong>,” we cover formatting<br />

strings for database storage now.<br />

Certain characters are perfectly valid as part of a string but can cause problems, particularly<br />

when you are inserting data into a database because the database could interpret<br />

these characters as control characters.The problematic ones are quotation marks (single<br />

<strong>and</strong> double), backslashes (\), <strong>and</strong> the NULL character.<br />

You need to find a way of marking or escaping these characters so that databases such<br />

as <strong>MySQL</strong> can underst<strong>and</strong> that you meant a literal special character rather than a control<br />

sequence.To escape these characters, add a backslash in front of them. For example, “<br />

(double quotation mark) becomes \” (backslash double quotation mark), <strong>and</strong> \ (backslash)<br />

becomes \\ (backslash backslash). (This rule applies universally to special characters,<br />

so if you have \\ in your string, you need to replace it with \\\\.)<br />

<strong>PHP</strong> provides two functions specifically designed for escaping characters. Before you<br />

write any strings into a database, you should reformat them with addslashes(), as<br />

follows if your <strong>PHP</strong> configuration does not already have this functionality turned on by<br />

default:<br />

$feedback = addslashes(trim($_POST['feedback']));<br />

Like many of the other string functions, addslashes() takes a string as a parameter <strong>and</strong><br />

returns the reformatted string.<br />

Figure 4.3 shows the actual effects of using these functions on the string.<br />

You may try these functions on your server <strong>and</strong> get a result that looks more like<br />

Figure 4.4.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!