2

PDO param:

$cto=new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);

Interacting with data base

$csql=$cto->prepare("INSERT INTO `users`(`username`, `password`, `class`, `is_on`, `time_log`, `IP`)
        VALUES (:name,:pass,:class,0,0,'0')");
        $pr=[
          ':name' => $_POST['username'],
          ":pass" => $_POST['password'],
          ":class" => $_POST["class"],
        ];
        $csql->execute($pr);
        $cto=null;

My question is ,i am currently using array $pr in execute,could i pass this array with using bindParam

$csql->bindParam($pr);
$csql->exec();

Thank you for your time.

AwwYsss
  • 99
  • 2
  • 3
  • 6
  • 2
    no, as [`->bindParam()`](http://php.net/manual/en/pdostatement.bindparam.php) - *Binds **a** parameter to the specified variable name*. An alternative would be to do it in a loop. ie. `foreach($pr as $key=>$val){$csql->bindParam($key,$val);}` – Sean Jan 19 '16 at 06:06

4 Answers4

9

You can use bindParam() in single line by this way:

$csql=$cto->prepare("INSERT INTO `users`(`username`, `password`, `class`, `is_on`, `time_log`, `IP`)
VALUES (:name,:pass,:class,0,0,'0')");

//Looping for all values into array...
foreach ($pr as $key => &$val) {
    $csql->bindParam($key, $val);
}
$csql->execute();

Hope this will help you!

AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57
6

Yes you have to do one line per bindParam(), if you want to bind several values as in an array, try it inside the excute()

http://php.net/manual/en/pdostatement.bindparam.php

SIDU
  • 2,258
  • 1
  • 12
  • 23
1

You can pass all parameters as an array inside the execute().

This works with variable parameter size, not know beforehand, and avoids the loop that can lead to mistakes.

$inputArray : input parameters in array format

//step 1 : create placeholders in format ?,?,?

$placeholders = str_repeat('?,', count($inputArray) - 1) . '?';

//step 2: create query

$query = "  select *
            from table
            where column in ($placeholders)";

//step 3: prepare as usual

$st = $this->db()->prepare($query);

//step 4: send values in the execute

$st->execute($inputArray);
Aris
  • 4,643
  • 1
  • 41
  • 38
0

You can also use bindValue, if you don't want to pass by reference with bindParam.

foreach ($pr as $key => &$val) {
    $csql->bindValue($key, $val);
}