I have an object that looks like this.
$user = new User(); $user->name = 'Name'; $user->age = 34;
There are five fields in my database,
id, name, age, location, reputation
I have a method that (for all my tables) collects all fields dynamically from a table with the following SQL. That way, I can dynamically get the number of place holders for entering an INSERT statement.
SHOW FIELDS FROM users SHOW FIELDS FROM questions SHOW FIELDS FROM topics
Then I wrote the create method, which counts the number of fields in the table and prepares a row filled with placeholders, and automatically inserts it into my PDO request by doing this:
INSERT INTO users VALUES (?, ?, ?, ?, ?)
Then I take the my user object and make an array of all the properties that it has, and pass this array to my prepared PDO statement in the execute parameter. This works great, and the function inserts data into the database.
My problem is that sometimes I donβt have all the properties for my objects yet, and therefore I populate the rest of the array, which passes the execute function to empty lines. When it reaches a field that takes an integer, it causes a fatal error and does not 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? Since this is all done dynamically, I cannot guess in advance to put an integer or an empty string there. Is there any way to discard some placeholders altogether? Any other solutions?