简体   繁体   English

用变量生成的str_replace生成的字符串不适用于php

[英]str_replace with variable generated string not working with 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. 我有一个通过变量填充的sql语句,该变量可能包含也可能不包含数据,这就是为什么我必须这样做。

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. 并非每个$data可能包含某些内容,因此某些变量将为空,并且不是我的SQL语句的一部分,但假设所有三个变量都有数据。

$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 . 问题是, WHERE之前sql语句中的最后一个逗号。 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. 我以为也许我需要先做类似strval($sql)事情,但是又没有用。

Is there a way to get this to work? 有没有办法让它工作? Am I making this harder than I need too? 我是否比我需要的还要难?

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'";
}

You can remove the last comma using rtrim() doing something like this: 您可以使用rtrim()删除最后一个逗号,如下所示:

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

if ($columns) {
  // remove any trailing ','
  $columns = rtrim($columns, ',');

  $sql = "UPDATE table SET $columns WHERE ID = '$ID'";
}

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

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