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 ???).