我有一个用户看起来像这样的对象。
$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, reputationI 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 topicsI 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.
更多推荐
发布评论