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 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计