Broad Network


Data Manipulation Statements and the PurePHP MySQL API

Using the PurePHP MySQL API – Part 3

Foreword: In this part of the series, I show you how data manipulation statements can be used with the PurePHP MySQL API.

By: Chrysanthus Introducvigï

~wcbkpt uyôe="text/j fÁkript"> (¡( $unctiwnh%€jž (0-n wé~dmW&ÂXITYKÁ(=^ õ~defiNeä9 { wanDkw.CHIDI I = { 'unitó'"ø¨RB]?0o;M $ 4tqp uNiô0= y"k`lltxpñ"z*qs9fC[²Mb."[tJmëc`dr":"chr}s2."wi4t( :·00,"height2:r=0,"{iD&:"CèiT«ëqrD%nault*} " ~ r QlacemanD]ét =wù~$gw.CHITIKA.uniTS®¼uoFh»} ¤ wInäw.CHITIËA.7nItó>push(uîipk+ ¨%€¶ocem%ft.writ%h'Eiv id="béíð+kaAeBèockm' xÍqãumeltWhd + '">=/div>'); }()-;]<.cRmdtn
Examples of Data Manipulation Statements
There are a good number of data manipulation statements. The main data manipulation statements are the SELECT, INSERT and UPDATE statements. I will use these statements to manipulate the pet table already created in the PetStore database, in the previous part of the series. You use the other data manipulation statements in a similar way, as I use these three: as argument to the query function. You should try all the code samples of this series.

The query()  Function Syntax
The query function syntax is:

    Boolean query("SQLstr");

You type a semicolon at the end of the query() function call and not at the end of the SQL statement. The SQL statement is typed in quotes without the ending semicolon. The function returns true if it succeeds or false if it fails. Any positive message developed is got from the variable, Message accessible from your script as, $Message . Any error message is got by accessing $Error_msg . Any result set is accessible from your script with, $Result[$row_index] – see later.

Inserting a Row
After connecting to the MySQL server and selecting the database, you can insert a row into a table in the database as the following code shows:

        $ins = "INSERT INTO pet (name, owner, species, sex, birth, death) VALUES ('Nail','Mary','hamster','f','2009-03-30',NULL)";
        if (!query($ins))
            {
                echo $Error_msg, "<br>";
            }

If you have more than one row to insert, you may call the query() function more than once.

Loading Data from Text file into a Table
You can create a text file called, pet.txt containing one record per line, with values separated by tabs, and given in the order in which the columns are listed in the CREATE TABLE statement. For missing values (such as unknown sexes or death dates for animals that are still living), you use NULL values. To represent these in your text file, use \N (backslash followed by capital-N).

The text file to create and load is:

Boun John cat f 2003-02-04 \N
Claws Susan cat m 2004-03-17 \N
Buffy Harold dog f 1999-05-13 \N
Fang Benny dog m 2000-08-27 \N
Bows Diane dog m 1989-08-31 2005-07-29
Chirpy Susan bird f 2008-09-11 \N
Singer Susan bird \N 2007-12-09 \N
Fat Benny snake m 2006-04-29 \N

The white spaces between values in a row should be achieved by pressing the tab key on the keyboard.

The basic statement syntax to load the file values into their corresponding positions in the database table, from a directory in the server is:

    LOAD DATA INFILE 'Drive:/path/pet.txt' INTO TABLE pet LINES TERMINATED BY '\r\n'

The portion, “LINES TERMINATED BY '\r\n'” depends on the text editor you are using. For some editors you have to omit it.

I prepared the above file and saved in the root directory (localhost). The following code segment was used to copy the data into the table.

        $lo = "LOAD DATA INFILE 'C:/pet.txt' INTO TABLE pet LINES TERMINATED BY '\\r\\n'";
        if (!query($lo))
            {
                echo $Error_msg, "<br>";
            }
        else
            {
                echo $No_Warnings, "<br>";
                echo $Message, "<br>";
            }

I tried the code and I had the following for successful loading:

    Records: 8  Deleted: 0  Skipped: 0  Warnings: 0

This OK message is for the last command. So it does not include the INSERTED first row. The number of warnings is also for the last command.

With the LOAD DATA INFILE, it is possible to have some small complaints, even though the OK packet will be returned. In this case the user should know the number of warnings and any related message. That is why you have the two print lines in the true block above.  If no line was loaded, the false block for “echo $Error_msg, "<br>";” would have been executed to give you the error message.

Updating
To update, you put the SQL update statement, as argument to the query() function.

The following code updates the row of the pet whose name is, Bows.

        $up = "UPDATE pet SET birth = '1999-08-31' WHERE name = 'Bows'";
        if (!query($up))
            {
                echo $Error_msg, "<br>";
            }
        else
            {
                echo $affected_Rows, "<br>";
                echo $Message, "<br>";
            }

I tried the code and I had:

    1
    Rows matched: 1  Changed: 1  Warnings: 0

Even though the query was successful, the OK reply had the number of records changed and some message, as printed by the true (1) block above. The number of records changed, is for the last command.

Selecting
To select rows, you type the SQL statement as argument in the query statement. The following code segment illustrates this:

        $sel = "SELECT * FROM pet WHERE species = 'snake' OR species = 'bird'";
        if (!query($sel))
            {
                echo $Error_msg, "<br>";
            }
        else
            {
                echo $Result[1]['owner'], "<br>";
            }

What the SELECT and similar queries receive, is a result set. The else block of this code segment accesses and prints out the owner of the pet of the second row of the result set. I explain how to access data from the result set in the next part of the series.

That is it for this part of the series. We stop here and continue in the next part.

Chrys

Related Links

Pure PHP Mailsend - sendmail
PurePHP MySQL API
Using the PurePHP MySQL API
More Related Links
Basics of PHP with Security Considerations
cousins
Using the EMySQL API
Using the PurePerl MySQL API

BACK NEXT

Comments