<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Stuporglue.org &#187; mysql</title>
	<atom:link href="http://stuporglue.org/tag/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://stuporglue.org</link>
	<description>Programming, Rambling and More!</description>
	<lastBuildDate>Tue, 24 Jan 2012 04:18:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Update Multiple Rows At Once With Different Values in MySQL</title>
		<link>http://stuporglue.org/update-multiple-rows-at-once-with-different-values-in-mysql/</link>
		<comments>http://stuporglue.org/update-multiple-rows-at-once-with-different-values-in-mysql/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 14:07:02 +0000</pubDate>
		<dc:creator>stuporglue</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[case statement]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[MySQL CASE]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[update query]]></category>

		<guid isPermaLink="false">http://stuporglue.org/?p=478</guid>
		<description><![CDATA[I&#8217;ve had to figure this out on my own twice now, so I guess it&#8217;s time to document it. It is possible, and fairly easy, to update multiple rows of a MySQL table at the same time, with different values &#8230; <a href="http://stuporglue.org/update-multiple-rows-at-once-with-different-values-in-mysql/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve had to figure this out on my own twice now, so I guess it&#8217;s time to document it. It is possible, and fairly easy, to update multiple rows of a MySQL table at the same time, with different values for each row. Unfortunately it&#8217;s not as easy as inserting, but once you see what&#8217;s being done you will probably say &#8220;Oh, of course!&#8221;.</p>
<p>The key to the multiple row update query is the CASE statement.  <a title="MySQL CASE" href="http://dev.mysql.com/doc/refman/5.0/en/case-statement.html" target="_blank">MySQL&#8217;s CASE reference page</a> doesn&#8217;t even have the word &#8220;UPDATE&#8221; on the page anywhere, but don&#8217;t let that fool you, it can be used in UPDATE statements!</p>
<p>The resultant query, to all of you holding your breath, will look something like this:</p>
<pre>UPDATE `table` SET

`column1` = CASE
WHEN `id`='1034786' THEN '0'
WHEN `id`='1037099' THEN '0'
WHEN `id`='1034789' THEN '3'
ELSE `sequence` END,

`column2` = CASE
WHEN `id`='1034786' THEN NULL
WHEN `id`='1037099' THEN '1034789'
WHEN `id`='1034789' THEN '1034789'
ELSE `parent_section_id` END,

`column3` = CASE
WHEN `id`='1034786' THEN 'Text One'
WHEN `id`='1037099' THEN 'Text Two'
WHEN `id`='1034789' THEN 'Text Three'
ELSE `title` END

WHERE `id`='1034786' OR `id`='1037099' OR `id`='1034789'
</pre>
<p>As you can see, for each column to be update we create a CASE statement which updates the column based on a unique ID. As I said, it&#8217;s not as easy as inserting, but if you have ever seen a case or switch statement while programming it should be straight forward. The ELSE case will let us keep the original value if we don&#8217;t explicitly provide one. The WHERE will limit our updates to the rows we are trying to update.</p>
<p>Now, for a little untested PHP code similar to something I&#8217;ve been working on:</p>
<pre>// Update values we got from somewhere
$update_values = Array(
  '1034786' =&gt; Array('column1' =&gt; 0, 'column2' =&gt; NULL, 'column3'=&gt; 'Text One'),
  '1037099' =&gt; Array('column1' =&gt; 0, 'column2' =&gt; 1034789 , 'column3'=&gt; 'Text Two'),
  '1034789' =&gt; Array('column1' =&gt; 3, 'column2' =&gt; 1034789 , 'column3'=&gt; 'Text Three')
);

// Start of the query
$update_query = "UPDATE `table` SET ";

// Columns we will be updating
$columns = Array('column1' =&gt; '`column1` = CASE ', 'column2' =&gt; '`column2` = CASE ', 'column3' =&gt; '`column3` = CASE ');

// Build up each columns CASE statement
foreach($update_values as $id =&gt; $values){
  $columns['column1'] .= "WHEN `id`='" . mysql_real_escape_string($id) . "' THEN '" . mysql_real_escape_string($values['column1']) . "' ";
  $columns['column2'] .= "WHEN `id`='" . mysql_real_escape_string($id) . "' THEN "  . ($values['column2'] === NULL ? "NULL" : "'".mysql_real_escape_string($values['column1'])."'") . " ";
  $columns['column3'] .= "WHEN `id`='" . mysql_real_escape_string($id) . "' THEN '" . mysql_real_escape_string($values['column3']) . "' ";
}

// Add a default case, here we are going to use whatever value was already in the field
foreach($columns as $column_name =&gt; $query_part){
  $columns[$column_name] .= " ELSE `$column_name` END ";
}

// Build the WHERE part. Since we keyed our update_values off the database keys, this is pretty easy
$where = " WHERE `id`='" . implode("' OR `id`='", array_keys($update_values)) . "'";

// Join the statements with commas, then run the query
$update_query .= implode(', ',$columns) . $where;
mysql_query($update_query) or die(mysql_error());
</pre>
<p>That aught to be enough to either get you started, or get you in trouble.</p>
<p>As always, make a backup of your database or use a test database when testing UPDATE queries.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://stuporglue.org/update-multiple-rows-at-once-with-different-values-in-mysql/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Recieve E-mail and Save Attachments with a PHP script</title>
		<link>http://stuporglue.org/recieve-e-mail-and-save-attachments-with-a-php-script/</link>
		<comments>http://stuporglue.org/recieve-e-mail-and-save-attachments-with-a-php-script/#comments</comments>
		<pubDate>Thu, 25 Mar 2010 02:41:09 +0000</pubDate>
		<dc:creator>stuporglue</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[attachments]]></category>
		<category><![CDATA[base64_decode]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[uudecode]]></category>

		<guid isPermaLink="false">http://stuporglue.org/?p=369</guid>
		<description><![CDATA[Here&#8217;s something fun! If you can tell your server to send e-mail to a script, you can send e-mails to PHP. Once you are processing the e-mail with PHP you can save attachments, automatically respond to the e-mail, save it &#8230; <a href="http://stuporglue.org/recieve-e-mail-and-save-attachments-with-a-php-script/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s something fun! If you can tell your server to send e-mail to a script, you can send e-mails to PHP. Once you are processing the e-mail with PHP you can save attachments, automatically respond to the e-mail, save it to a database, make a webpage from it&#8230;really whatever you want!</p>
<p>Here&#8217;s a script I am currently using. My brother is on a mission for <a href="http://mormon.org/" target="_blank">our Church</a>, in Peru for two years and has near weekly e-mail access but can&#8217;t do much more than e-mail. He wanted a way to easily send photos to the server via e-mail; this script is the results of his wishes.</p>
<h2>E-mail Processing Script Features:</h2>
<ol>
<li>Saves the e-mail sender, subject and body to a database</li>
<li>Saves any attachments as files and creates an entry for those files in the database, associated with the e-mail info in #1</li>
<li>Sends  a response back to the sender telling them what files were received and their file sizes</li>
<li>Checks a list of allowed senders to make sure we only take files from specified addresses.</li>
</ol>
<h2>Database Setup:</h2>
<p>If you&#8217;re going to use the database features, you&#8217;ll need a database. Here&#8217;s the SQL to create an identical setup to the one I have:</p>
<pre>-- Here's my DB structure

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
-- Table structure for table `emails`

CREATE TABLE IF NOT EXISTS `emails` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `from` varchar(250) NOT NULL,
  `subject` text NOT NULL,
  `body` text NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

-- --------------------------------------------------------
-- Table structure for table `files`

CREATE TABLE IF NOT EXISTS `files` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `email_id` int(100) NOT NULL,
  `filename` varchar(255) NOT NULL,
  `size` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;
</pre>
<p>Pretty straightforward I would say. The size field in the files table stores a user friendly &#8220;100Mb&#8221; type description of the size. You will need to know your database name, username, password and host name in the next step.</p>
<h2>The Email Handling Script:</h2>
<p>The max_time_limit variable is how long you want the script to be allowed to run. The default max for your server might be too small to handle 20Mb of attachments (the max you can send with Google).</p>
<pre>#!/usr/bin/php -q
&lt;?php
//  Use -q so that php doesn't print out the HTTP headers
//  Anything printed to STDOUT will be sent back to the sender as an error!

//  Config options

$max_time_limit = 600; // in seconds
// A safe place for files with trailing slash (malicious users could upload a php or executable file!)
$save_directory = "/some/folder/path";
$allowedSenders = Array('myemail@gmail.com',
    'Bob the Builder &lt;whatever@whoever.com&gt;'); // only people you trust!

$send_email = TRUE; // Send confirmation e-mail?
$save_msg_to_db = TRUE; // Save e-mail body to DB?

$db_host = 'localhost';
$db_un = 'stuporgl_stuporg';
$db_pass = 'c41p1r4p0r4';
$db_name = 'stuporgl_org';

// ------------------------------------------------------

set_time_limit($max_time_limit);
ini_set('max_execution_time',$max_time_limit);

global $from, $subject, $boundary, $message, $save_path,$files_uploaded;
$save_path = $save_directory;
$files_uploaded = Array();

function formatBytes(&amp;$bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');

    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);

    $bytes /= pow(1024, $pow);

    return round($bytes, $precision) . ' ' . $units[$pow];
} 

function process_part(&amp;$email_part){
    global $message;

    // Max two parts. The data could have more than one \n\n in it somewhere,
    // but the first \n\n should be after the content info block
    $parts = explode("\n\n",$email_part,2);

    $info = split("\n",$parts[0]);
    $type;
    $name;
    $encoding;
    foreach($info as $line){
	if(preg_match("/Content-Type: (.*);/",$line,$matches)){
	    $type = $matches[1];
	}
	if(preg_match("/Content-Disposition: attachment; filename=\"(.*)\"/",
	    $line,$matches)){
	    $name = time() . "_" . $matches[1];
	}
	if(preg_match("/Content-Transfer-Encoding: (.*)/",$line,$matches)){
	    $encoding = $matches[1];
	}
    }

    // We don't know what it is, so we don't know how to process it
    if(!isset($type)){ return FALSE; }

    switch($type){
    case 'text/plain':
	// "But if you get a text attachment, you're going to overwrite
	// the real message!" Yes. I don't care in this case...
	$message = $parts[1];
	break;
    case 'multipart/alternative':
	// Multipart comes where the client sends the data in two formats so
	// that recipients who can't read (or don't like) fancy content
	// have another way to read it. Eg. When sending an html formatted
	// message, they will also send a plain text message
	process_multipart($info,$parts[1]);
	break;
    default:
	if(isset($name)){ // the main message will not have a file name...
	    // text/html messages won't be saved!
	    process_data($name,$encoding,$parts[1]);
	}elseif(!isset($message) &amp;&amp; strpos($type,'text') !== FALSE){
	    $message = $parts[1]; // Going out on a limb here...capture
	    // the message
	}
	break;
    }
}

function process_multipart(&amp;$info,&amp;$data){
    global $message;

    $bounds;
    foreach($info as $line){
	if (preg_match("/boundary=(.*)$/",$line,$matches)){
	    $bounds = $matches[1];
	}
    }

    $multi_parts = split("--" .$bounds,$data);
    for($i = 1;$i &lt; count($multi_parts);$i++){
	process_part($multi_parts[$i]);
    }
}

function process_data(&amp;$name,&amp;$encoding = 'base64' ,&amp;$data){
    global $save_path,$files_uploaded;

    // find a filename that's not in use. There's a race condition
    // here which should be handled with flock or something instead
    // of just checking for a free filename

    $unlocked_and_unique = FALSE;
    while(!$unlocked_and_unique){
	// Find unique
	$name = time() . "_" . $name;
	while(file_exists($save_path . $name)) {
	    $name = time() . "_" . $name;
	}

	// Attempt to lock
	$outfile = fopen($save_path.$name,'w');
	if(flock($outfile,LOCK_EX)){
	    $unlocked_and_unique = TRUE;
	}else{
	    flock($outfile,LOCK_UN);
	    fclose($outfile);
	}
    }

    if($encoding == 'base64'){
	fwrite($outfile,base64_decode($data));
    }elseif($encoding == 'uuencode'){
	// I haven't actually seen this in an e-mail, but older clients may
	// still use it...not 100% sure that this will work correctly as is
	fwrite($outfile,convert_uudecode($data));
    }
    flock($outfile,LOCK_UN);
    fclose($outfile);

    // This is for readability for the return e-mail and in the DB
    $files_uploaded[$name] = formatBytes(filesize($save_path.$name));
}

// Process the e-mail from stdin
$fd = fopen('php://stdin','r');
$email = '';
while(!feof($fd)){ $email .= fread($fd,1024); }

// Headers hsould go till the first \n\n. Grab everything before that, then
// split on \n and process each line
$headers = split("\n",array_shift(explode("\n\n",$email,2)));
foreach($headers as $line){
    // The only 3 headers we care about...
    if (preg_match("/^Subject: (.*)/", $line, $matches)) {
	$subject = $matches[1];
    }
    if (preg_match("/^From: (.*)/", $line, $matches)) {
	$from = $matches[1];
    }
    if (preg_match("/boundary=(.*)$/",$line,$matches)){
	$boundary = $matches[1];
    }
}

// Check $from here and exit if it's blank or
// not someone you want to get mail from!
if(!in_array($from,$allowedSenders)){
    die("Not an allowed sender");
}

// No boundary was in the e-mail sent to us. We don't know what to do!
if(!isset($boundary)){
    die("I couldn't find an e-mail boundary. Maybe this isn't an e-mail");
}

// Split the e-mail on the found boundary
// The first part will be the header (hence $i = 1 in our loop)
// Each other chunk should have some info on the chunk,
// then \n\n then the chunk data
// Process each chunk
$email_parts = split("--" . $boundary,$email);
for($i = 1;$i &lt; count($email_parts);$i++){
    process_part($email_parts[$i]);
}

// Put the results in the database if needed
if($save_msg_to_db){
    mysql_connect($db_host,$db_un,$db_pass);
    mysql_select_db($db_name);

    $q = "INSERT INTO `emails` (`from`,`subject`,`body`) VALUES ('" .
	mysql_real_escape_string($from) . "','" .
	mysql_real_escape_string($subject) . "','" .
	mysql_real_escape_string($message) . "')";

    mysql_query($q) or die(mysql_error());

    if(count($files_uploaded) &gt; 0){
	$id = mysql_insert_id();
	$q = "INSERT INTO `files` (`email_id`,`filename`,`size`) VALUES ";
	$filesar = Array();
	foreach($files_uploaded as $f =&gt; $s){
	    $filesar[] = "('$id','" .
		mysql_real_escape_string($f) . "','" .
		mysql_real_escape_string($s) . "')";
	}
	$q .= implode(', ',$filesar);
	mysql_query($q) or die(mysql_error());
    }
}

// Send response e-mail if needed
if($send_email &amp;&amp; $from != ""){
    $to = $from;
    $newmsg = "Thanks! I just uploaded the following ";
    $newmsg .= "files to your storage:\n\n";
    $newmsg .= "Filename -- Size\n";
    foreach($files_uploaded as $f =&gt; $s){
	$newmsg .= "$f -- $s\n";
    }
    $newmsg .= "\nI hope everything looks right. If not,";
    $newmsg .=  "please send me an e-mail!\n";

    mail($to,$subject,$newmsg);
}
</pre>
<h2>Testing The Script:</h2>
<p>Save an e-mail, headers and all, and upload it to your server. Cat the saved e-mail to your script to test it.</p>
<pre>cat 'saved_email.txt' | ./process_email.php
</pre>
<p>You should get an e-mail response, see new entries in your DB and see your saved attachments. If you don&#8217;t, you can print debugging statements or use your usual PHP debugging techniques with this easy testing method.</p>
<h2>Security:</h2>
<p>Don&#8217;t let anonymous people upload files to your server without appropriate precautions! If someone uploaded a PHP file they could run it and easily gain access to your server that way. Protect the upload destination directory and limit who can send e-mail to this script.  There are probably a bunch of glaring security holes in this script. In my limited use situation where only two people knows the only address that can send e-mail to this script and the address to send it to, and where only I have access to the uploaded files (outside of the server root!) I&#8217;m comfortable with the level of security. For your situation, you might need to be more cautious.</p>
<h2>EDIT: Sending Email to the Script</h2>
<p>Initially I didn&#8217;t have any instructions on how to forward email to the script you just made. I have now posted those instructions here: <a href="http://stuporglue.org/add-an-email-address-that-forwards-to-a-script/" target="_self">Add an Email Address That Forwards to a Script</a>. It has instructions for CPanel and a link for Exim, Sendmail and Qmail users.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://stuporglue.org/recieve-e-mail-and-save-attachments-with-a-php-script/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
	</channel>
</rss>

