dongshie8450 2015-04-13 17:54
浏览 45
已采纳

如何更新mysql中的文本字段

in my wordpress blog i have a table consist of users and their products seperated by ";" for example :

       mytable
----------------------
userid  | products
----------------------
   1    | camera
   2    | books;keyboard;computer
   3    | mouse;printer
   4    | scanner

now in my script the user will add a new product so i need to check if that user has more than 3 products because in this case i will do nothing and will not add this product for him but if he has less than 3 products i need to add the new product to his products seperated by ";" something like :

$userid = 3;
$newproduct = "ball"


if (pruduct field for that user has more than 2 ";" ) {

   do nothing

 }else{


$wpdb->update( 
'mytable', 
array( 'product' => concat(product, ";", $newproduct)), 
array( 'userid ' => $userid ), 
array( '%s' ), 
array( '%d' ) 
);

so the result in this example would be :

       mytable
----------------------
userid  | products
----------------------
   1    | camera
   2    | books;keyboard;computer
   3    | mouse;printer;ball
   4    | scanner
  • 写回答

2条回答 默认 最新

  • dsy1971 2015-04-13 18:22
    关注

    Despite the data normalization arguments, which are incredibly valid, if for some reason you cannot correct that and must work with what exists.

    Select the products column as a string and use the PHP explode() and implode() functions. You'd end up with something like this:

    $current_products = explode(';', $user['products']);
    // $current_products is now an array of the user's products.
    if !(count($current_products) >= 3) {
        $current_products[] = $new_product;
    }
    $user_products = implode(';', $current_products);
    // Insert $user_products into your table via UPDATE
    

    The implode and explode functions convert strings to and from arrays based on given delimiters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)