Page 1 of 1
Works fine, but I need some advice with PHP/MySQL
Posted: Mon Sep 18, 2006 2:12 am
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.
Posted: Mon Sep 18, 2006 3:00 am
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)
Posted: Mon Sep 18, 2006 10:07 am
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.