Works fine, but I need some advice with PHP/MySQL

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
pgolovko
Forum Commoner
Posts: 38
Joined: Sun Sep 17, 2006 9:13 am

Works fine, but I need some advice with PHP/MySQL

Post by pgolovko »

The following code saves my settings. The problem is I have hundreds of settings to be saved, and I was looking for a shorter, more logical way of writing this code:

Code: Select all

if(isset($save)){
	mysql_query("UPDATE `config` SET `title` = '$title', `admin` = '$admin', `email` = '$email' LIMIT 1");
	echo mysql_error();
	print "Settings saved!<p>";
	}
Someone suggested me use of array, but I'm not sure how to do it, and if it is a solution at all.

Thanks in advance.
GM
Forum Contributor
Posts: 365
Joined: Wed Apr 26, 2006 4:19 am
Location: Italy

Post by GM »

Maybe if your settings don't change often you could keep them in a .ini file and read them into your script from there? If you prefer to keep them in a table, then you might be able to shorten the amount of typing you do by doing something like this:

Code: Select all

// put your settings into a $settings array with key = column name and value = column value

$update_string = "UPDATE config SET ";

//loop through the $settings array and add them to the update string:
foreach($settings as $col_name => $col_value) {
    $update_string .= "$col_name='$col_value', ";
}

//remove the trailing ", " from the $update_string
$update_string = rtrim($update_string, ", ");

//add WHERE part:
$update_string .= " WHERE blah blah lbha lhbal";

//execute query held in $update_string
(This is not tested)
ody
Forum Contributor
Posts: 147
Joined: Sat Mar 27, 2004 4:42 am
Location: ManchesterUK

Post by ody »

Your best bet is probably something like this:

Code: Select all

$settings = array(
'title' => 'test',
'admin' => FALSE,
'email' => 'someone@somehost.com'
);

function saveSettings($userid, $settings=array())
{
  mysql_query("update users set settings = '".mysql_escape_string(serialize($settings))."' where userid = '".$id."'");
}

function getSetting($userid, $setting)
{
 $result = mysql_query("select settings from users where userid = '".$userid."'");
 if(mysql_num_rows($result) == 1)
 {
   $row = mysql_fetch_array($result);
   $settings = unserialize($row[0]).
   return $settings[$setting];
 }
 else
 {
   return FALSE;
 }
}
It's un-tested and un-finished but it should give you the idea.
Post Reply