Blogroll

photoshop cs6 html 5 css php seo backlinks

adsense

Smarty Template Engine Step by Step Tutorial

Smarty has focused on how to help you make an high-performance, scalability, security and future growth application.

JavaScript was designed to add interactivity to HTML pages

JavaScript’s official name is ECMAScript, which is developed and maintained by the ECMA International organization.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Sunday, 9 February 2014

How to update data in a database?

In previous lessons, you have learned to insert, retrieve and delete data from a database. In this lesson, we will look at how to update a database, i.e., edit the values of existing fields in the table.

Update data with SQL

The syntax for an SQL statement that updates the fields in a table is:
 
 UPDATE TableName SET TableColumn='value' WHERE condition
 
 
It is also possible to update multiple cells at once using the same SQL statement:
 
 UPDATE TableName SET TableColumn1='value1', TableColumn2='value2' WHERE condition 

 
With the knowledge you now have from the lessons 19, 20 and 21, it should be quite easy to understand how the above syntax is used in practice. But we will of course look at an example.

Example: Update cells in the table "people"

The code below updates Donald Duck's first name to D. and changes the phone number to 44444444. The other information (last name and birthdate) are not changed. You can try to change the other people's data by writing your own SQL statements.
 <html>
 <head>
 <title>Update data in database</title>

 </head>
 <body>

 <?php
 // Connect to database server
 mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

 // Select database
 mysql_select_db("mydatabase") or die(mysql_error());
 
 // The SQL statement is built
 $strSQL = "Update people set "; 
 $strSQL = $strSQL . "FirstName= 'D.', "; 
 $strSQL = $strSQL . "Phone= '44444444' "; 

 $strSQL = $strSQL . "Where id = 22"; 

 // The SQL statement is executed 
 mysql_query($strSQL);

 // Close the database connection
 mysql_close();
 ?>

 <h1>The database is updated!</h1>
 </body>
 </html>

 
This example completes the lessons on databases. You have learned to insert, retrieve, delete and update a database with PHP. Thus, you are actually now able to make very advanced and dynamic web solutions, where the users can maintain and update a database using forms.

How to delete data from database?

In the two previous lessons, you have learned to insert and retrieve data from a database. In this lesson, we'll look at how to delete records in the database, which is considerably easier than inserting data.

Delete data using SQL

The syntax for an SQL statement that deletes records is:
 
 DELETE FROM TableName WHERE condition 

 

Example: Delete a record

When deleting a record, you can use the unique AutoNumber field in the database. In our database, it is the column named id. Using this unique identifier ensures that you only delete one record. In the next example, we delete the record where id has the value 24:
 <html>
 <head>
 <title>Delete data in the database</title>
 </head>

 <body>
 
 <?php
 // Connect to database server
 mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

 // Select database
 mysql_select_db("mydatabase") or die(mysql_error());

 // The SQL statement that deletes the record
 $strSQL = "DELETE FROM people WHERE id = 24";
 mysql_query($strSQL);
 
 // Close the database connection
 mysql_close();
 ?>

 <h1>Record is deleted!</h1>

 </body>
 </html>
 

How to get data from database? SQL queries

Now it's time to retrieve data from our database to our PHP pages.
This is really one of the most important lessons in this tutorial. Once you have read and understood this lesson, you will realize why database-driven web solutions are so powerful, and your views on web development will be expanded dramatically.

SQL queries

To retrieve data from a database, you use queries. An example of a query could be: "get all data from the table 'people' sorted alphabetically" or "get names from the table 'people'".
Again, the language Structured Query Language (SQL) is used to communicate with the database. Try looking at this simple example:
 Get all data from the table 'people'
 
 
Will be written like this in SQL:
 SELECT * FROM people
 
 
The syntax is pretty self-explanatory. Just read on and see how SQL statements are used in the examples below.

Example 1: Retrieve data from a table

Therefore, it is important that you read these lessons first.
The example shows how data in the table "people" is retrieved with an SQL query.
The SQL query returns a result in the form of a series of records. These records are stored in a so-called recordset. A recordset can be described as a kind of table in the server's memory, containing rows of data (records), and each record is subdivided into individual fields (or columns).
A recordset can be compared to a table where each record could be compared to a row in the table. In PHP, we can run through a recordset with a loop and the function documentationmysql_fetch_array, which returns each row as an array.
The code below shows how to use documentationmysql_fetch_array to loop through a recordset:
 <html>
 <head>
 <title>Retrieve data from database </title>
 </head>
 <body>

 <?php
 // Connect to database server
 mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

 // Select database
 mysql_select_db("mydatabase") or die(mysql_error());

 // SQL query
 $strSQL = "SELECT * FROM people";

 // Execute the query (the recordset $rs contains the result)
 $rs = mysql_query($strSQL);
 
 // Loop the recordset $rs
 // Each row will be made into an array ($row) using mysql_fetch_array
 while($row = mysql_fetch_array($rs)) {

    // Write the value of the column FirstName (which is now in the array $row)
   echo $row['FirstName'] . "<br />";

   }

 // Close the database connection
 mysql_close();
 ?>
 </body>
 </html>
 
 
Notice that for every record how we get the content of the column "FirstName" by typing $row['FirstName']. Similarly, we can get the content of the column "Phone" by writing $row['Phone'], for example.
The order of the recordset is exactly the same as in the table in the database. But in the next example, it will be shown how to sort recordset.

Example 2: Sort the data alphabetically, chronologically or numerically

Often it can be helpful if a list or table of data is presented alphabetically, chronologically or numerically. Such sorting is very easy to do with SQL, where the syntax Order By ColumnName is used to sort according to the column contents.
Look at the SQL statement from the example above:
 strSQL = "SELECT * FROM people"
 
 
The records can, for example, be sorted alphabetically by the first name of the people this way:
 strSQL = "SELECT * FROM people ORDER BY FirstName"
 
 
Or chronologically by date of birth like this:
 strSQL = "SELECT * FROM people ORDER BY BirthDate"
 
 
The sorting can be charged from ascending to descending by adding DESC:
 strSQL = "SELECT * FROM people ORDER BY BirthDate DESC"
 
 
In the following example, the people are sorted by age:
 <html>
 <head>

 <title>Retrieve data from database </title>

 </head>
 <body>
 
 <?php
 // Connect to database server
 mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

 // Select database
 mysql_select_db("mydatabase") or die(mysql_error());

 // SQL query
 $strSQL = "SELECT * FROM people ORDER BY BirthDate DESC";

 // Execute the query (the recordset $rs contains the result)
 $rs = mysql_query($strSQL);
 
 // Loop the recordset $rs
 while($row = mysql_fetch_array($rs)) {

    // Write the value of the column FirstName and BirthDate
   echo $row['FirstName'] . " " . $row['BirthDate'] . "<br />";

   }

 // Close the database connection
 mysql_close();
 ?>

 </body>
 </html>
 
 
Try to change the SQL statement yourself and sort the records by first name, last name or phone number.

Retrieve selected data

Until now, our SQL statement retrieves all rows from the table. But often you need to set criteria in the SQL query for the data to be retrieved, for instance, if we only want the rows for those who have a particular phone number or a certain last name.
Say, we only want to retrieve people from the database who have the phone number "66554433". That could be done like this:
 strSQL = "SELECT * FROM people WHERE Phone = '66554433 '"
 
 
There are six relational operators in SQL:
= Equals
< Less than
> Greater Than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
In addition, there are some logical operators:
AND
OR
NOT
 for more information on how to set up conditions.
In the next example, we use conditions to set up an address book.

Example 3: Address book

In this example, we will try to combine many of the things you have just learned. We will make a list of the names from the database where each name is a link to further details about the person.
For this, we need two files - list.php and person.php - with the following code:

The code of list.php

 <html>
 <head>
 <title>Retrieve data from the database</title>
 </head>
 <body>

 <ul>

 <?php
 // Connect to database server
 mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

 // Select database
 mysql_select_db("mydatabase") or die(mysql_error());

 // SQL query
 $strSQL = "SELECT * FROM people ORDER BY FirstName DESC";

 // Execute the query (the recordset $rs contains the result)
 $rs = mysql_query($strSQL);
 
 // Loop the recordset $rs
 while($row = mysql_fetch_array($rs)) {

    // Name of the person
   $strName = $row['FirstName'] . " " . $row['LastName'];

    // Create a link to person.php with the id-value in the URL
    $strLink = "<a href = 'person.php?id = " . $row['id'] . "'>" . $strNavn . "</a>";

     // List link
    echo "<li>" . $strLink . "</li>";

   }

 // Close the database connection
 mysql_close();
 ?>

 </ul>
 </body>
 </html>

 
 

The code for person.php

 <html>
 <head>
 <title>Retrieve data from database</title>
 </head>
 <body>

 <dl>

 <?php
 // Connect to database server
 mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

 // Select database
 mysql_select_db("mydatabase") or die(mysql_error());

 // Get data from the database depending on the value of the id in the URL
 $strSQL = "SELECT * FROM people WHERE id=" . $_GET["id"];
 $rs = mysql_query($strSQL);
 
 // Loop the recordset $rs
 while($row = mysql_fetch_array($rs)) {

  // Write the data of the person
  echo "<dt>Name:</dt><dd>" . $row["FirstName"] . " " . $row["LastName"] . "</dd>";
  echo "<dt>Phone:</dt><dd>" . $row["Phone"] . "</dd>";
  echo "<dt>Birthdate:</dt><dd>" . $row["BirthDate"] . "</dd>";

 }

 // Close the database connection
 mysql_close();
 ?>

 </dl>
 <p><a href="list.php">Return to the list</a></p>

 </body>

 </html>
 
 
The address book example is rather simple, but it shows the potential of working with PHP and databases.
Imagine that the database had contained 10,000 products with detailed descriptions. By making a few changes in the above files, you could easily create a product catalogue with more than 10,000 pages with only one database and two PHP files.

Insert data into a database free tutorial

In this lesson, we look at how you can insert data into the database directly from your PHP scripts.

Insert data using SQL

You use SQL to insert data in a database in the same way that you can use SQL to create databases and tables. The syntax of the SQL query is:
 INSERT INTO TableName(column1, column2, ...) VALUES(value1, value2, ...) 
 
 
As you can see, you can update multiple columns in the SQL statement by specifying them in a comma-separated list. But of course, it is also possible to specify just one column and one value. The columns that are not mentioned in the SQL statement will just be empty.

Example: Insert a new person in the table

In this example we use the database from lesson 18. Let's say we want to insert a person into the database. It could be the person Gus Goose with the phone number 99887766 and 1964-04-20 as the date of birth.
The SQL statement would then look like this:
 
 $strSQL = "INSERT INTO people(FirstName,LastName,Phone,BirthDate) VALUES('Gus','Goose','99887766 ','1964-04-20')"; 

 mysql_query($strSQL) or die(mysql_error());
 
 
As you can see, SQL statements can get quite long, and you can easily lose track. Therefore, it can be an advantage to write the SQL statement in a slightly different way:
 strSQL = "INSERT INTO people(";

 strSQL = strSQL . "FirstName, ";
 strSQL = strSQL . "LastName, "
 strSQL = strSQL . "Phone, ";
 strSQL = strSQL . "birth) ";

 strSQL = strSQL . "VALUES (";

 strSQL = strSQL . "'Gus', ";
 strSQL = strSQL . "'Goose', ";
 strSQL = strSQL . "'99887766', ";

 strSQL = strSQL . "'1964-04-20')";
  
 mysql_query($strSQL) or die(mysql_error());
 
 
This way, the SQL statement is built up by splitting the sentence into small parts and then putting those parts together in the variable $strSQL.
In practice, it makes no difference which method you choose, but once you start working with larger tables, it's crucial that you always keep track, so choose the method you find most convenient.
Try running the following code to insert Gus Goose into the database:
 <html>
 <head>
 <title>Insert data into database</title>
 </head>
 <body>
 <?php

 // Connect to database server
 mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

 // Select database
 mysql_select_db("mydatabase") or die(mysql_error());

 // The SQL statement is built

 $strSQL = "INSERT INTO people(";

 $strSQL = $strSQL . "FirstName, ";
 $strSQL = $strSQL . "LastName, ";

 $strSQL = $strSQL . "Phone, ";
 $strSQL = $strSQL . "BirthDate) ";

 $strSQL = $strSQL . "VALUES(";

 $strSQL = $strSQL . "'Gus', ";

 $strSQL = $strSQL . "'Goose', ";
 $strSQL = $strSQL . "'99887766', ";

 $strSQL = $strSQL . "'1964-04-20')";

 // The SQL statement is executed 
 mysql_query($strSQL) or die (mysql_error());

 // Close the database connection
 mysql_close();
 ?>

 <h1>The database is updated!</h1>
 </body>
 </html>
 
 

Save user input into a database

Often you want to save user input in a database.
As you've probably already figured out, this can be done by creating a form as described in lesson 11 - where the values from the form fields can be inserted in the SQL statement. Suppose you have a simple form like this:
 <form action="insert.php" method="post">
 <input type="text" name="FirstName" />
 <input type="submit" value="Save" />

 </form>
 
 
The form submits to the file insert.php where you, as shown in lesson 11, can get the user's input by requesting the form content. In this particular example, an SQL statement could look like this:
 strSQL = "INSERT INTO people(FirstName) values('" . $_POST["FirstName"] . "')"
 
 
In the same way, it is possible to retrieve data from cookies, sessions, query strings, etc.

Most common beginner mistakes

In the beginning, you will probably get a lot of error messages when you try to update your databases. There is no room for the slightest inaccuracy when you work databases. A misplaced comma can mean the database is not being updated, and you get an error message instead. Below, we describe the most common beginner mistakes.

Wrong data types

It is important that there is consistency between the type of data and column. Each column can be set to a data type. The screenshot below shows the data types for the table "people" in our example.
Specifying data types
An error occurs if you, for example, attempt to insert text or numbers in a date field. Therefore, try to set the data types as precisely as possible.
Below is the most common data types listed:
SettingData TypeSize
CHARText or combinations of text and numbers. Can also be used for numbers that are not used in calculations (e.g., phone numbers).Up to 255 characters - or the length defined in the "Length"
TEXTLonger pieces of text, or combinations of text and numbers.Up to 65,535 characters.
INTNumerical data for mathematical calculations.4 bytes.
DATEDates in the format YYYY-MM-DD3 bytes.
TIMETime in the format hh:mm:ss3 bytes.
DATETIMEDate and time in the format YYYY-MM-DD hh:mm:ss8 bytes.

SQL statements with quotes or backslash

If you try to insert text that contains the characters single quote ('), double quote (") or backslash (\), the record may not be inserted into the database. The solution is to add backslashes before characters that need to be quoted in database queries.
This can be done with the function documentationaddslashes this way:
 <?php

 $strText = "Is your name O'Reilly?";
 $strText = addslashes($strText);

 ?>
 
 
All single quotes ('), double quotes (") and backslashs (\) will then get an extra backslash before the character. This would only be to get the data into the database, the extra \ will not be inserted. Please note that PHP runs documentationaddslashes on all $_GET, $_POST, and $_COOKIE data by default. Therefore do not use documentationaddslashes on strings that have already been escaped.