0

two arrays:

$columns = array('mail', 'phone', 'author', 'title');
$values = array('some mail', 'some phone', 'an author', 'a title');

Is it possible something like this:

$sql = "insert into actual (" . implode(', ', $columns) . ") values (" . implode(', ', $values) . ")";
$st = $db->prepare($sql);
$st->execute();  // line 23

I tried and got a syntax error on line 23.

6
  • 1
    try show us the var_dump($sql) Commented Sep 18, 2018 at 19:30
  • the implode don't wrap the string with proper quotes .. Commented Sep 18, 2018 at 19:33
  • 1
    Your values should be in quotes, better still is to use place holders for each value and bind the $values array in the execute() Commented Sep 18, 2018 at 19:33
  • @scaisEdge, you probably mean var_dump($columns)? Commented Sep 18, 2018 at 19:34
  • 1
    WARNING: Whenever possible use prepared statements to avoid injecting arbitrary data in your queries and creating SQL injection bugs. These are quite straightforward to do in mysqli and PDO where any user-supplied data is specified with a ? or :name indicator that’s later populated using bind_param or execute depending on which one you’re using. Commented Sep 18, 2018 at 19:37

1 Answer 1

1

To write this as a prepared statement with place holders, you need to repeat ? for each field and then pass the values using bindParam() (assuming mysqli)...

$columns = array('mail', 'phone', 'author', 'title');
$values = array('some mail', 'some phone', 'an author', 'a title');
// Create place holders (need to remove last comma - done in build of SQL)
$valuesPlace = str_repeat("?,", count($values));
$sql = "insert into actual (" . implode(', ', $columns) . ") 
    values (" . rtrim($valuesPlace, ",") . ")";

$st = $db->prepare($sql);
// Bind a list of string values (big assumption)
$st->bindParam(str_repeat("s", count($values)), ...$values);
$st->execute();  // line 23
Sign up to request clarification or add additional context in comments.

1 Comment

While this is a solution, this ends up being a really crappy imitation of a proper ORM. If you need this sort of dynamic query building, which can really simplify code design, use an actual ORM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.