Jump to content

[SOLVED] Combine and Optimize MYSQL UPDATE with PHP


mikenl

Recommended Posts

Hi,

 

I want to set all fields in a MySQL row to the default value (0) and update the row with new values.

 

I now use 2 queries and I'm curious if these can be combined and/or optimized?

 


// set prof_pref to 0

$setfetish0 = "UPDATE prof_pref SET ";

for ($N=1; $N<=12; $N++) 
    {     
$setpref0 = $setpref0 . "pref".$N." = '0'";
if($N != 12){
	$setpref0 = $setpref0 . ", ";
	} 
  } 	

$setpref0 = $setpref0 . " WHERE unid = '$session_id'";

mysql_query($setpref0 );


// update prof_pref 

$pref= $_POST[pref];

dbsystem();	
$setpref= "UPDATE prof_pref SET ";	

foreach ($pref as $pre=> $value){
if(!empty($pre)){
	$setpref= $setpref. ", ";
	}  
$setpref= $setpref. "pref".$value." = '1'";
 }

$setpref= $setpref. " WHERE unid = '$session_id'";

mysql_query($setpref);

Link to comment
Share on other sites

if you are pertaining to the same info and update them consecutively, i dont think its a good idea since you are going to update the same fields. why not go directly to the second update instead? or do you have other special implication.

 

sorry but i dont really see any good reason for doing such.

Link to comment
Share on other sites

I want to set them to default first as I receive only the selected checkboxes (as '1') and pass them on to the db.

 

The previous selection must be erased (filled with '0's) otherwise the db will fill up with '1's...

Link to comment
Share on other sites

OK, messed around with the query, and this is now working:

 

dbsystem();	
$setlanguage = "UPDATE prof_language SET ";	

foreach ($language as $lang => $value){
if(!empty($language)){
	$setlanguage = $setlanguage. ", ";
	}  
$setlanguage = $setlanguage. "lang".$value." = '$lang'";
 }

$setlanguage = $setlanguage. " WHERE unid = '$session_id'";

mysql_query($setlanguage);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.