Categories
Database MySQL

Selecting Field Names in MySQL

Selecting field names in MySQL is pretty easy, though it's not quite like the SELECT syntax we're all used to:

SHOW COLUMNS FROM TABLE;

To select all fields that start with 'customer' we extend that a little bit, note the wild card to select all fields that start with 'customer'.

SHOW COLUMNS FROM TABLE LIKE 'customer%';
Categories
Database MySQL

Resetting a MySQL Password

Resetting a MySQL root password (or other password, for that matter) is easy enough if you have admin access to the server.

First go to the command line (Start > Run > "cmd") and type "mysqladmin" – and see a bunch of output text, you're good to go. otherwise you'le need to locate mysqladmin.exe and navigate to that folder.

Once there, enter the following command:

mysqladmin -u root password NEWPASSWORD

and you're good to go!

Categories
Database MySQL

Adding a UNIQUE constraint to a database column

Sometimes we may need to make a column unique in a database table.  For instance we can't have two employees with the same employees with the same employee number or pension plan id.

To prevent this, run a query like the following to place a constraint on the attribute or attributes;

ALTER TABLE Employee ADD UNIQUE (EmpID, PensionID)

There are many other uses of the ALTER command that will help us modify our existing tables.  See this article for more useful applications of the ALTER command.

Categories
Database MySQL

Pulling database values in multiple formats

When we pull a value from MySQL or another database, there's nothing stopping us from pulling the same value in different ways within the same query.

For instance, say we want to pull dates in their raw format, which is suitable for sorting but may not be the most useful formatting for display.  We might find a format like "Jan-13-2009 · Wed" more useful for display purposes, though it's useless for sorting on.

We could massage the data in PHP to alter the date format, but it would be much faster and more efficient to let the database server deal with that.  You'll also have cleaner PHP code if you deliver attributes from your database server ready to use.

Here's an example of a query that pulls all values (the asterisk) followed by additional formats of two dates.  Note that the additional formats are manipulations of data which have already been pulled in their raw format by the asterisk in the select statement.  Note also that I've adopted the convention of  prepending "fmt_" to these derived attributes.

1
2
3
4
5
SELECT
  *,
  DATE_FORMAT(date_received,'%Y-%b-%d · %a') AS fmt_date_received,
  DATE_FORMAT(date_dispatched,'%Y-%b-%d · %a') AS fmt_date_dispatched,
FROM packages

You're now free to use date_received and fmt_date_received independently throughout your code.

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;