Categories
MySQL PHP Snippet

Quick and Dirty: List records in a table using PHP and MySQL

This code lists reads a dataset from the database and lists all attributes in a table. 

This code sample is deliberately quite basic, though CSS is used (through the $bgcolour variable) to create alternating background colours for the rows.

The code assumes you have already connected to a database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
echo "<table border='0'>";
// capture the data
$dataset = mysql_query("SELECT * FROM tablename");
// now process the dataset, one row at a time
while ($row = mysql_fetch_assoc($dataset)) {
  // create a variable for each attribute in the record
  //  - variables are easier to use when building the table 
  foreach($row as $var => $value) {
    $$var = $value;
  }
  // set the alternating background colour for the row
  $bgcolour = (!isset($bgcolour) || $bgcolour == "#F0F7FF") ? "#FFFFFF" : "#F0F7FF";
  // build the rows, placing the variables in <td> elements as appropriate
  echo "\n<tr style="background-color:$bgcolour;">";
  echo "\n<td style="font-size:80%;">$attribute</td>";
  echo "\n</tr>";
} // end while
echo "</table>";
Categories
PHP

Calculating a fiscal year in PHP

This code is a straight cut and paste from a comment the php.net page on the strftime() function, credit is due to lamb dot dan at gmail dot com.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
/*
*    This function figures out what fiscal year a specified date is in.
*    $inputDate - the date you wish to find the fiscal year for. (12/4/08)
*    $fyStartDate - the month and day your fiscal year starts. (7/1)
*    $fyEndDate - the month and day your fiscal year ends. (6/30)
*    $fy - returns the correct fiscal year
*/
function calculateFiscalYearForDate($inputDate, $fyStart, $fyEnd){
    $date = strtotime($inputDate);
    $inputyear = strftime('%Y',$date);
 
    $fystartdate = strtotime($fyStart.$inputyear);
    $fyenddate = strtotime($fyEnd.$inputyear);
 
    if($date < $fyenddate){
        $fy = intval($inputyear);
    }else{
        $fy = intval(intval($inputyear) + 1);
    }
 
    return $fy;
 
}
 
// my fiscal year starts on July,1 and ends on June 30, so...
echo calculateFiscalYearForDate("5/15/08","7/1","6/30");
// returns 2008
 
echo calculateFiscalYearForDate("12/1/08","7/1","6/30");
// returns 2009
?>
Categories
MySQL PHP

Prevent SQL Injection attacks in PHP and MySQL

Place this code in your database connect include, just before the database connection is made.

This ensures that SQL injection attempts are handled before the database is opened.

By doing it up front like this, the input is already escaped and we don't have to deal with it in our other scripts as we use input data.

1
2
3
4
5
6
7
8
9
10
11
12
// ~~~~~~~~~~~~~~~~~~~~ SECURE ALL INPUT FROM SQL INJECTION ~~~~~~~~~~~~~~~~~~~~~~~~ //
// --- escape special characters in input data to prevent SQL injection attacks ---- //
 
// Prevent SQL Injection attacks in POST vars
foreach ($_POST as $key => $value) {
  $_POST[$key] = mysql_real_escape_string($value);
}
// Prevent SQL Injection attacks in GET vars
foreach ($_GET as $key => $value) {
  $_GET[$key] = mysql_real_escape_string($value);
}
// ~~~~~~~~~~~~~~~~~~~ /secure all input from sql injection ~~~~~~~~~~~~~~~~~~~~~~~~ //
Categories
CSS PHP WordPress

Changing the font of code blocks with geshi syntax highlighter

By default, geshi-derived syntax highlighters use a serif font to display code blocks.  Many people find serif fonts less clear than the visually simpler sans-serif fonts.

A good choice is Lucida Console.  Consolas is even better because it has a slashed zero, which is easier to distinguish from the capital letter "O", though not as many computers have Consolas installed. To account for this, list the fonts in order of preference, the browser will use the first one that it can display.

To change the default font for code blocks, find the geshi code folder (usually under plugins), open geshi.php and look for the following code:

1
2
3
4
5
    /**
     * The overall style for this code block
     * @var string
     */
    var $overall_style = 'font-family:monospace;';

And modify is as seen here. Note that two word font names must be quoted, and the quote marks may need to be escaped, as seen below;

1
2
3
4
5
    /**
     * The overall style for this code block
     * @var string
     */
    var $overall_style = 'font-family:Consolas, \'Lucida Console\', monospace;';
Categories
Database MySQL PHP

Import CSV file to MySQL Database using PHP

<!--p 
 
/** ~~~~~~~ CSV IMPORT TO DATABASE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  *
  * This script reads in a comma delimited text file (.csv) and creates
  * a table in the database from it.
  *
  * The table will be emptied to start with if it is already in the database.
  *
  * Have not yet tried this with a .csv file that did -not- have column
  * headers as the first row
  *
  * Requirements: the csv file needs to be the same name as the table,
  *               comma separated with the columns in the same order as the table,
  *               and in the same dir as this script
  *
  * It may be necessary to run this script repeatedly to correct minor data errors in the CSV.
  *
  * TO FIX: Doesn't carry on as intended when it hits a data error, perhaps because
  *    of 'or die' code below. Maybe doesn't need to be fixed.
  *
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  */
 
include("../includes/connect-string.inc.php");  
 
$table          = array( 'districtmembers'); // assign the tables that you want to import to to the table array
$columnheadings = 1; // 1 if first row of files is column headings, 0 if not and first line should be read as a record
$emailaddress   = "test@nosuchdomaincom"; // contains the email address you want the results sent to
$emailfrom      = "test@nosuchdomaincom"; // contains the email address that will show in the from line
$localtime      = gmdate('F j, Y, g:i:s a', time() + (-18000));  // current local time
$runtime        = (date("d M Y H:i:s Z ")); // set to the date and time the script was run 
 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
// perform the required operations for every table listed in the table array
foreach ($table as $tablename) { 
 
  $deleterecords = "TRUNCATE TABLE `$tablename`"; # empty the table of its current records
  mysql_query($deleterecords) or die("Query failed: $deleterecords = " . mysql_error());  
 
  $pass = 0; # intialize counters for successful record imports
  $fail = 0; # intialize counters for failed record imports 

  $file_handle = fopen ("$tablename.csv","r");
  while (($row = fgetcsv($file_handle, 1000, ",")) !== false) {
 
    if ($row[0] == "CLUBNAME") {continue;}  // skip the first line which is just the column names
    // ~~~~ clear the last element in the array if it is a null value,      ~~~~~//
    // ~~~~ such null values will be caused by a trailing comma on the line ~~~~~//
    if ($row[count($row) - 1] == "") {
      unset($row[count($row) - 1]);
    } // close if
 
    $insertrecord = "Insert Into `$tablename` Values (\"".implode('", "', $row)."\")";   
 
    mysql_query($insertrecord) or die("
 
Query failed: $insertrecord = " . mysql_error());
      if(mysql_error()) {
           $fail += 1;     # increments if there was an error importing the record
      } else {
          $pass += 1;     # increments if the record was successfully imported
      }
  } // end while
 
  # adds a line to the email message we will send stating how many records were imported
  # and how many records failed for each table
  $message .= "Table $tablename was loaded with data from the .csv file.\n\n   Success=$pass\n   Failure=$fail \n";
} // close foreach
 
echo "
 
Table $table[0] was loaded with data from the file <span style="color:maroon;" mce_style="color: maroon--><strong>$tablename.csv</strong>.";
echo "
 
$localtime.";
echo "
<ul>
	<li>Success: $pass
 
";
echo "</li>
	<li>Failure: $fail</li>
</ul>
";
 
print "
 
".gmdate('F j, Y, g:ia', time() + (-18000))." EST";
 
/**
  * Confirmation Email
  *
  * Some email code ideas from
  * http://www.phpnoise.com/tutorials/12/4
  *
  *
  */
$to = "D7040 Webmaster ";
$from = "D7040 Webmaster ";
$subject = "D7070 DB Update: Table $tablename with $pass records";
$message = "
 
The <span style="color: #0a0000;"><strong>$tablename</strong></span> table in the district database was updated $localtime.
<ul>
	<li>Success: $pass</li>
	<li>Failure: $fail</li>
</ul>
<em>This is an automated message.</em>
 
 ";
$headers  = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n"; 
 
/**
  * Notification in browser of success/failure if notification email.
  *
  */
$success = mail($to, $subject, $message, $headers);
if ($success)
    echo "
 
The confirmation email to <strong>$to</strong> from <strong>$from</strong> was successfully sent";
else
    echo "
 
An error occurred when sending the confirmation email to $to from $from";
 
?&gt;