1
$con = mysqli_connect('localhost','root','',"z_db_test");
$tablename = 'test';
$about = 'Some info';
$firstname = 'Doe';
$lastname = 'Joe';  

$datas = array('about'=>$about,'firstname'=>$firstname,'lastname'=>$lastname);

function addeverything($tablename,$datas)
{
    $keys= array_keys($datas);
    $insert = "INSERT INTO ".$tablename."
   ('`'.implode('`,`', $keys).'`')
    VALUES("        '
    ".implode("
    ','
    ", $datas)."
    '
    ") ";

    return mysqli_query($insert);
}

addeverything('test',array('about'=>$about,'firstname'=>$firstname,'lastname'=>$lastname));

So i get the error

Parse error: syntax error, unexpected ''".implode("'' (T_CONSTANT_ENCAPSED_STRING) in C:\xampp\htdocs\test\index.php on line 20

How to fix the error?

juergen d
  • 201,996
  • 37
  • 293
  • 362
  • The problem is your quotes inside of quotes in your insert statement. You also have the .implode function inside of quotes, so PHP can't determind what you are trying to do. Using variables inside of DOUBLE quotes is fine..... – Native Coder Sep 15 '16 at 14:57
  • **Just saying: your function is useless, you could aswell directly put the content into the query and add the table to the query.** – Xatenev Sep 15 '16 at 15:15
  • @Xatenev - while not *ideal*, the function is far from "useless". And no need to bold your whole comment. Not very useful / constructive. – random_user_name Sep 15 '16 at 15:42
  • @cale_b Can you explain me what this function helps with? Sorry for the bold. This function seems absolutely redundant for me. – Xatenev Sep 15 '16 at 15:44
  • @Xatenev - It provides a more abstract way of inserting into the database. While in it's current form it may not be super useful, but for maintenance / future enhancement purposes, it's useful to have a function like this. There could be sanitization added, some sort of "watcher" function added to detect certain things, etc. If you had tens or hundreds of individual inserts separately, touching every one to add / edit something would be a lot of work. If it's centralized into a function like this, OP could - for example - switch from mysqli to PDO in *one place* simply. – random_user_name Sep 15 '16 at 15:49

1 Answers1

0

The errors suggests you're missing a " or a . somewhere in your php. It's an overly complicated statement, try simplifying it.

You could do something like this.

function enquote($val){return sprintf("`%s`", $val);};

 $insert = "INSERT INTO ". $tablename ."( ". implode(',', $keys ) ." ) 
            VALUES ( ". implode(",", array_map( "enquote", $datas )) .")";

the enquote function will add ` around all values quoting them for insert.

This query is not SQL Injection proof so be aware.

serverSentinel
  • 994
  • 6
  • 20