doudinghan8319 2016-03-02 21:11
浏览 42
已采纳

str_replace与变量生成的字符串不能与PHP一起使用

I am sure this has something to do with using variables to populate a string, but I am not sure how to fix the problem.

I have a sql statement that gets populated through variable which may or may not contain data which is why I have to do it this way.

Example

if ($data1 != '') {
    $col1 = "col1 = '".$data1."', "
}
if ($data2 != '') {
    $col2 = "col2 = '".$data2."', "
}
if ($data3 != '') {
    $col3 = "col3 = '".$data3."', "
}

Not every $data may contain something so some variables will be empty and not part of my SQL statement, but lets assume all three have data.

$sql = "UPDATE table SET $col1$col2$col3 WHERE ID = '$ID'";

which then produces

$sql = "UPDATE table SET col1 = 'data1', col2 = 'data2', col3 = 'data3', WHERE ID = '$ID'";

The problem is the last comma in the sql statement before the , WHERE. That needs to be removed.

So I tried

$sql = "UPDATE table SET $col1$col2$col3 WHERE ID = '$ID'";
$sql = str_replace(", WHERE", " WHERE", $sql);

but that seems to be ignoring it. I thought maybe I needed to do something like strval($sql) first, but again didn't work.

Is there a way to get this to work? Am I making this harder than I need too?

  • 写回答

2条回答 默认 最新

  • douzhaochan6468 2016-03-02 21:16
    关注

    Instead of:

    if ($data1 != '') {
        $col1 = "col1 = '".$data1."', "
    }
    if ($data2 != '') {
        $col2 = "col2 = '".$data2."', "
    }
    if ($data3 != '') {
        $col3 = "col3 = '".$data3."', "
    }
    

    use something like:

    $update_arr = array();
    if ($data1 != '') {
        $update_arr[] = "col1 = '".$data1."'";
    }
    if ($data2 != '') {
        $update_arr[] = "col2 = '".$data2."'";
    }
    if ($data3 != '') {
        $update_arr[] = "col3 = '".$data3."'";
    }
    

    and then create update part of query like this:

    if ($update_arr) {
        $sql = "UPDATE table SET ".implode(", ", $update_arr)." WHERE ID = '$ID'";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码