1

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'

3 Answers 3

1

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.

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

1 Comment

@Pat4561 oh I know why , you need to use named placeholder , you see my edit INSERT INTO table(username, password) VALUES (:username, :password)
0

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));

2 Comments

I already know that way, but the problem is that the array is already stored in the variable $values.
you mean, you want to assign it from this $data = array('username' => 'Newuser', 'password' => 'mysecretpass');
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.