Thursday, August 25, 2005

PHP/MySQL List By Alphabet


This simple tutorials will show you how to create a alphabet index to grabs data from a mysql database.
Let's go on...




1. The alphabet index - how to create a cool one?



The first thing is list character from a to
z. How to do this? In a I've read, the author did it by doing a loop like

for ($i=$start ;$i<=$end; $i++);

Where $start and $end is the ASCII code of a
and z. However, It's sometimes quite hard to remember this value. Actually, I
cannot at the moment ;) So I solve the problem like this:

$list[]='0-9';
for ($ch=ord('a');$ch<=ord('z');$ch++)
{
$list[]=chr($ch);
}

Now that we have the list for the index. The next step is
simple. You will define the number of items per row, for example:

define('num_per_row','6');

The open a table, lop through the character set.
Check if an item is the first cell -> open the row, or the last cell -> close a
row:

$num_rows=count($list);
define ("TB_COLOR_LIGHT","#EEF7FA");
define ("TB_COLOR_DARK","#DBE9EF");
$width=(100/num_per_row).'%';
echo '<table bgcolor="'.TB_COLOR_DARK.'" width="100%">';
for ($i=0;$i<$num_rows;$i++)
{
if (0==$i%num_per_row)
{
echo '<tr align="center" valign="middle">'; // open the row
}
$url=append_sid('your_result_page&type=abc&keys='.$list[$i]);
echo '<td bgcolor="'.TB_COLOR_LIGHT.'" height="20" width="'.$width.'" nowrap>';
if (is_song_abc($list[$i])) // show only necessary items, see bellow
{
echo'<a href="'.$url.'"><b>'.$list[$i].'</b></a></td>';
}
else
{
echo $list[$i];
}
echo '</td>';
if ((num_per_row-1)==$i%num_per_row) // close the row
{
echo '</tr>';
}
}
echo '</table>';


2. The search code

The function is_abc($item) is to check if there is result which begin
with that item, for example, we search song_name from table TB_SONGS

function is_song_abc($keywords)
{
$where="song_name REGEXP '^[$keywords]'";
$sql ='SELECT count(*) as total
FROM '.TB_SONGS."
WHERE $where";
$result = sql_query($sql);
return mysql_result($result,'total');
}

The search code is totally similiar, you can
select what ever you want from the database with the WHERE condition is:

$where="song_name REGEXP '^[$keywords]'";


3. Conclusion

This tutorial is simple, yet useful to who new to mysql database search. In the next article, I intend to discuss more about mysql database search problem and some solution.

Monday, August 22, 2005

More on File Upload Handle In PHP

Some problem with PHP file upload handle:
Make sure the file size not exceed desired value
allow certain fype type: to prevent user upload harmful content.
In my current project. I have to solve it all. In this artice, I will share you some of the trick. If you like to know more, feel free to ask question by commenting.

Make a Upload function:

////////////////////
function upload_file($user_file,
$dest_dir,
$max_file_size,
$to_file_name='')
{

$file_name=(empty($to_file_name))
? $_FILES[$user_file]['name']
: $to_file_name;
$file_size=$_FILES[$user_file]['size'];
$temp_file=$_FILES[$user_file]['tmp_name'];
$upload_file="$dest_dir/$file_name";
$err='';
if ($_FILES[$user_file]['error'])
{
$err=upload_error_message(
$_FILES[$user_file]['error']
);
message_warning($err);
return false;
}
echo "
Uploading file $file_name...";
if (DEBUG)
{
echo "to $upload_file";
}
if (is_uploaded_file($temp_file))
{ //check size
if ($file_size>$max_file_size)
{
message_warning("
File size too large: $file_size
");
unlink($temp_file);
return false;
}
if (file_exists($upload_file))
{
message_warning('File Existed');
unlink($temp_file);
return false;
}
if (move_uploaded_file($temp_file,$upload_file))
{
echo "
File uploaded: $file_name!";
return true;
}
else
{
message_warning('Cannot copy file!');
return false;
}
}
else
{
message_warning('Upload Failed!');
return false;
}
}



Upload form valiate:

function validate_upload_form($update=false)
{
global $file_name;
global $tempfile;
global $err_file;

$ok=true;
if (empty($file_name))
{
$err_songfile='
No file specified!';
$ok=false;
}
else
{
$ext=get_ext($file_name);
if (!is_ext_allowed($ext))
{
$err_file='
Exentions not allow';
$ok=false;
}

}

if ( (!$ok)&&amp;(!empty($tempfile)) )
{
delete_file($tempfile);
}
return $ok;
}



Get File extension:


function get_ext($filename)
{
if (!empty($filename))
{
$pathinfo=pathinfo($filename);
return $pathinfo['extension'];
}
else
{
return 'Unkown';
}
}



Is an extension allow?


//
define ("EXT_ALLOWED",'mp3,wma,rm,mov,mid,swf,wmv');
function is_ext_allowed($ext)
{
$EXT_ALLOWED=explode(',',EXT_ALLOWED);
return in_array(strtolower($ext),$EXT_ALLOWED);
}



Upload error message:


function upload_error_message($err_code)
{
switch ($err_code)
{
case UPLOAD_ERR_OK:
return 'No error';
case UPLOAD_ERR_INI_SIZE:
$max_size=return_bytes(
ini_get('upload_max_filesize')
);
return 'The uploaded file exceeds
the upload_max_filesize directive
in php.ini: '.$max_size.' bytes';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds
the MAX_FILE_SIZE directive that
was specified in the HTML form.';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file
was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
default:
return 'Unkown error';
}
}



Upload Processing...


switch ($_action)
{
case 'upload':
if(validate_upload_form())
{
upload_processing();
}
else
{
show_upload_form();
}
break;
default:
show_upload_form();
break;

Saturday, August 20, 2005

File Upload Handle In PHP: Some tricky functions

I try to say few words here. I Just want to show some problem and Ideas on File Upload Hanlde in PHP and some samples – asap (as simple as possible):
Upload Limit Size There are 3 kind of limits:



  • Limit Specified in HTML code
  • Limit specified by you-PHP program
  • Limit specified of upload_max_filesize in PHP Configuration Directives.
The Limit by HTML form is useful to fast check upload file. But this can be trick if someone modifies the value in HTML code. So it's better recheck the value in PHP.
But in some cases, the value you specified exceeds the value upload_max_filesize.
The question is how to check this value?
You can use the following functions:


function return_bytes($val)
{
$val = trim($val);
$last = strtolower($val{strlen($val)-1});
switch($last)

{
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}


function upload_max_filesize()
{
return return_bytes(ini_get(\'upload_max_filesize\'));
}



Friday, August 19, 2005

PHP Users authorization - some ideas?

User management is always a problem with web developers. You can see everywhere, that a visitor must sign up for several times in order to use different service in one website. That is boring and makes a lot of people run away. If you are the one who create a full website for yourself, I think you will unite the user management. That is true for some famous open source like php-nuke, xoops.
Basically, the user management involves 2 database tables, say, tb_users and tb_groups. tb_users contains user_id, user_name, user_password, group_id and other information.
tb_groups contains group_id, group_name and some authority like: auth_view, auth_post, auth_upload,...
Whenever a user is logged and try to use a service, the php code will check the database to see if he have right or not.
The following is a proposal function to it conveniently

function check_auth($user_id,$auth)
////For example check_auth('upload')
{
global $_CONNECTION;
$group_id=get_group($user_id);
$field="auth_$auth";
$sql="SELECT $field
FROM ".TB_GROUPS."
WHERE group_id=$group_id";
if ($result=mysql_query($sql,$_CONNECTION))
{
if (mysql_num_rows($result))
{
return mysql_result($result,0,$field);
}
else
{
return 0;
}
}
else
{
return 0;
}
}//end function



If you have other ideas, please share ;)

Thursday, August 18, 2005

About Apress Contest and PHP Fractal Generator


Apress has announced a Programming Contest on mandelbrot Fractal Generation.
There are there proramming groups:
  • C++, C
  • Perl, PHP, Python, Common Lisp
  • Java, C#, VB.NET
The fastest program in each group will win a SONY Playstation, the second will win a iPod Shuffle.
I feel excited because one can use PHP to do it. Since I am not used to C++, I choose PHP and start coding.
The result was quite dissapointed. For an image of 320x200, with number of itterations is 200, it take > 20 second. (!) The same code written in C++ has much larger speed, though I cannot calculate exact number. I tried to optimized a lot, and the speed may increase nearly two times, but still too slow. I wonder what wrong with PHP loop and not sure about the performance of other languge in the group (perl, phython,...)
At last, I submit the program althogh I can optimize it a litle more. Anyway, as the rule, I will expose the code after the contest finish.
If anyone interested, you can still apply, since the deadline is August 31.
Go to the website for more information

Tuesday, August 16, 2005

How to add the RSS feed to your Blogs/Site?

You have little time to update your site/blogs frequently?
You want to read latest news from a reliable source?
One of the solution is the rss feed.

This is the simple tutorials of how to add rss feed to your blogs.

  • The first step is to get the rss source. You can find anywhere. For example, you can go to google and type few keywords then search. In this tutorials, you can go to news.yahoo.com, type the keywords you want and see the result. On the bottom-right corner, you'll see a RSS icon. Right click, copy shortcut.
  • Then go to http://jade.mcli.dist.maricopa.edu/feed/index.php?s=build and paste the link into rss feed box. Choose some options and click preview to fit your needs.
  • Once you satisfied, click generate JavaScript code. Copy the code and past into you page/blog template.
  • Preview and Republish if you like,

Enjoy,

Starting Blogs - Continuing the Hobbies

echo 'Hello the world';
I am a big fan of PHP. Or should I say PHP is one if my biggest hobbies, although the number of my hobbies is numerous. So, like the big fan of anything, one should have a lot of ideas around the objects. I intended to make a whole website for it. But it still in the plan.

A friend of mine told me that I should use a blog to keep track of myself, or to share my ideas.
I agree, "An unrecorded idea is an idea that often lost" - Zig Ziglar
So I set up this. The purpose is clear: to keep track of myself, share the ideas, practice my writing, etc.