[英]php sql update only filled in fields
(這是所有基本的php voor學校)我制作了一個表格,您可以在其中更新您的帳戶信息,當您單擊“提交”按鈕時,它將顯示此php代碼。 如果未填寫字段,則不需要更新,我嘗試了“ WHERE field IS NOT NULL”,但它似乎不起作用,它提供了一個空記錄...
(變量全是荷蘭語,對不起)
$klantnummer = $_COOKIE['klantnummer'];
$naam =($_POST["naam"]);
$adres =($_POST["adres"]);
$postcode =($_POST["postcode"]);
$gemeente =($_POST["gemeente"]);
$leden =($_POST["gezinsleden"]);
$huidigemeterstand =($_POST["huidigemeterstand"]);
$vorigemeterstand =($_POST["vorigemeterstand"]);
$provincie =($_POST["provincie"]);
//set up connection and choose database
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("opdracht3", $con);
mysql_query("UPDATE waterstand SET naam = '$naam', adres = '$adres', postnummer = '$postcode', gemeente = '$gemeente', vorigemeterstand='$vorigemeterstand', huidigemeterstand='$huidigemeterstand', provincie='$provincie', aantalgezinsleden = '$gezinsleden'
WHERE klantnummer = '$klantnummer' AND naam IS NOT NULL");`
當然,我需要聲明“字段”的其余部分不是NULL,但是例如,我僅使用“ naam” ..但它不起作用:/
如果讓邏輯的這一部分遠離數據庫,那可能是最容易的,例如
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if ( !mysql_select_db("opdracht3", $con) ) {
die('Could not connect: ' . mysql_error());
}
// contains strings/parameters/identifiers ready-for-use with mysql
$sql_params = array(
'fields' => array('naam', 'adres', 'postcode', 'gemeente', 'gezinsleden', 'huidigemeterstand', 'vorigemeterstand', 'provincie'),
'klantnummer' => mysql_real_escape_string($_COOKIE['klantnummer']),
'updates' => array()
);
// the names of the POST-fields are the same as the column identifiers of the database table
// go through each identifier
foreach( $sql_params['fields'] as $f ) {
// put in here the conditions for "an empty field, e.g.
// if there is such POST-field and its value is one or more "usable" characters long
if ( isset($_POST[$f]) && strlen(trim($_POST[$f])) > 0 ) {
// create a new `x`=`y` "line" as in UPDATE ... SET `x`='y'
// and append it to the array $sql_params['updates']
$sql_params['updates'][] = sprintf("`%s`='%s'", $f, mysql_real_escape_string($_POST[$f]));
}
}
// the "lines" in $sql_params['updates'] need to be concatenated with , between them
// join(', ', $sql_params['updates']) does that
// insert that string and the parameter klantnummer into the query string
$query = sprintf(
"
UPDATE
waterstand
SET
%s
WHERE
klantnummer = '%s'
",
join(', ', $sql_params['updates']),
$sql_params['klantnummer']
);
(未試)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.