title: str_replace with variable generated string not working with php
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>Example</p>
  
  <pre><code>if ($data1 != '') {
      $col1 = "col1 = '".$data1."', "
  }
  if ($data2 != '') {
      $col2 = "col2 = '".$data2."', "
  }
  if ($data3 != '') {
      $col3 = "col3 = '".$data3."', "
  }
  </code></pre>
  
  <p>Not every <code>$data</code> may contain something so some variables will be empty and not part of my SQL statement, but lets assume all three have data.</p>
  
  <pre><code>$sql = "UPDATE table SET $col1$col2$col3 WHERE ID = '$ID'";
  </code></pre>
  
  <p>which then produces</p>
  
  <pre><code>$sql = "UPDATE table SET col1 = 'data1', col2 = 'data2', col3 = 'data3', WHERE ID = '$ID'";
  </code></pre>
  
  <p>The problem is the last comma in the sql statement before the <code>, WHERE</code>. That needs to be removed.</p>
  
  <p>So I tried </p>
  
  <pre><code>$sql = "UPDATE table SET $col1$col2$col3 WHERE ID = '$ID'";
  $sql = str_replace(", WHERE", " WHERE", $sql);
  </code></pre>
  
  <p>but that seems to be ignoring it. I thought maybe I needed to do something like <code>strval($sql)</code> first, but again didn't work.</p>
  
  <p>Is there a way to get this to work? Am I making this harder than I need too?</p>