0

I have this function

function updateDbRecord($db, $table, $carry, $carryUrl) {   
    mysql_select_db($db) or die("Could not select database. " . mysql_error());
    $resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
    $fieldnames=array();
      if (mysql_num_rows($resultInsert) > 0) {
        while ($row = mysql_fetch_array($resultInsert)) {
            $fieldnames[] = $row['Field'];
            $arr = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
        }
      }

      $set = "";
      foreach($arr as $key => $v) {
        $val = is_numeric($v) ? $v : "'" . $v . "'";

        $set .= $key . '=' . $val . ', ';
      }
      $sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $set, $_POST['id']);
      mysql_query($sql);
      if ($carry == 'yes') {
        redirect($carryUrl.'?id='.$_REQUEST['id']);
      } else { echo "Done!"; }
      echo $sql;

}

It outputs for example: UPDATE projects SET project_name='123', project_bold='123', project_content='123', WHERE id='12'

The last comma before where is preventing it from working. Is there a way of avoiding this? Im aware of the function implode, however I am not sure how to employ it in this situation.

4

3 回答 3

0

Yes,

$sql = substr($sql,'',-1);
于 2012-07-01T01:25:07.987 回答
0

I would use

$sql = rtrim($sql, ',');

Either that or instead of appending to a string, append to an array and use implode.

于 2012-07-01T01:26:26.073 回答
0
function updateDbRecord($db, $table, $carry, $carryUrl) {   
    mysql_select_db($db) or die("Could not select database. " . mysql_error());
    $resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
    $fieldnames=array();
      if (mysql_num_rows($resultInsert) > 0) {
        while ($row = mysql_fetch_array($resultInsert)) {
            $fieldnames[] = $row['Field'];
            $array = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
        }
      }
      foreach ($array as $key => $value) {

                $value = mysql_real_escape_string($value); // this is dedicated to @Jon
                $value = "'$value'";
                $updates[] = "$key = $value";
            }
      $implodeArray = implode(', ', $updates);
      $sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
      mysql_query($sql);
于 2012-07-01T01:46:37.133 回答