2012-07-01 53 views
0

我有這個功能內爆修復更新SQL

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; 

} 

它輸出例如:UPDATE SET項目PROJECT_NAME = '123',project_bold = '123',project_content = '123',其中ID = '12 '

之前的最後一個逗號是阻止它工作的地方。有沒有辦法避免這種情況?我意識到函數內爆,但我不知道如何在這種情況下使用它。

+0

請修復SQL注入漏洞,並考慮切換到MySqli或PDO擴展來訪問您的數據庫(MySql擴展名爲obselete)。請參閱http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php –

回答

0

我會使用任一的

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

那個或代替附加到一個字符串,追加到一個數組並使用implode

+0

我一直在試圖實施這個解決方案無濟於事。你能否在這方面給我一個例子?對於之前的插入函數,我這樣做:\t $ sql = sprintf('INSERT INTO%s(%s)VALUES(「%s」)'',$ table, \t implode(',',array_map(' mysql_escape_string',array_keys($ values))),implode('','',array_map('mysql_escape_string',$ values))); \t mysql_query($ sql); – Alex

+1

@Alex爲什麼不只是使用'PDO'? –

+0

還沒有學到它,而且在這個項目的最後階段,我沒有時間:(但是當我這樣做時,我會確定地閱讀它的材料! – Alex

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);