将NULL从PHP传递到MySQL以自动递增 [英] Passing NULL from PHP to MySQL for auto increment

查看:81
本文介绍了将NULL从PHP传递到MySQL以自动递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在MySQL中有一个数据库设置,共有三列.第一列是"idnum",它会自动增加用户的ID号.第二个和第三个分别是名字和姓氏.我的问题是,当我通过PHP文件中的查询字符串将名称发送到数据库时,出现了一些不同的错误……

So I have a database setup in MySQL with three columns. The first column is 'idnum' that auto increments the users id numbers. The second and third are first and last names respectfully. My problem is when I go to send the the names to the DB via a query string in my PHP file, I get a couple different errors back...

我发送查询时:

$sql = "insert into namesdb values('NULL', 'firstname', 'lastname')";
$result = $db->query($sql);

我得到以下错误:第1行的'idnum'列的整数值不正确:'NULL'"因为第1列是INT类型.

I get back this error: "Incorrect integer value: 'NULL' for column 'idnum' at row 1." Because column 1 is an INT type.

但是当我发送此查询时:

But then when I send this query:

$sql = "insert into namesdb values(".NULL.", 'firstname', 'lastname')";
$result = $db->query($sql);

我找回语法错误...

I get back a syntax error...

关于我在这里做错了什么的任何想法?

Any idea on what the heck I'm doing wrong here??

谢谢您的帮助!

推荐答案

应为:

$sql = "insert into namesdb values(NULL, 'firstname', 'lastname')";
$result = $db->query($sql);

'NULL'"NULL"的字符串.

另一种选择(我会选择的一种选择)是显式列出列:

Though another option (the one I would go with) is to list the columns explicitly:

INSERT INTO namesdb (firstname, lastname) VALUES ('firstname', 'lastname')

我更喜欢列出这些列,因为它可以为将来提供更多证明,并且更容易看到正在发生的事情.想象一下将来是否重新排列,添加或删除了列.如果您必须在每个地方都删除第6个未命名的参数,那么突然修复您的查询将是一个巨大的麻烦.

I prefer listing the columns because it is more future proof, and it's easier to see what's going on. Imagine if columns are rearranged, added, or removed in the future. Suddenly fixing your queries is going to be a massive pain if you have to remove the 6th unnamed parameter everywhere (for example).

这篇关于将NULL从PHP传递到MySQL以自动递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆