0

(这是所有基本的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");`

当然我需要添加“字段”的其余部分不为空,但例如我只使用“naam”..但它不起作用:/

4

1 回答 1

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

(未经测试)

于 2012-11-19T10:25:05.380 回答