蓝海航行家
发布于

PHP/MySQL 插入 null 值

从 1 个表中读取,更改一些字段,然后写入另一个表,如果插入并且其中一个数组值为 null,当它在数据库中插入 null(字段允许 null 值)时,不会发生任何事情。它看起来有点像这样:

  $results = mysql_query("select * from mytable");
while ($row = mysql_fetch_assoc($results) {
    mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', {$row['null_field']});
}

并非每一行都有 null 值,在查询中,有更多的字段和 2 列可能为 null,也可能不为 null

浏览 (16)
点赞
收藏
1条评论
星际漫游者
在 MySQL 中,为了插入 null 值,您必须在 time 指定它或省略需要额外分支的字段:INSERT INSERT INTO table2 (f1, f2) VALUES ('String Value', NULL); 但是,如果要在该字段中插入值,则现在必须对代码进行分支以添加单引号: INSERT INTO table2 (f1, f2) VALUES ('String Value', 'String Value'); 准备好的语句会自动为您执行此操作。他们知道 and 之间的区别,并适当地编写您的查询:string(0) ""null $stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)"); $stmt->bind_param('ss', $field1, $field2); $field1 = "String Value"; $field2 = null; $stmt->execute(); 它会为你转义你的字段,确保你不要忘记绑定一个参数。没有理由继续使用这个扩展。使用 和 it's prepared statements。
点赞
评论