2012-12-12 87 views
-1

我有這個查詢,我用它來更新表。 的問題是,我只需要更新值從「未定義」只更新非空記錄

隨着有人在這裏的幫助我得到這個查詢不同:

$sqlStart="UPDATE forma SET "; 
$sql=""; 
if (!empty($postDyqani_pergjegjes)) $sql += " dyqani_pergjegjes='$postDyqani_pergjegjes',"; 
if (!empty($postEmri)) $sql += " emri='$postEmri',"; 
if (!empty($postKlienti)) $sql += " klienti='$postKlienti',"; 
if (!empty($postTelefoni)) $sql += " telefoni='$postTelefoni,'"; 
if (!empty($postMontim)) $sql += " montim='$postMontim',"; 
if (!empty($postAdresa)) $sql += " adresa='$postAdresa',"; 
if (!empty($postData_e_shitjes)) $sql += " data_e_shitjes='$postData_e_shitjes',"; 
if (!empty($postDifekti)) $sql += " difekti='$postDifekti',"; 
if (!empty($postTekniku_emer)) $sql += " tekniku_emer='$postTekniku_emer',"; 
if (!empty($postTekniku_mesazh)) $sql += " tekniku_mesazh='$postTekniku_mesazh',"; 
if (!empty($postData_fillim)) $sql += " data_fillim='$postData_fillim',"; 
if (!empty($postData_mbarim)) $sql += " data_mbarim='$postData_mbarim',"; 
if (!empty($postData)) $sql += " data='$postData',"; 
if (!empty($postStatus)) $sql += " status='$postStatus',"; 
// replace the last `,` for `;` 
if ($sql != "") { 
$sql = substr($sql, 0, -1) . ";"; 

    // replace the last `,` for `;` 
    // run sql command 
    echo $sqlCommand = $sqlStart.$sql; 
    $result=mysql_query($sqlCommand) or die(mysql_error()) ; 

} else { 
} 

它雖然不會執行.. 請給我一手在這.. 如果我打印的變量其中大部分結果是undefined 謝謝

+1

change + = to。= – Kao

+0

「undefined」?在PHP或MySQL中沒有這種價值。請描述你想要做的更好。也許'......在哪裏不是NULL'? – deceze

+0

的想法是,更新查詢將flexible,所以一些變量,即使他們在查詢中,可能沒有一個值,當我打印它們時,它說undefined –

回答

0

有許多事情打破你的方法;首先,+ =不會做你認爲它爲PHP字符串,將可能使一切最終成爲值0 =使用一個字符串串聯到現有的字符串:

$foo = '123'; 
$foo .= 'abc'; 

// $foo == '123abc' 

其次,沒有關於變量來自何處的更多信息,很難說出錯的方式。如果您有一個名爲「Dyqani_pergjegjes」的字段,則引用它的正確方法是使用$_POST['Dyqani_pergjegjes']

此外,您需要轉義想要在SQL查詢中使用的字符串,以避免SQL注入漏洞和其他可能的錯誤(或者在mysqli中使用預準備語句或使用PDO),如果您想要正確解決它) :

difekti='". mysql_real_escape_string($postDifekti) . "' 

您也錯過了UPDATE語句的條件,所以在它的當前表單中它會更改數據庫中的所有行。可能不是你想要的。而且你不需要添加「;」在聲明的最後 - 這在執行查詢時是隱含的,並且通常不建議。