Writing to MSQL Databases PartII

advertisement

Writing to MSQL Databases PartII

Introduction

Note: This Tutorial extends upon the knowledge gained through " Accessing a mySQL database " and Part 1 of this series of tutorials. Needless to say, read those first!

Hi there, welcome again to Part 2 of this tutorial. Today will be all about the UPDATE query (and finally about the DELETE query). We'll learn what the statement has to look like and we'll extend the Administration page we created in Part I of the tutorial. But first, let's have a look at the table we have from Part I.

+-----+----------------+-----------------------------+

| aid | name | email |

+-----+----------------+-----------------------------+

| 1 | Raphael Pirker | raphaelp@nr1webresource.com |

| 2 | Simon Remppis | simon@nr1webresource.com |

| 3 | Nadine Pirker | nadine@nr1webresource.com |

+-----+----------------+-----------------------------+

Our goal will be to first change raphaelp@nr1webresource.com into nr1webresource@raphaelp.com and then we'll learn a few basics of the Administration page before we conclude the tutorial and end this series of

Tutorials.

Ok, starting off, I'd like to introduce you to the syntax of the UPDATE query:

UPDATE table SET column1=value1, [column2=value2, ...] [WHERE column_x=value_x]

As you can see, the WHERE statement is not mandatory, but if you miss it, the whole database will be updated and usually you'll want to pick only one record out of the database and modify it.

That much about the introduction, now for the real part!

Modifying data statically

Remember the task I gave at the beginning? (to change the value of my e-mail address) Let's have a crack at it, ok?

<?php

$db = mysql_connect("localhost", "username", "password"); mysql_select_db("database",$dB);

$sql="UPDATE authors SET email='nr1webresource@raphaelp.com' WHERE aid=1";

$result=mysql_query($SQL,$dB);

?>

(remember to change the first two lines according to your system!!)

Placing this code into a PHP3 file and executing it would change my e-mail address everytime the page is loaded. Needless to say, this is a useless script, but it serves it's purpose: to guide you to the real thing step by step. Let's break down this code:

$dB = mysql_connect("localhost", "username", "password"); mysql_select_db("database",$dB);

Well well, where have we seen that already? It wasn't the last 2 lessons, was it? :)

$SQL="UPDATE authors SET email='nr1webresource@raphaelp.com' WHERE aid=1";

Ok, this is the "real" part. It's our SQL-query which tells our function below what to do. As I already mentioned, this query is useless if we'd like to execute it more than once, we need to set some variables in there to use it later on.

$result=mysql_query($SQL,$dB);

Also a little code-snippet from our previous lessons: This code just executes the SQL-query against our mySQL database.

Now that we've slightly touched how to modify data statically, let's define how to modify data dynamically!

Modifying data dynamically

One of the great advantages of PHP is that it can automatically integrate variables passed along from the

URL. For example typing index.php3?stupid=1

into the location bar will automatically create the variable stupid

and assign the value

1

to it (provided index.php3 actually exists. duh!)

Keeping that in mind, we'll create our first code which will UPDATE and INSERT code, depending on the variables we pass along in the URL. Let's first create the layout

We have 3 different types of submissions:

1. Inserting data

2. Reading data for modification

3. Updating data for modification

Let's create a variable called "t" (our abbreviation of "type") and assign a number to each of these types of submissions. This will allow us to easily track what the user wants to do.

Now that we have the idea, let's create the blueprint of the code:

<?php if ($t==1) {

// new data wants to be inserted!

} elseif ($t==2) {

// Let's read the specified record from the database, shall we?

} else {

// The user wants me to update the record, so I will follow his command...

}

?>

We still have the code for the first type of submission from our previous lesson, but we'll need to create a new one for next two types. The first type has to read data from our table, so let's create that first:

<?php

[...]

} elseif ($t==2) {

$SQL="SELECT * FROM authors WHERE aid=$aid";

$result=mysql_query($SQL,$dB);

$row = mysql_fetch_array($result);

$name = $row["name"];

$email = $row["email"];

} [...]

?>

I hope there's not much to be explained here! Only one thing that I would like to discuss: We're picking out only the record

WHERE aid=$aid

but what's the value of

$aid

? Well, to make it short: We don't have a value for that yet, but we'll assign the value to

$aid

using the method I told you about at the beginning of this chapter: index.php3?t=2&aid=1

This will make the variable $t hold the value " 2 " and the variable $aid will have the value of " 1 ". Cool, right?

Now that we have the second type covered, let's go for the third type as well:

<?php

[...]

} else {

$SQL="UPDATE authors SET name='$name', email='$email' WHERE aid=$aid";

$result=mysql_query($SQL,$dB);

}

?>

It couldn't be much easier. The variable $aid makes sure that the record we want to update is unique and

$name and

$email take care that the correct data is updated. These two variables will get their values from our old form which we used to write data into the SQL database. Let's have a look at the complete code now:

<?php

$dB = mysql_connect("localhost", "username", "password"); mysql_select_db("database",$dB); if ($t==1) {

$SQL="INSERT INTO authors VALUES('','$name','$email')";

$result=mysql_query($SQL,$dB);

} elseif ($t==2) {

$SQL="SELECT * FROM authors WHERE aid=$aid";

$result=mysql_query($SQL,$dB);

$row = mysql_fetch_array($result);

$name = $row["name"];

$email = $row["email"];

} else {

$SQL="UPDATE authors SET name='$name', email='$email' WHERE aid=$aid";

$result=mysql_query($SQL,$dB);

}

?>

Lookin' good! :)

Before we can test our script, we should first have a look at our form, which we'll need to extend a little in order to be able to update records.

<form name="author_admin" method="post" action="<?php echo

$PHP_SELF;?>">

<p>name: <input type="text" name="name"

value="<?php echo

$name;?>"

><br> e-mail: <input type="text" name="email"

value="<?php echo $email;?>"

>

<input type="submit" value="Insert

/Update

"></p>

<input type="hidden" name="t" value="<?php echo $t_value;?>">

<input type="hidden" name="aid" value="<?php echo $aid;?>">

</form>

I highlighted all the changes I made to the form from our previous lesson. The value="<?php ... ?>" addition makes sure that, if a value is given for the variable, it gets echoed as default value of the formelement, thus displaying the value from the database inside the text-field. The hidden-fields serve for us to determine what type of submission we have and if we're editing, what row we're editing. We still have a problem, though:

$t_value

isn't defined yet. This is because we need to calculate it. But how? Here's the main idea:

 if

$t

equals "

2

" (meaning we're reading the data to be edited), the value of

$t_value

has to be

" 3 ", because by the next submission, we have data which has to be updated

 the default value of

$t

is "

1

", since by default, we'll want the user to insert data

 for reasons you'll understand later on, if the value of $t is " 3 ", the value of $t_value also has to be "

3

"

With this knowledge, creating a "$t_value-generator" is no more than a walk in the park:

<?php

if ($t == 2) {

$t_value = 3;

} elseif ($t == 3) {

$t_value = 3;

} else {

$t=1;

$t_value = 1;

}

?>

This part of code goes right above our lovely Form. Now we're ready to INSERT and MODIFY data. Load the file which you've been working on under the following URL: filename.php3?t=2&aid=1

You should get the form with my name and e-mail written inside it. Make a change and then load the above page again, did something change? If nothing changed, go recheck your source, because there must be

SOMETHING that changed!

Now, once again we have a administrator page which works perfectly, but which can't really be used without a 10-paged handbook (unless you did the coding yourself!) That's why we should make the whole thing a little more user-friendly before we add the delete feature...

Now that we have the blueprint...

In this chapter, we'll add the following to the administrator page:

Headings describing what the administrator just did or will do

A list of all data entered into the database with "edit" buttons next to it

 include "action" links to switch mode

First, describing the headings:

Our headers change depending on value of

$t

, correct? After the code which determines

$t_value

, we'll add the following:

<h1><?php

$t_headers = array('Insert Data','Edit Data','Data Edited'); if ($t == 1 && (isset($name) && isset($email))) { echo "Record Inserted";

$t_headers = "";

} echo $t_headers[$t-1];

?></h1>

Well, understanding this code is a little harder. Basically, we insert all possible "titles" into an array (if you don't know what arrays are, make sure you read about them in some PHP introductory after this tutorial...) and later echo that title according to the value of

$t

we have ( red code). The blue code is there to cover the case when

$t

equals "

1

" and we don't want to insert a new record but rather we've already inserted a new record!

This will describe the headings perfectly, try for yourself!

Next, making a list of all data entered in the database:

We'll use the code from the last chapter of Lesson 2 and modify it a little. Here is what we have so far:

<?php

$SQL="SELECT * FROM authors ORDER BY aid DESC LIMIT 0,30";

$result=mysql_query($SQL,$dB);

$num = mysql_num_rows($result);

$cur = 1; echo '<table width="300" border="1" cellspacing="2" cellpadding="1" class="content">

<tr>

<td nowrap><b>aid</b></td>

<td nowrap><b>name</b></td>

<td nowrap><b>email</b></td>

</tr>';

while ($num >= $cur) {

$row = mysql_fetch_array($result);

$aid = $row["aid"];

$name = $row["name"];

$email = $row["email"]; echo "<tr><td nowrap>$aid</td><td nowrap>$name</td><td nowrap>$email</td></tr>";

$cur++;

} echo "</table>";

?>

Let me remind you about the edit-link: filename.php3?t=2&aid=$aid - having that in mind, let's create another column for the table:

<?php

$SQL="SELECT * FROM authors ORDER BY aid DESC LIMIT 0,30";

$result=mysql_query($SQL,$dB);

$num = mysql_num_rows($result);

$cur = 1; echo '<table width="300" border="1" cellspacing="2" cellpadding="1" class="content">

<tr>

<td nowrap><b>aid</b></td>

<td nowrap><b>name</b></td>

<td nowrap><b>email</b></td>

<td nowrap><b>action</b></td>

</tr>'; while ($num >= $cur) {

$row = mysql_fetch_array($result);

$aid = $row["aid"];

$name = $row["name"];

$email = $row["email"]; echo "<tr><td nowrap>$aid</td><td nowrap>$name</td><td nowrap>$email</td>

<td><a href=\"$PHP_SELF?t=2&aid=$aid\">edit</a></td>

</tr>";

$cur++;

} echo "</table>";

?>

If you place this code at the bottom of our current administrator page, you'll get the list of all the data you've got inside the database. On mine, the table looks somehow like this:

aid name email action

3 Nadine Pirker nadine@nr1webresource.com edit

2 Simon Remppis simon@nr1webresource.com edit

1 Raphael Pirker raphael@nr1webresource.com edit

How neat! :) Now all that's missing is a link for "Insert New Records" when we're in edit mode, then everything is good!

The link to the page which allows us to insert new records again is pretty simple:

<a href="<?php echo $PHP_SELF;?>">Insert New Records</a>

Add that someplace smart where it will always be visible on the screen I placed it below the form...

Okay, the administrator page looks pretty good already, what's missing is a DELETE button, I always love those.. *evilgrin* :)

DELETE some records?

Okay, this chapter is a fun one. Deleting stuff has always been something I loved doing. First of all the

DELETE query:

DELETE FROM table WHERE column_x=value_x

Short but fatal :)

In order to delete correctly on our administrator page, we'll have to create a new type (

$t

). Here we go:

<?php

$dB = mysql_connect("localhost", "us15389c", "we_will_win"); mysql_select_db("db15389c",$dB); if ($t==1) {

$SQL="INSERT INTO authors VALUES('','$name','$email')";

$result=mysql_query($SQL,$dB);

} elseif ($t==2) {

$SQL="SELECT * FROM authors WHERE aid=$aid";

$result=mysql_query($SQL,$dB);

$row = mysql_fetch_array($result);

$name = $row["name"];

$email = $row["email"];

}

elseif ($t==4) {

$SQL="DELETE FROM authors WHERE aid=$aid";

$result=mysql_query($SQL,$dB);

}

else {

$SQL="UPDATE authors SET name='$name', email='$email' WHERE aid=$aid";

$result=mysql_query($SQL,$dB);

}

?>

Check out the bold code, it's what I added. I'm sure this makes sense to you by now...

Same goes for the $t_value-generator - we'll need to add another if-then statement there, too:

<?php

if ($t == 2) {

$t_value = 3;

} elseif ($t == 3) {

$t_value = 3;

}

elseif ($t == 4) {

$t_value = 1;

}

else {

$t=1;

$t_value = 1;

}

?>

"Why?" you may ask now... Quite simple: Because of the headers of our administrator page. If the headers weren't there, we could use the last statement. The last statement also redefine

$t

(see the red code) and therefore it's not usable to echo "Record Deleted".

Another thing we have to change is the array. We need to add another value to it:

$t_headers = array('Insert Data','Edit Data','Data Edited',

'Record

Deleted'

);

And last but not least, we'll need to add the "delete" link to the table, right? echo "<tr><td nowrap>$aid</td> <td nowrap>$name</td><td nowrap>$email</td> <td nowrap><a href=\"$PHP_SELF?t=2&aid=$aid\">edit</a> |

<a href=\"$PHP_SELF?

t=4

& aid=$aid \">delete</a>

</td></tr>";

I don't think there is much need for explanation, since the only difference to the "edit" link is the "4" (marked red) instead of the "2". As you can see, planning your programming before you start off creating the actual program can save you a lot of trouble afterwards! Save your file and reload it and try deleting an item... :)

Well, my keyboard is smoking, the screen is flickering and just about to go blank, the stereo system next to me is making scratchy noises out and I'm pretty worn out - are you too? It's not a shame if you aren't because you survived this set of tutorials perfectly! Have fun with the last chapter, which is a complete collection of code which we produced throughout the PHP/mySQL tutorials!

Da code, dude!

Copy-pasting this code will give you the complete administration page which we created with great efforts in the past lessons:

<?php

/* Administrator Page for mySQL databases.

Extendable to fit any Database!

Learn how this thing is built up: http://www.nr1webresource.com/article.php3?id=152 */

$dB = mysql_connect("localhost", "username", "password"); mysql_select_db("database",$dB); if ($t==1) {

$SQL="INSERT INTO authors VALUES('','$name','$email')";

$result=mysql_query($SQL,$dB);

} elseif ($t==2) {

$SQL="SELECT * FROM authors WHERE aid=$aid";

$result=mysql_query($SQL,$dB);

$row = mysql_fetch_array($result);

$name = $row["name"];

$email = $row["email"];

} elseif ($t==4) {

$SQL="DELETE FROM authors WHERE aid=$aid";

$result=mysql_query($SQL,$dB);

} else {

$SQL="UPDATE authors SET name='$name', email='$email' WHERE aid=$aid";

$result=mysql_query($SQL,$dB);

}

?>

<?php if ($t == 2) {

$t_value = 3;

} elseif ($t == 3) {

$t_value = 3;

} elseif ($t == 4) {

$t_value = 1;

} else {

$t=1;

$t_value = 1;

}

?>

<h1><?php

$t_headers = array('Insert Data','Edit Data','Data Edited','Record

Deleted'); if ($t == 1 && (isset($name) && isset($email))) { echo "Record Inserted";

$t_headers = "";

} echo $t_headers[$t-1];

?></h1>

<form name="author_admin" method="post" action="<?php echo

$PHP_SELF;?>">

<p>name: <input type="text" name="name" value="<?php echo

$name;?>"><br> e-mail: <input type="text" name="email" value="<?php echo $email;?>">

<input type="submit" value="Insert/Update"></p>

<input type="hidden" name="t" value="<?php echo $t_value;?>">

<input type="hidden" name="aid" value="<?php echo $aid;?>">

</form>

<a href="<?php echo $PHP_SELF;?>">Insert New Records</a><p>

<?php

$SQL="SELECT * FROM authors ORDER BY aid DESC LIMIT 0,30";

$result=mysql_query($SQL,$dB);

$num = mysql_num_rows($result);

$cur = 1; echo '<table width="300" border="1" cellspacing="2" cellpadding="1" class="content">

<tr>

<td nowrap><b>aid</b></td>

<td nowrap><b>name</b></td>

<td nowrap><b>email</b></td>

<td nowrap><b>action</b></td>

</tr>'; while ($num >= $cur) {

$row = mysql_fetch_array($result);

$aid = $row["aid"];

$name = $row["name"];

$email = $row["email"]; echo "<tr><td nowrap>$aid</td><td nowrap>$name</td><td nowrap>$email</td><td nowrap><a

href=\"$PHP_SELF?t=2&aid=$aid\">edit</a> | <a href=\"$PHP_SELF?t=4&aid=$aid\">delete</a></td></tr>";

$cur++;

} echo "</table>";

?>

See you in some other tutorial(s)! Cheers! :)

Download