Categories
PHP

Test for Database Table in PHP

Sometimes it's handy to be able to detect whether a given table exists, such as when you want to create a table if it isn't present.

The following example will detect the presence of a table in the simplest way I can think of.

 if(mysql_num_rows( mysql_query("SHOW TABLES LIKE 'tablename'"))) {
    // table is present
    // execute some code here
 };

Alternatively, a small change to reverse the logic will let you react if the table does not exist. Note the exclamation point which means "not" and changes the logic to respond if the table does not exist.

 if(!mysql_num_rows( mysql_query("SHOW TABLES LIKE 'tablename'"))) {
    // table is not present
    // here you might want to create the missing table
 };

If you're not familiar with PHP, the logic of the first if() statement says essentially this:

Query the database to see how many tables are named 'tablename'.

Because only one table in the database can have the name, only two responses are possible: 1 or 0. In boolean logic, those values represent Yes/No or True/False respectively and can be acted on.

If the condition is satisfied (yes, the table exists in the first example above or no, the table does not exist in the second example above), the code between the braces {} will be executed.

Categories
PHP

Writing Secure PHP Code

I won't try to reinvent the wheel here.

These articles from Dave and AddedBytes.com do the job just fine.

Writing Secure PHP

Categories
PHP

PHP Debug Message Function

PHP coders frequently need to display a message in code for debugging purposes. It helps to be able to display these messages in a distinctive matter that sets them apart from normal page content, and to display the line number where the message was triggered.

This function displays the massage in a visually distinctive form, and prepends the line number from which the function is called.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function debugMsg($message) {
	/*-------------------------------------------------------------------------------------------------
	 *   SCRIPT: debugMsg()
	 *  PURPOSE: Accept a text string and display is in a formatted div, preceeded by the line
	 *           number of the line that called the message.
	 *   SYNTAX: debugMsg('this is my error message.');
	 *-----------------------------------------------------------------------------------------------*/
	// 	
	// determine calling line - line number which called this function	
	// Reference: http://php.net/manual/en/function.debug-backtrace.php
	$call_info = array_shift( debug_backtrace() );
	$calling_line = $call_info['line'];
	// now print the message with the line number from which the message was generated.
	echo "<div style='border:1px dashed silver;background-color:#F7F3E8;margin:.25em; padding:.25em .5em;color:darkgray;font-size:100%;'>";
	echo "<pre style='margin:0px;'>$calling_line: $message</pre>";
	echo "</div>";
}
Categories
MySQL PHP

Loading configuration data from a MySQL into PHP constants

The following code will take the contents of the first row of a configuration table and create a constant for each attribute stored in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ----------------------------- LOAD CONFIGURATION DATA FROM DATABASE -----------------------------
// Each data element in first row is placed in a constant using attribute name as constant name
// The array_slice function eliminates the first attribute in the row, 'id', which is the primary
//   key and not relevant for our purposes.
$result = mysql_query("SELECT * FROM configuration WHERE id = '1'") or die(__LINE__." SELECT Error: ".mysql_error());
if($result != false and mysql_num_rows($result)) {
    foreach(array_slice(mysql_fetch_assoc($result), 1) as $key => $val) {
        if(!defined($key)) {
            define(strtoupper($key), $val);
        } else {
            user_error("'$key' already defined.");
        }
    }
}
// ---------------------------- /load configuration data from database -----------------------------
Categories
MySQL PHP

Building a dynamic SELECT list with PHP and MySQL

A common scenario in web applications is the need to create a <SELECT> list using a set of values extracted from a lookup table in a database. This article will explore a simple example of how to do that.

For this example, imagine that in our database we have a lookup table, lu_status, that holds all the possible values we will use for the status field in our form.  Imagine also the the attribute name in our form is 'status', and that our lu_status table has two attributes; status, which is the value and option_label which will be the visible label in the select control drop list. Because we might be using the <select> list in a form to edit existing records in a data table, we can also assume that the current value of the status attribute, if any, is in the variable $status.

In line 2, we create a variable, $select_status, and put the first line of the code for our select control in it.  The name 'status' in that line is the attribute name in the data table that the form will be feeding. The \n at the end of the line will cause a line break in the source code of the HTML page, making it easier to read and troubleshoot.

Line 3 is the default –SELECT ONE– value commonly used in forms when no value has previously been selected.

Lines 4-12 are where we access that database and get to work.

In line 4, we read all the possible values from the lookup table which we will use to populate our select list.

Line 5 opens a while loop which we will use to process each row that we read from the lookup table in the previous row, creating a <option> element for each.

Line 6 opens the <option> element.

Lines 7-11 are an if statement which will determine if the current value of the status attribute (if there is a current value) matches the current status attribute of the current row from the lookup table. If so, it adds the attribute selected='selected' to the option element, otherwise it creates the element without the selected attribute. In either case, the status attribute and option_label attribute from the current row are inserted into the <option> element appropriately. Each row in the table lu_status will be processed this way inside the while loop.

Now that we've build all our <option> elements, all that remains is to close the <select> control in line 13 and we're done.

Here's the PHP code;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// assemble the HTML code for the <select> list in a variable called $select_status
$select_status = "<select name='status'>\n";
$select_status .= "<option value=''>SELECT ONE</option>\n";
$dataset = mysql_query("SELECT * FROM lu_status");
while($row=mysql_fetch_array($dataset)) {
  $select_status .= "<option value='".$row['option_label']."'";
  if (strtolower($row['status']) == strtolower($status)) {
    $select_status .= " selected='selected'>".$row['option_label']."</option>\n";
  } else {
    $select_status .= ">".$row['option_label']."</option>\n";
  }
} // end while loop
$select_status .= "</select>\n";
// now insert the <select> list control into the page
echo "$select_status";

And here's the HTML code we will see generated;

1
2
3
4
5
<select name='status'>
  <option value=''>SELECT ONE</option>
  <option value='active' selected='selected'>Active</option>
  <option value='inactive'>Inactive</option>
</select>