View Single Post
  #3 (permalink)  
Old Oct 22nd, 2007, 12:34
Rakuli's Avatar
Rakuli Rakuli is offline
SuperMember

SuperMember
Join Date: Sep 2007
Location: Australia
Age: 24
Posts: 956
Blog Entries: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Change it Around -- The UPDATE query

Okay so this some information on the update query.

Because of how the UPDATE query works, mySQL will need to know what data to update or else it will change everything. For the purposes of this example we will be using a hidden element in our form.

The value of the hidden input will be the PIG_ID of your pig. You should have received this from example on the INSERT QUERY

The form should look similar to :
PHP: Select all



<form name=”guineapigForm” action=”<?php echo $_SERVER[&#8216;php_self’]; ?>” method=”post”>

<label for=”pigName”>Guinea Pig Name</label>

<input type=”text” name=”pigName” id=”pigName” maxlength=”50” size=”30” /><br />

<label for=”pigColour”>Guinea Pig Colour</label>

<select name=”pigColour” id=”pigColour”>

<option value=”green”>Green</option>

<option value=”pink”>Pink</option>

<option value=”black”>Black</option

<option value=”blue”>Blue</option>

<option value=”polkadotted”>Polka Dots</option>

</select><br />

<label name=”pigAge”>Guinea Pig Age</label>

<input type=”text” name=”pigAge” id=”pigAge” maxlength=”3” size=”3” /><br />

<label name=”pigDescription”>Guinea Pig Description</label><br />

<textarea name=”pigDecription” id=”pigDescription”></textarea><br />
<input type="hidden" name="PIG_ID" value="1" />

<input type=”submit” name=”submitPig” value=”Save Your Pig!” />

</form>
PHP: Select all

<?php


// Okay, so we're only going to worry about adding anything to the database if the user has actually submitted the form
// We do this by checking of the submit button has been passed to the server we will check all data sent using
// $_POST becuase the action of out form is method="post" if it was method="get" we would replace $_POST with $_GET
// The name of our submit buttin is 'submitPig' so e check for that

if (isset($_POST['submitPig']) && !empty($_POST['PIG_ID']) && is_numeric($_POST['PIG_ID'])) 
// Isset checks that the variable has been set (does not check value its any usable type.. eg could be NULL or false)
// because we want to update a record with this script we will check to be sure that a PIG_ID has been sent and tha this id is a number
// You don't have to send the id in all cases, you could use a SELECT query to pull a record from the database based on criteria you specify
// Once you have retrieved the record you can then use that in the UPDATE query... For now though, we will use the PIG_ID sent in the form.
{

    
$_POST['PIG_ID'] = mysql_real_escape_string($_POST['PIG_ID']); // escape the data to be sure to be sure
    // Let's connect to the database
    
    
$con    mysql_connect('localhost''root''guineapigsrule'
    
    or 
    
// By adding the or die line we make it so the script will not continue if we cannot connect.
    
die ('Oh no! We could not connect');
    
    
// now select the database to be used
    
    
mysql_select_db('guineapigs'$con// databasename and then the connection id from above
    
    
or
    
    die (
mysql_error()); // die with mysql error response if we cannot select the database.


    // For this update script we will assume that *nothing* is required. When we created the record, we required everything so updating 
    // won't need such a firm hand -- you can be firm if you'd like but I'd be afraid they would yell at me :(

    
$errors = array(); // initialise an error array... We can still have errors of course.. A guinea pig names %%44$$ wouldn't make much sense
    
    
$updates = array(); // When we write the query to update our database, we will need columnName=value pairs.. This array will have the columnName as the 
                        // key of the array with the value as well, umm the value
    
    // The validation in use is very simple, it would be recommended to check in more detail in a live script
    
    // Check for a guineapig name
    
$_POST['pigName'] = @trim($_POST['pigName']); // trim the whitespace from both ends
    
    
if (!ctype_alpha($_POST['pigName']) || strlen($_POST['pigName']) > 50
    
// !ctype_aplha checks to make sure that the field only has alphabetic letters
    // strlen to check that field is not too long
        
$errors[] = 'How mean are you? You can\'t name your guinea pig that, image how much it will get teased at guinea pig school. Please make sure that the name is only letters and less that 50 at that.';
    
    else if (!empty(
$_POST['pigName']))  // We will only add to out $updates array if there is a value sent to us..
    
{
    
// Everything checks out so we will escape the data ready to insert into the database
        
$_POST['pigName']     = mysql_real_escape_string($_POST['pigName']);
        
$updates['pigName'] = $_POST['pigName'];
    }
        
    
    
// Now check the rest of the fields
    
    
$_POST['pigColour'] = @trim($_POST['pigColour']);
    
    if (!
ctype_alpha($_POST['pigColour']) || strlen($_POST['pigName']) > 20)
        
$errors[] = 'You poor piggie\'s colour has more than 20 letters or some crazy character in it. Please fix';
    else if (!empty(
$_POST['pigColour']))
    {
        
$_POST['pigColour'] = mysql_real_escape_string($_POST['pigColour']); 
        
$updates['pigColour'] = $_POST['pigColour'];
    }
    
    
$_POST['pigAge'] = @trim($_POST['pigAge']);
    
    if (!
is_numeric($_POST['pigAge']) || $_POST['pigAge'] > 999)
    
// Different check for a number, check that it is a number with !is_numeric and check that it is less that max 999
    
        
$errors[] = 'And *how* old is your little piggie? Make sure it\'s just numbers and less than 999.';
    else if (!empty(
$_POST['pigAge']))
    {
        
$_POST['pigAge'] = mysql_real_escape_string($_POST['pigAge']); 
        
$updates['pigAge'] = $_POST['pigAge'];
    }
        
        
// Now check the rest of the fields
    
    
$_POST['pigDescription'] = @trim($_POST['pigDescription']);
    
    if (!empty(
$_POST['pigDescription']))
    {
        
$_POST['pigDescription']   = mysql_real_escape_string($_POST['pigDescription']); 
        
$updates['pigDescription'] = $_POST['pigDescription'];
    }
    
    
// Obviously if they have sent nothing, we don't have to update anything so we will call this an error
    
    
if (!count($updates)) // count the updates we're making and make a fuss if they sent nuffin'
        
$errors[] = 'Did your guinea pig run across your keyboard? It would appear you have not sent any data... A shame that.';
    
        
        
    
// Now we have checked all of the fields, one of two this has happened
    // 1 -- we have some data to update in our database
    // 2 -- We don't
    // We will not continue if we have any errors cause that would be reckless and I don't want to break any rules just now
    
    
$ne count($errors); // Count the errors
    
    
    
if (!$ne) { // If there are no errors we will go to the database entry
    
    // Okay, an update to the data base is slightly tricker syntax to the insert it looks like :
    
    // UPDATE tableName SET thisColumn = 'thisValue', thisColumn2 = 'thisValue2', thisColumn3 = 'thisValue3'
    // Now, the above is enough on it's own to change the data BUT****** This will change every single entry in the
    // table. For an UPDATE query to be of any use at all, you really must tell mySQL what column to update you do this
    // using the WHERE clause. eg :
    
    //UPDATE tableName SET thisColumn = 'thisValue', thisColumn2 = 'thisValue2', thisColumn3 = 'thisValue3'
    //WHERE thisColumn = 'thisValue'
    // You don't have to use a column comparison you could use arbitrary statements like WHERE 1 = 1 but this is beyond the
    // scope of this little lesson.
    
    // This raises the question of how we are going to find out where to put OUR data.... In the text above this post
    // You will see that I got you to add a hidden form element that will send our pig's unique ID to the FORM
    // Later, when I get to the SELECT QUERY you will see how to dynamically add the PIG_ID to the form using SELECT
    // but for now you can just hard code in the ID of your pig (which is given to you on a successful INSERT in the above post)
    // The pig id will be in $_POST['PIG_ID']
    
    // To write the UPDATE query from scratch it would look similar to
    
    // UPDATE petGuineapigs SET pigName = 'The pig formally known as Johny', pigColour = 'purplybrown', pigAge = 136, pigDescription = 'Johnny did not like beging known as johnny so he changed his name.' 
    // WHERE PIG_ID = 1
    
    // Because of the slightly more complex syntax of the UPDATE query, we have added the updates to the $updates array so we can use 
    // a foreach loop to create the updates in the list
    
    
$query  "UPDATE petGuineapigs SET "// The first part of the query
    
    
$i 0// because we need a comma to separate values and don't want a trailing comma we will only add the comma to the second 
            // update....
    
foreach ($updates as $column => $value)
    {
        
$query .= ($i ', ' '') . $column " = '" $value "'";
        
$i++; // increment one to add commas for all after the first
    
}
    
    
// finish off the query with the WHERE clause
    
    
$query .= " WHERE PIG_ID = {$_POST['PIG_ID']} ";
    

    
// now we will run the query
    
    
mysql_query($query)
                or
                die (
'Shite! -- Go and sit in the corner for a minute ' mysql_error());
    
    
// Okay, just because we didn't die does not mean it was a success. mysql will consider it a success even if it didn't add anything
    // we have to check and see if any rows were affected
    
    
$success mysql_affected_rows(); // How many rows were updated
    
    
if ($success)
    
// Successful? Jump up and down and clap excitedly
        
$message 'Your guinea pig was successfully updated... the query looked like this <pre>' $query '</pre>';
    else
    
// Oh! Punish yourself by biting your pinkie finger
        
$message ' Nothing was updated, your pig must be having an identity crisis :( check your PIG_ID';
    

    } else {
        
// Now we are in here because we had some errors so we will add the errors to a message string
        // to display later.
        
        
$message '<strong>Something went awry!</strong>
                    <ol>'
;
        
        foreach (
$errors as $error)
            
$message .= '<li>' $error '</li>';
        
        
$message .= '</ol>';
    }
}


?>

<html>
<head>
<!-- Head stuff here //-->
</head>
<body>
<?php 
// Echo the message from above it is set
echo !empty($message) ? $message ''
?>

<!-- The form goes below etc.... //-->
</body>
</html>
I was a little tired writing this so if you spot an error please PM me and I will update.

Cheers

Last edited by Rakuli; Oct 28th, 2007 at 09:52.
Reply With Quote