Reputation: 2835
I am following tutorials for user registration. This is what I am trying to build query using implode:
if(isset($_POST['submit'])){
$registration_data= array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'password_again' => $_POST['password_again'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email']
);
register_user($registration_data);
}
function register_user($registration_data){
global $connect;
$data=implode(',', $registration_data).'}';
$fields= implode(",", array_keys($registration_data));
Now I have to build query like this
$query=INSERT INTO users ($fields) VALUES($data);
// I want data to be formated like this '{$username}', '{$password}',
How can I do it in above mentioned implode functions,
Note: I am just following some basic tutorials so not worried about PDO/ injections etc
Upvotes: 2
Views: 894
Reputation: 12798
Especially if you are just learning on how to do this, you should learn to do them right from the beginning.
You really don't need to use implode()
with prepared statements. Just use PDO::prepare()
and pass the array to PDOStatement::execute
. Pseudo code is along the lines of:
$registration_data= array(
':username' => $_POST['username'],
':password' => $_POST['password'],
':password_agai' => $_POST['password_again'],
':first_name' => $_POST['first_name'],
':last_name' => $_POST['last_name'],
':email' => $_POST['email']
);
$sql='INSERT INTO yourtable VALUES (:username, :password, :password_agai, :first_name, :last_name, :email);';
$qry=$yourpdoconn->prepare($sql);
$qry->execute($registration_data);
Please note that you still need to handle your errors and everything else, but that's the gist of it. mysqli_*
can do the same with prepared statements so you aren't necessarily stuck with PDO either.
Upvotes: 2
Reputation: 781088
You need to put quotes around all the data values before you implode them:
$data = implode(',', array_map(function($x) {
return "'" . $x . "'";
}, $registration_data));
$fields = implode(',', array_keys($registration_data));
$query = "INSERT INTO users ($fields) VALUES ($data)";
Upvotes: 2