Archive for September, 2011

AVG function returns 0.9999

This one is a very odd bug! 😐

For some reason, the AVG function from MySQL is always returning the value 0.9999 instead of the average value. This has been experienced on MySQL 5.5.12 hosted on Amazon RDS (Relational Database Service).
However, the exact same query executed on MySQL 5.1.28 is returning the right values.

Why is that? Is it a bug in MySQL 5.5.12?
I did a search on internet and I couldn’t find anything about it. So to be honest, I am not sure what is this bug or even if MySQL is aware of it.

Anyway, if you encounter the same problem, you can simply replace the AVG function by the combination SUM/COUNT.
For example, the following query:

SELECT student_name, AVG(test_score)
FROM student
GROUP BY student_name;

can be replaced by the one below:

SELECT student_name, SUM(test_score)/COUNT(test_score)
FROM student
GROUP BY student_name;

, , , ,


Send email attachment with PHP

Everybody probably knows how to send an email using PHP, but do you know how to send an email with an attachment?

This is actually not very difficult and you can find examples all over the web. However, it seems that all the examples I found didn’t work! 🙁
But after some debugging and testing, I finally got a working solution. 😀

Please see below the code with comments:

// Define some variables
$to = ''
$subject = 'Test email';
// Create a boundary string. It must be unique so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));

// Define the headers
$headers = "From:\r\n";
// Add boundary string and mime type specification
$headers .= "Content-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

// Read the attachment file contents into a string, encode it with MIME base64, and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('')));

// Define the body of the message
$message = "
Content-Type: text/plain; charset='iso-8859-1'

This is a test email message sent with PHP.

Content-Type: application/zip;
Content-Transfer-Encoding: base64
Content-Disposition: attachment


// Send the email
if (@mail($to, $subject, $message, $headers)) {
	echo "The mail has been sent.";
} else {
	echo "The mail has NOT been sent!";

, ,