php sql update只填写字段

时间:2012-11-19 10:04:40

标签: php sql

(这是所有基本的php voor学校) 我创建了一个表单,您可以在其中更新您的帐户信息,当您点击提交按钮时,它将来到此PHP代码。如果一个字段没有填写,它不需要更新,我尝试“WHERE字段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");`

当然我需要广告“字段”的其余部分IS NOT NULL但是例如我只使用'naam'..但它不起作用:/

1 个答案:

答案 0 :(得分:0)

如果你将这部分逻辑远离数据库,那可能是最简单的,例如

<?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']
);

(未测试的)