简体   繁体   English

使用PHP在变量为空时更新SQL表字段

[英]Update a SQL table field when a variable is empty using PHP

I have a table, with columns _photo(string) and f1(int)(this is users sex). 我有一个表,列_photo(string)和f1(int)(这是用户性别)。

If _photo is empty I want to populate it with a string based on what column f1 contains. 如果_photo为空,我想根据f1列所包含的字符串来填充它。 I have this working fine for when a new user joins up, by doing this - 通过执行以下操作,我可以很好地处理新用户加入时的情况-

$sex = mysql_result(mysql_query("SELECT `f1` FROM `{$dbtable_prefix}user_profiles` WHERE `fk_user_id`='".$_SESSION[_LICENSE_KEY_]['user']['reg_id']."' "),0);

And then 接着

if ($sex =='1') {
            $no_photo = "no_photo_male.png";
        }
        if ($sex =='2') {
            $no_photo = "no_photo_female.png";
        }
        if ($sex =='3') {
            $no_photo = "no_photo_couple_ff.png";
        }
        if ($sex =='4') {
            $no_photo = "no_photo_couple_mm.png";
        }
        if ($sex =='5') {
            $no_photo = "no_photo_couple_mf.png";
        } 
        $insertphoto= "UPDATE dsb_user_profiles SET _photo = '$no_photo' Where `fk_user_id` = '".$_SESSION[_LICENSE_KEY_]['user']['reg_id']. "' "; // note the use of reg_id and not user_id
        if (!($res=@mysql_query($insertphoto))) {trigger_error(mysql_error(),E_USER_ERROR);}    

I am trying to make a script that I can run on the database to update all the records to assign the correct string to all the records where _photo is empty. 我试图制作一个可以在数据库上运行的脚本,以更新所有记录,以便为_photo为空的所有记录分配正确的字符串。 I am new to mysql and php and can't work out how to cycle through each record and check f1, run the code to set the no_photo variable than insert it into the _photo column. 我是mysql和php的新手,无法解决如何遍历每条记录并检查f1的问题,运行代码来设置no_photo变量,而不是将其插入_photo列。

Any help is greatly appreciated! 任何帮助是极大的赞赏! Thanks. 谢谢。

You could loop trough records like this: 您可以像这样循环记录低谷记录:

$userResult = mysql_query("SELECT `f1` FROM `{$dbtable_prefix}user_profiles` WHERE");

while($user = mysql_fetch_array($userResult)) {
   if($user['f1'] == '1'){
      $no_photo = "no_photo_male.png";
   }
   else if($user['f1'] == '2'){
      //more else ifs
   }
   //your update query
}

Please try below update query:- 请尝试以下更新查询:

UPDATE Table_Name 
SET _photo = 
CASE 
   WHEN f1 = '1' 
      THEN "no_photo_male.png"
   WHEN f1 = '2' 
    THEN "no_photo_female.png"
   WHEN f1 = '3' 
    THEN "no_photo_couple_ff.png"
   WHEN f1 = '4' 
    THEN "no_photo_couple_mm.png"
   WHEN f1 = '5' 
    THEN "no_photo_couple_mf.png"
   ELSE NULL 
END
WHERE _photo = ''

You can update the database directly w/o PHP using nested MySQL IF() statements: 您可以不使用PHP使用嵌套的MySQL IF()语句直接更新数据库:

UPDATE user_profiles 
SET _photo = IF(sex = 1, 'photo_1', IF(sex = 2, 'photo_2', IF(sex = 3, 'photo_3', IF(sex = 4, 'photo_4', NULL ) ) ) )
WHERE photo IS NULL;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM