Reputation: 607
The $data variable stores an array containing a username and password, which need to be inserted in a certain table.
$data = array('username' => $username, 'password' => $password);
foreach($data as $key => $value){
$values = $values . "'" . $value . "'" . ",";
}
$sql = "INSERT INTO table(username, password) VALUES (?, ?)";
$query = $con->prepare($sql);
$query->execute($values);
How can I change this code in such a way that it will print the values of the $values variable into the execute function? E.g. 'Newuser','mysecretpass'
Upvotes: 1
Views: 1105
Reputation: 45490
You can do it this way:
$data = array('username' => $username, 'password' => $password);
$sql = "INSERT INTO table(username, password) VALUES (:username, :password)";
$query = $con->prepare($sql);
foreach($data as $key => $value){
$query->bindValue($key, $value);
#echo 'key = '.$key.' | value = '.$value;
}
$query->execute();
The above binds each value to its placeholder, and if you want to print them you can.
Upvotes: 1
Reputation: 1681
You can bind the params like
$sql = "INSERT INTO table(username, password) VALUES (:user, :pass)";
$query = $con->prepare($sql);
$query->bindParam(':user', $data['username'] );
$query->bindParam(':pass', $data['password']);
$query->execute();
Upvotes: 0
Reputation: 7977
Try this! Execute a prepared statement by passing an array of insert values.
$sql = "INSERT INTO table(username, password) VALUES (?, ?)";
$query = $con->prepare($sql);
$query->execute(array($username, $password));
Upvotes: 0