1

I'm trying to make a loop to add all POST keys to PDO bind Parameter. when i make the POST Request with JS it works however if i made it all in php it don't which i found kind of a strange ,here's an example .

This the JS

 var dataString="Name="+encodeURIComponent($("#name ."+Name[i]+"").val())+"&Email="+encodeURIComponent($("#email ."+Name[i]+"").val());
$.ajax({
    type: "POST",
    url: "sendback.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
     }
    });

PHP Backend.

   foreach($_POST as $key => $value) {
    $Value=trim(urldecode($value));
       $stmt -> bindParam(':'.$key.'',$Value);
    }

Result

---------------------------
Name          |        Email 
AAA           |[email protected]
----------------------------

This Works and stores data correctly in the database

However

This Don't

$_POST['Name']="AAA";
$_POST['Email']="[email protected]";
foreach($_POST as $key => $value) {
$Value=trim(urldecode($value));
$stmt -> bindParam(':'.$key.'',$Value);
}
$stmt -> execute();

Result

---------------------------
Name          |        Email 
[email protected] |[email protected]
----------------------------

It stores the values of the last $_post key in all the database columns . So all the inputs to the database in this example would be "[email protected]" after searching i found that to make the previous example works i need to add an "&" before the "$value" in the loop,makes me wonder why it's different than the Ajax request,i mean they both POST requests,right?

8
  • var dataString={name1: val1, name2: val2,........} Commented Apr 8, 2016 at 10:09
  • 1
    In what way does it not work?? Commented Apr 8, 2016 at 10:15
  • in the last example when i try to make the $POST with PHP it self rather than an Ajax request Commented Apr 8, 2016 at 10:22
  • Yes but in what way does it not work? Commented Apr 8, 2016 at 10:38
  • Oh , sorry about that I didn't mention the results . Commented Apr 8, 2016 at 12:24

1 Answer 1

1

What the PDO docs fail to explain is that bindParam() is passed to PDO byref - whereas bindValue() isn't.

It's better to use bindValue() in this case. bindParam() is intended to execute a query, and then change the variables and re-execute without binding the parameters again. bindValue() binds immediately, bindParam() only on execute

&$value is the reference to the $value, not it's value

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

1 Comment

This doesn't change anything compared to his own code. Besides that, it would crash his file since you have two errors in your code. There are too much quotes before the mail and you have a comma too much at the end.

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.