Hi,
I've been lurking this sub-forum for some time as I started learning PHP a few months ago and use a fair amount of SQL in my job.
Anyway, I was trying to put together a function in PHP that would allow me to update a user's (or groups of users') info without having to decide in advance of using the function what fields I wanted to match or what fields I wanted to update.
I managed to put together a function that does what I needed it to, but it feels kind of hacky and inelegant.
Here's a version of the function that would only take 3 variables:
Code:
function update_user_info($userid=NULL,$email=NULL,$username=NULL)
{
$update_array = array();
$i = 0;
$j = 0;
if( $userid != NULL )
{
$update_array['userid'] = $userid[0];
if("where"==$userid[1])
{
$update_array['where'][$i++] = 'userid';
}
else
{
$update_array['set'][$j++] = 'userid';
}
}
if( $email != NULL )
{
$update_array['email'] = "'".$email[0]."'";
if("where"==$email[1])
{
$update_array['where'][$i++] = 'email';
}
else
{
$update_array['set'][$j++] = 'email';
}
}
if( $username != NULL )
{
$update_array['username'] = "'".$username[0]."'";
if("where"==$username[1])
{
$update_array['where'][$i++] = 'username';
}
else
{
$update_array['set'][$j++] = 'username';
}
}
$set = "";
$where = "";
if(isset($update_array['set'][0]))
{
foreach($update_array['set'] as $value)
{
$set .= "`" . $value . "` = " .$update_array[$value] . ", ";
}
}
if(isset($update_array['where'][0]))
{
foreach($update_array['where'] as $value)
{
$where .= "`" . $value . "` = " .$update_array[$value] . " AND ";
}
}
$set = substr($set,0,-2);
$where = substr($where,0,-5);
if($userid[0] == $userinfo['userid'] || isset($userinfo['admin_priv']))
{
$query = "UPDATE users SET " . $set . " WHERE " . $where;
$result = mysql_query($query);
$affected = mysql_affected_rows();
}
else return "Incorrect privileges";
}
So, if I wanted to update the username of a single user, and I knew his userid, I would call the function with:
Code:
$userid = array(5,'where');
$username = array('username','set');
update_user_info($userid,NULL,$username);
If I wanted to update the email of someone who I knew their username, I would:
Code:
$email = array('test@example.com','set');
$username = array('username','where');
update_user_info(NULL,$email,$username);
Like I said, it appears to work correctly for all the cases, I've tested so far, but it seems off to me (partially because it's so long), and I'm not experienced enough at programming yet to know why that might be.
Thanks for any help or insight anyone can give.