I’m trying to build a simple and flexible application with PHP and mySQL. Basically, I have several mySQL tables each with a unique number of fields/columns.
The problem I’m facing is that can’t figure out how to write a dynamic mySQL insert statement based off a PHP array variable. For example, I have a table with three fields: title, author, and year. I want a user to be able to INSERT a record into the table via a simple webform. The catch is that I want to be able to re-use the mySQL statet throughout my application, so it needs to be somewhat generic.
I thought I could go about this by declaring an array variable like so:
$table_variables = array(title, author, year);
My hope is that each form on my application will use the same php/mySQL code base and all I’ll need to do is update the array variable.
Normally, I’d write an INSERT statement like so:
$sql = "INSERT INTO books(title, author, year)
VALUES(
'" . $POST['title'] . "'),
'" . $POST[author] . "'),
'" . $_POST[year] . "')”;
For the application though, I want things to fill in dynamically, something like:
$sql = "INSERT INTO books($table_variables[0], $table_variables[1], $table_variables[2])
VALUES(
'" . $POST[$table_variables[0]] . "'),
'" . $POST[$table_variables[1]] . "'),
'" . $_POST[$table_variables[2]] . "')”;
Is there any way to embed a increment variable within the declaration of another variable. For example, is there a way to embed i++ within the declaration of my $sql variable? Without doing that, I don’t know how to build up the sql statement.