2016-02-28 63 views
0
<form action="hi.php" method="post"> 
    <input type="text" name="id" /> 
    <input type="hidden" name="name" value="name" /> 
</form> 

我发送此输入没有值。我想更新id列为NULL更新为NULL Mysql

$id = $_POST['id']; 
$name = $_POST['name']; 

$mysqli->query("UPDATE table SET id=$id WHERE name='$name'); 

但是,它更新为空而不是NULL。我如何在$id中插入NULL?

如果我发送一个值为<input name="id">,它会正确更新它。但是,如果我发送它为空,列变空,我想它为NULL

+0

我只是写它基本上是这样。我知道表单必须具有'action'和'method'属性 –

+1

而且没有WHERE子句也是由于“我刚刚写了基本的”? – VolkerK

+0

@VolkerK现在可以吗? –

回答

0

我建议你使用PDO,而不是mysql的(),但是这会给你的想法:

$id = $_POST['id']; 

if($id==''){ 
    $id='NULL'; 
} 
else{ 
    $id = mysql_real_escape_string($id); 
} 

$qr = 'Update table SET id='.$id; 
mysql_query($qr); 
+0

他在第一行写道:))$ id = $ _POST ['id'];在那里我把它..最后的问题不是关于那个,关于如何处理NULL,我给他的解决方案。 –

+0

definetelly isset()预检查。在整个POST或GET过程中,我通常使用trim和mysql_real_escape_string来运行array_map(),如果我不使用PDO –

1

当使用prepared statements和参数,在参数之一NULL值也将被视为NULL由MySQL服务器。
HTTP参数作为字符串传输。如果没有给出输入控件的值,那么键/值对的值将是一个空字符串(!= NULL)。但是你的脚本中仍然可以有像if(emptystring) use NULL这样的提示。

例如

<?php 
// only for this example; otherwise leave _POST alone.... 
$_POST['id'] = 1; 
$_POST['name'] = ''; 
$mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test'); 
if ($mysqli->connect_errno) { 
    trigger_error(sprintf('mysqli connect error (%d) %s', $mysqli->connect_errno, $mysqli->connect_error), E_USER_ERROR); 
    die; 
} 
mysqli_report(MYSQLI_REPORT_STRICT|MYSQLI_REPORT_ALL); // that's all the "error handling" for this example.... 
setup($mysqli); 

// even if the user didn't fill in any value, the parameters should be in the request 
// as empty strings 
if (!isset($_POST['name'], $_POST['id'])) { 
    echo 'missing POST paramete'; 
} 
else { 
    // <-- maybe some plausiblity checks here anyway; e.g. some assumptions about the id you can test, leaving it out as optional for now ---> 

    // decision point: applying trim() to _POST[name] and _then_ consider it NULL or not - you might disagree about the specifics, just an example. 
    $name = trim($_POST['name']); 
    if (0===strlen($name)) { 
     $name = NULL; 
    } 

    // <-- actually it would suffice to establish the databse connection here.... 
    $stmt = $mysqli->prepare('UPDATE soFoo set name=? WHERE id=?'); 
    $stmt->bind_param('ss', $name, $_POST['id']); 
    $stmt->execute(); 

    printTable($mysqli); 
} 

function printTable($mysqli) { 
    $result = $mysqli->query('SELECT * FROM soFoo ORDER BY id'); 
    foreach($result as $row) { 
     var_export($row); echo "\r\n"; 
    } 
} 

function setup($mysqli) { 
    $mysqli->query('CREATE TEMPORARY TABLE soFoo (id int, name varchar(32), primary key(id))'); 
    $mysqli->query("INSERT INTO soFoo (id,name) VALUES(1,'oldname1'),(2,'oldname2')"); 
} 

打印

array (
    'id' => '1', 
    'name' => NULL, 
) 
array (
    'id' => '2', 
    'name' => 'oldname2', 
)