0

I've been trying to get a grasp on PDO and I have a question about insert statements. I'm trying to add an array of values (ie., the following example)

data = array (
    fname -> Jay
    lname -> Doe
    phone -> 8137587733
    email -> me@me.com
);

The fields and values are broken into strings as below:

$fields = '`' . implode('`, `', array_keys($data)) . '`';
$values = '\'' . implode('\', \'', $data) . '\'';

...but I want to be able to use prepared statements to prevent possible SQL Injection.

Not all fields are required. For example, phone (which comes from $_POST['phone']), might be empty, and the database field accepts NULL input for this field.

Can the old way:

mysql_query("INSERT INTO 'users' ($fields) VALUES ($values)");

be adapted somehow to be used with PDO or do I need to do the following:

$sql = "INSERT INTO users VALUES (:fname, :lname, :phone:, :email)";
$st = $conn->prepare($sql);
$st->bindValue( ":fname", ???, PDO::PARAM_STR );
$st->bindValue( ":lname", ???, PDO::PARAM_STR );
$st->bindValue( ":phone", ???, PDO::PARAM_STR );
$st->bindValue( ":email", ???, PDO::PARAM_STR );
$st->execute();

Here I'm not sure how to input my values (hence the ???).

JimRomeFan
  • 407
  • 6
  • 19
  • Actually, there's a middle ground. Look here for some good suggestions: [PHP PDO: Can I bind an array?](http://stackoverflow.com/questions/920353/php-pdo-can-i-bind-an-array-to-an-in-condition) – paulsm4 Mar 30 '13 at 01:47
  • 1
    Every question you have regarding PDO already covered in the [tag wiki](http://stackoverflow.com/tags/pdo/info) – Your Common Sense Mar 30 '13 at 01:51
  • @paulsm4 the answer in the question you linked to should never be used. Asserts are not for production code. – Your Common Sense Mar 30 '13 at 01:55
  • I actually saw that page when I was looking for a solution but the syntax confused me. – JimRomeFan Mar 30 '13 at 01:57
  • If I put data[fname] where the first ??? is and repeat that will it work based on my code? – JimRomeFan Mar 30 '13 at 02:17

0 Answers0