0

I've created a new function with PDO to insert data in my database.

The function looks like this

 function insert($table,$column = array(),$value = array()) { $array1 = implode(",", $column); $array2 = implode(",", $value); try { $sql = $this->connect->query("INSERT INTO $table ($array1) VALUES ($array2)"); } catch(PDOException $e) { echo $e->getMessage(); } } 

and the call for the function like this

-> insert('coupons',array('categorie','name','link','code','id'),array('test11','test','test','test','NULL')); 

but after all, it seems not to work and isn't showing any error. Do someone have a few points for me, where I should search the mistake? When I write the query /wo the varibales and call the function, it works. Even with the first two variables it works. Only the last one ($array2) seems to have a "bug".

4
  • 3
    I recommend against such a design. For starters, it doesn't utilize the main benefits of PDO, namely binding parameters and protecting against SQL Injection. Commented Nov 15, 2012 at 18:46
  • what do you mean by binding the paramerters? Like splitting the query and reassamble it on the end ? Commented Nov 15, 2012 at 19:00
  • bindParam() Commented Nov 15, 2012 at 19:02
  • Thanks for the pointer, I will use it in my code! Commented Nov 15, 2012 at 19:07

1 Answer 1

1

You're inserting strings, which means your query comes out

INSERT INTO coupons (categorie, name, ...) VALUES (test11, test, ...) 

bare strings are interpreted as field/table names, meaning your query is completely invalid.

At bare minimum, ignoring all the other problems with this code, the fix would be

$array2 = implode("','", $value); ^-^--- INSERT INTO $table ($array) VALUES ('$array2'); ^-- ^-- 

of course, this is ignoring the sql injection vulnerabilities, keyword problems, blah blah blah.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.