我可以让mysql对它收到的数据类型不那么严格吗?(can i make mysql less strict about what type of data it receives?)

编程入门 行业动态 更新时间:2024-10-25 16:23:23
我可以让mysql对它收到的数据类型不那么严格吗?(can i make mysql less strict about what type of data it receives?)

我有一个用户看起来像这样的对象。

$user = new User(); $user->name = 'Name'; $user->age = 34;

在我的数据库中有五个字段,

id, name, age, location, reputation

我有一个方法(对于我的所有表)使用以下SQL从表中动态收集所有字段。 这样我就可以动态地获取要放在INSERT语句中的占位符数。

SHOW FIELDS FROM users SHOW FIELDS FROM questions SHOW FIELDS FROM topics

然后我编写了一个create方法,它计算表中字段的数量,并准备一个充满占位符的字符串,并自动将其插入到我的PDO查询中,使得:

INSERT INTO users VALUES (?, ?, ?, ?, ?)

然后我接受我的$ user对象并从它拥有的所有属性中创建一个数组,并将该数组提供给execute参数中的PDO预处理语句。 这很好用,该函数将数据插入数据库。

我的问题是,有时我还没有填充我的对象的所有属性,因此我填充了用空字符串提供execute函数的数组的其余部分。 当它到达一个取整数的字段时,它会导致致命错误并且不起作用。 如果能够在我的代码中为每个字段编写正确的数据类型,我能够动态地将空字段插入到我的数据库中,该怎么办? 因为这一切都是动态完成的,所以我不能提前知道在那里放一个整数或一个空字符串。 有没有办法完全省略一些占位符? 还有其他方法吗?

I have a user a object that looks like this.

$user = new User(); $user->name = 'Name'; $user->age = 34;

In my database there are five fields,

id, name, age, location, reputation

I have a method that (for all my tables) collects all the fields dynamically from a table with the following SQL. This way I can dynamically get the number of place-holders to put in an INSERT statement.

SHOW FIELDS FROM users SHOW FIELDS FROM questions SHOW FIELDS FROM topics

I then have written a create method that counts the number of fields in the table and prepares a string full of placeholders and automatically insert it into my PDO query making this:

INSERT INTO users VALUES (?, ?, ?, ?, ?)

I then take my $user object and make an array out of all the properties that it has and give that array to my PDO prepared statement in the execute parameter. This works fine and the function inserts data into the database.

My problem is that sometimes I dont yet have all the properties for my objects filled in and I therefore populate the rest of the array that feeds the execute function with empty strings. When it reaches a field that takes an integer, it causes a fatal error and doesn't work. What can I do to be able to insert empty fields into my database dynamically without writing the correct data-type for each field in my code? Because this is all done dynamically I cannot know ahead of time to put an integer or an empty string there. Is there a way to leave out some placeholders altogether? Any other solutions?

最满意答案

将可选的mysql字段设置为接受NULL。

Set your optional mysql fields to accept NULL.

更多推荐

本文发布于:2023-07-16 07:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1125432.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对它   数据类型   mysql   strict   receives

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!