Hackosis is an Open Blog. You Can Participate.

  • 15
  • Jul

PHP and MySQL are one of the most used technologies on the web today. By using about 7 different script files we can add, update, and delete rows from a MySQL table.

Example of completed project:

Simple MySQL Table Editor

Download the Simple PHP MySQL Table Editor.

Lets get started. I will explain each section of the script files so you have an understanding of how it works. You can download the project in a zip file above. The download also includes the example MySQL schema structure so you can test the script right away.

All examples in this post assume that you have already typed the php opening and closing tags. I cannot inlcude them on my page due to Wordpress plugins that I am running.

ALSO, because my PHP color coder sometimes runs off the page, you may have to click “show plain code” to view all typed PHP code.

HEADER.PHP:

Header.php stores the HTML header that include the title, etc. I am not going into detail since this is not a HTML tutorial.

I always start my PHP files with comments to indicate the purpose of the script and give contact details in case anyone has questions. Comments in PHP are indicated with ‘//’ for single lines and ‘/*’, ‘*/’ for multiple line comments:

  1. /**************************************************************************************
  2. *Header
  3. * Author: Shane <shane *at* hackosis *dot* com>
  4. * use this to learn, share, or what ever else floats your boat and finds your lost remote
  5. **************************************************************************************/

Now we print the HTML headers inside of the echo command. The ‘\n’ sends a line break to the browser so the source is readable. If we didn’t do that, it would be all one one line and look like doo doo:

  1. echo "<html>\n";
  2. echo "<head>\n";
  3. echo "<title>MySQL Table Editor by Hackosis.com</title>\n";
  4. echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />\n";
  5. echo "</head>\n";
  6. echo "<body>\n";

CONFIG.PHP:

Config.php stores our database connection details. Match this to what you have setup in your MySQL database. You may have to contact your systems administrator to get the details. Fill in the appropriate values for $dbhost, $username, and $password:

  1. $dbhost=‘127.0.0.1′;
  2. $dbusername=‘username’;
  3. $dbuserpass=‘password’;
  4. $dbname = ‘db1′;

INDEX.PHP:

Add the comments:

  1. /**************************************************************************************
  2. * Simple MySQL Table Editor index script - index.php
  3. * Author: Shane - shane *at* hackosis *dot* com>
  4. * use this to learn, share, or what ever else floats your boat and finds your lost remote
  5. **************************************************************************************/

The next part of the index.php script is going to require that the config.php be ran so we have the details to connect to the MySQL database:

  1. //Get database credentials
  2. require ‘config.php’;

Now we can connect to the MySQL database. The mysql_connect and mysql_select_db functions are used for this:

  1. // connect to the mysql database server.
  2. mysql_connect ($dbhost, $dbusername, $dbuserpass);
  3. //select the database
  4. mysql_select_db($dbname) or die(‘Cannot select database’);

Next, we are going to require a header.php script that will store our HTML header so we have (some what) valid code:

  1. require ‘header.php’;

After the initialization of the database connection and spitting out our HTMl header we define the MySQL query to display the data from our table. We are using a PHP variable to store the query string.

It is best to define the columns we want to SELECT, but for instructional purposes we will just use ‘*’ to select all columns:

  1. $query = "SELECT * FROM table1;";

Now we acually run the query on the database and store the results in an array. We use the mysql_query function to accomplish this:

  1. $result = mysql_query($query) or die(mysql_error());

We need some HTML to output or results in a way that will look nice in the browser window. I know tables are out of date and can be defined through CSS, but this is a PHP tutorial not HTML or CSS.

This snippit is using the echo command to output the true HTML code to the browser. You always have to use ‘\’ if you want to use double quote inside of the HTML code or we will get errors:

Spit out the header HTML for our editing table:

  1. //Table header
  2. echo "<div><table id=\"tableheader\" bgcolor=\"#4382b5\">\n";
  3. echo "<tr>\n";
  4. echo "<td>&nbsp;Column 1:</td>\n";
  5. echo "<td>&nbsp;Column 2:</td>\n";
  6. echo "<td>&nbsp;Column 3:</td>\n";
  7. echo "<td>&nbsp;Column 4:</td>\n";
  8. echo "<td>&nbsp;Column 5:</td>\n";
  9. echo "<tr>";
  10. echo "</table></div>";

Now we are going to count the number of rows returned from the MySQL query. The reason we do this is that we want to display a message stating there are no rows if that is the case:

  1. //Count the number of rows returned
  2. $count = mysql_num_rows($result);

Now comes the if statement to display the data IF there are rows, and if there are no rows we print “NO DATA” using an else statement.

Pay close attention to where the ‘{’ and the ‘}’ are because this defines were the if and else statements begin and end. This is really where we should start to indent, but you can see that in the download.

The while statement is REALLY important. What it is saying is that while there are rows print them to the browser. We use the mysql_fetch_array to achieve this.

This code also involves a form to update the data using the update.php script if we want to edit any of the data in the database. Also there is a delete button to delete rows that uses the delete.php script if we choose to do so:

  1. if ($count !== 0) {
  2. while($row = mysql_fetch_array($result)) {
  3. echo "<div class=\"addform\"><form method=’get’ action=\"update.php\">\n";
  4. echo "<input type=\"text\" value=\"".$row[column1]."\" name=\"column1\">\n";
  5. echo "<input type=\"text\" name=\"column2\" value=\"".$row[column2]."\"/>\n";
  6. echo "<input type=\"text\" name=\"column3\" value=\"".$row[column3]."\"/>\n";
  7. echo "<input type=\"text\" name=\"column4\" value=\"".$row[column4]."\"/>\n";
  8. echo "<input type=\"text\" name=\"column5\" value=\"".$row[column5]."\"/>\n";
  9. echo "<input type=\"image\" src=\"images/update.png\" alt=\"Update Row\" class=\"update\" title=\"Update Row\">\n";
  10. echo "<a href=\"delete.php?column1=".$row[column1]."\"><img title=’Delete Row’ alt=\"Delete\" class=’del’ src=’images/delete.png’/></a></form></div>\n";
  11. }
  12. echo "</table><br />\n";
  13. } else {
  14. echo "<b><center>NO DATA</center></b>\n";
  15. }

After printing the data, we have a form to add new records to the database. This is similar to the previous form, but it calls the add.php script to add new rows into the database:

  1. echo "<div class=\"addform\"><form method=’get’ action=\"add.php\">\n".
  2. "<input type=\"text\" name=\"column1\"/>\n".
  3. "<input type=\"text\" name=\"column2\"/>\n".
  4. "<input type=\"text\" name=\"column3\"/>\n".
  5. "<input type=\"text\" name=\"column4\"/>\n".
  6. "<input type=\"text\" name=\"column5\"/>\n".
  7. "<input type=\"image\" src=\"images/add.png\" alt=\"Add Row\" class=\"update\" title=\"Add Row\">\n".
  8. "</form></div>";

That pretty much completes the index.php file except for a legend to idiot proof the icons for adding, deleting, and updating records in the database. I have now escaped the PHP code and am using standard HTML:

  1. <br />
  2. <b>Legend:</b>
  3. <br />
  4. <img alt="Add" src="images/add.png"> Add a row after entering the correct information.<br />
  5. <img alt="Update" src="images/update.png"> Update a row after editing it.<br />
  6. <img alt "Delete" src="images/delete.png"> Delete a row.<br />
  7. </div>
  8. </body>
  9. </html>

UPDATE.PHP:

The update.php script will be called from the form on the index.php when we click the update button or hit enter on our keyboard when editing data already in the MySQL table.

Again, we are adding comments to the beginning of the script (click show plain code to view all):

  1. /**************************************************************************************
  2. * update row in database - update.php
  3. * Author: Shane  - <shane *at* hackosis *dot* com>
  4. * use this to learn, share, or what ever else floats your boat and finds your lost remote
  5. **************************************************************************************/

Also, we are again going to require the config.php to get the credentials to connect to the database. It is easier to keep the information in one file in case we have to update the credentials we only have to do it once:

  1. //Get database credentials
  2. require ‘config.php’;

Now we are going to use the predefined $_GET variable to pull the data from the URL that is stored when we edit data on the index.php script. This will store the value that we have inputted so we can update the database. We do this for each column we are going to update:

  1. $column1 = $_GET[‘column1′];
  2. $column2 = $_GET[‘column2′];
  3. $column3 = $_GET[‘column3′];
  4. $column4 = $_GET[‘column4′];
  5. $column5 = $_GET[‘column5′];

Then again, we connect to the MySQL server and select the database:

  1. // connect to the mysql database server.
  2. mysql_connect ($dbhost, $dbusername, $dbuserpass);
  3. //select the database
  4. mysql_select_db($dbname) or die(‘Cannot select database’);

Now that we are connected to the database we can store our MySQL query in a variable. This is where we use the variables pulled from the $_GET. This assumes that column1 is distinct and our primary key. It might be best if it was an auto increment column or some type of ID column. If it is not distinct then we might be updating rows we don’t want to. We use an UPDATE query to achieve this:

  1. $query = "UPDATE table1" .
  2. " SET column2 = ‘".$column2."’," .
  3. " column3 = ‘".$column3."’," .
  4. " column4 = ‘".$column4."’," .
  5. " column5 = ‘".$column5."’" .
  6. " WHERE column1 = ‘".$column1."’;";

And we run the query that updates the database:

  1. //Run the query
  2. $result = mysql_query($query) or die(mysql_error());

Now is where we redirect back to the index.php page because we don’t need to see anything happen. We use the header function to achieve this:

  1. //link variable is equal to the referring page
  2. $link = $_SERVER[‘HTTP_REFERER’];
  3. //sends a header directly to the browser telling it to redirect the user to the referring page
  4. header("Location: $link");

ADD.PHP

The add.php script file will use the add form we have on the index.php page to add rows into the database. This is very similar to the update.php, but we use a slightly different query called INSERT.

Again, we are adding comments:

  1. /**************************************************************************************
  2. * add row to database - add.php
  3. * Author: Shane <shane *at* hackosis *dot* com>
  4. * use this to learn, share, or what ever else floats your boat and finds your lost remote
  5. **************************************************************************************/

Again, we are requiring config.php:

  1. //Get database credentials
  2. require ‘config.php’;

Again, we are using the predefined $_GET variable to store data from the URL inputted from the add form on the index.php page:

  1. $column1 = $_GET[‘column1′];
  2. $column1 = $_GET[‘column1′];
  3. $column2 = $_GET[‘column2′];
  4. $column3 = $_GET[‘column3′];
  5. $column4 = $_GET[‘column4′];
  6. $column5 = $_GET[‘column5′];

Again, we are connecting and selecting the database:

  1. // connect to the mysql database server.
  2. mysql_connect ($dbhost, $dbusername, $dbuserpass);
  3. //select the database
  4. mysql_select_db($dbname) or die(‘Cannot select database’);

Now we are ready to define our MySQL query. Remember that we are using an INSERT query to add a row to the database. This is pulling the variable that we stored with the $_GET command and inserting them into the database:

  1. $query = "INSERT INTO `table1` ( `column1` , `column2` , `column3` , `column4` , `column5` )" .
  2. "VALUES (’".$column1."’, ‘".$column2."’, ‘".$column3."’, ‘".$column4."’, ‘".$column5."’);";

Now we run the MySQL query:

  1. //Run the queries
  2. $result = mysql_query($query) or die(mysql_error());

Again, we are redirecting back the the index.php page because we only need to execute the query, not view anything. We are also using the predefined $_SERVER variable to achieve this:

  1. //link variable is equal to the referring page
  2. $link = $_SERVER[‘HTTP_REFERER’];
  3. //sends a header directly to the browser telling it to redirect the user to the referring page
  4. header("Location: $link");

DELETE.PHP

The delete.php script delete rows from the database. This is called when you click the the delete button on the index.php page. This is very similar to the previous two scripts except we are using a DELETE MySQL query.

Again, we are adding comments:

  1. /**************************************************************************************
  2. * delete row from database- delete.php
  3. * Author: Shane  <shane *at* hackosis *dot* com>
  4. * use this to learn, share, or what ever else floats your boat and finds your lost remote
  5. **************************************************************************************/

Again, we are requiring the execution of config.php to pull the MySQL credentials:

  1. //Get database credentials
  2. require ‘config.php’;

Now since we have a primiary index and unique column of ‘column1′ it is safe to delete by this index. If it is not unique we might be deleting more then desired. We again use the predefined $_GET variable to pull the value from the URL:

  1. //Get the row ID to delete!
  2. $column1 = $_GET[‘column1′];

Again, we are connecting and selecting the MySQL database:

  1. // connect to the mysql database server.
  2. mysql_connect ($dbhost, $dbusername, $dbuserpass);
  3. //select the database
  4. mysql_select_db($dbname) or die(‘Cannot select database’);

After that we set the MySQL query and store it in a variable:

  1. //Set the query to return names of all employees
  2. $query = "DELETE FROM table1 WHERE column1 = ‘".$column1."’;";

Then again, we run the query to delete the row in the database:

  1. //Run the query
  2. $result = mysql_query($query) or die(mysql_error());

Now we redirect, again:

  1. //link variable is equal to the referring page
  2. $link = $_SERVER[‘HTTP_REFERER’];
  3. //sends a header directly to the browser telling it to redirect the user to the referring page
  4. header("Location: $link");

STYLE.CSS

There is a style.css style sheet also required by the header.php script. I am not including this here since this is not a CSS tutorial. You can find it in the download.

Thanks for stopping and I hope this PHP tutorial was useful to you. If you have any requests for PHP tutorials please leave a comment or contact me.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Posts


Tags: , , , ,

Like this post? Subscibe to the RSS feed.


8 Comments

  1. Jon Says:

    Very nice PHP script, would like to see more of this!

  2. Shane Says:

    Glad you enjoyed it Jon. Any suggestions to improve the script?

  3. Lyle Says:

    Your teaching method is great and easy to follow. I like how you take the reader through the code!!! More tutorials should be this way. Do you have any tutorials that are similar to goal tracking (MS Project)? You can email me at: sales@eisorwear.com

    Thanks again for the great learning eperience!!

  4. Matt Says:

    First off, thanks tor the tutorial.

    Let me warn you that I’m brand new to PHP/MySQL. I’m having trouble getting data to actually display. I’m fairly certain its a syntax problem with the query in update.php. Any help would be greatly appreciated.

    **********************************************************************
    $query = “UPDATE main” .
    ” SET place = ‘”.$column2.”‘,” .
    ” date = ‘”.$column3.”‘,” .
    //” date = ‘”.$column4.”‘,” .
    //” column5 = ‘”.$column5.”‘” .
    ” WHERE id = ‘”.$column1.”‘”;
    **********************************************************************
    you may email me directly if you wish. mtaylor143 AT gmail DOT com.

    thanks

  5. Mike Says:

    Hi, I get lots of rows, but they don’t seem to contain any data. Am I missing something? Do I need to amend the code so that the script uses the actual field names? I.e. don’t use [column1] etc??

  6. Mike Says:

    I set the table1 to correspond with my table and the columns to correspond with the fileds in the table, and can now see the data.

    BUT… when I try to update i get the following (example) error message:

    ‘You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘WHERE stockref = ‘dior0602100” at line 1′

    This seems to me to indicate that there is a problem with the syntax of the query, but I’ve tried and tried and don’t seem to be able to correct the problem. ANY suggestions?

  7. Shane Says:

    Can you print the query here that you are using character for character?

  8. Andy Says:

    Thanks for a great tutorial. You kept it nice and simple but I would like to have seen a search functions explained. Since you build all the other functions into a single page maybe a search page ‘add on’ could be written?

Leave a Comment