GlobalWarming Awareness2007

Manage options using PHP and MySQL

I have made this site just to partecipate to the SEO World Championship and I've written just few lines of code to menage it.

A thing that I consider very useful is to save and to get options easily in the several parts of my PHP scripts.

To do this I've created an options table and two functions, one to insert/update options and one to get them.

This is the MySQL table:

CREATE TABLE `options` (
  `name` varchar(80) NOT NULL,
  `value` text NOT NULL,
  PRIMARY KEY (`name`)
) DEFAULT CHARSET=utf8;

To insert or to update options I use this function:

function save_option($name, $value){
	$value = serialize($value);
	$sql = mysql_query("INSERT INTO options VALUES('$name', '$value') ON duplicate KEY UPDATE value = '$value'");
}

The PHP function serialize() generates a storable representation of a value.

The MySQL query I have used is explained in the article INSERT ON DUPLICATE KEY UPDATE on the MySQL Performance Blog.

The string generated using serialize() is inserted or updated in the database, and we can take it and reobtain a PHP value using unserialize():

function get_option($name){
	$get = mysql_query("SELECT value FROM options WHERE name = '$name' LIMIT 1");
	if($r = mysql_fetch_row($get))
		return unserialize($r[0]);
}

Final test:

<?php
$array = array(1, 2, 3);
save_option('test-option', $array);

$array = get_option('test-option');
$array[] = 4;

save_option('test-option', $array);

print_r(get_option('test-option'));
?>

I hope the output will be:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Technorati tags:

My Awareness2007 - Index:

SEO Contest

GlobalWarming Awareness2007:

GlobalWarming Awareness2007