Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

php - insert array data into mysql using PDO

i have this array with data from a html form, and i want this array to be inserted into PHP function that handles the INSERT query into mysql.

how can i declare my array into PDO

   if (isset($_POST['submit'])); {
    $_POST['name'];
    $_POST['age'];


$myarray= array();
foreach ($_POST as $key => $value){
   $myarray[$key] = $value;
}

whatever($myarray);

}

functions whatever($myarray) {
    $sql=$db->prepare("INSERT INTO `user`(`name`, `age`) VALUES (:name,:age)");

    foreach($myarray as $row=>$value){
     $sql->bindValue(array($myarray)){
    }
    $sql->execute();
}

apology for forgetting the error.

this is what i get

    Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in C:Webxampphtdocssubmit.php on line 36

    Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in C:Webxampphtdocssubmit.php on line 36

    Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in C:Webxampphtdocssubmit.php on line 36

    Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: no parameters were bound' in 
C:Webxampphtdocssubmit.php:38 Stack trace: #0 
C:Webxampphtdocssubmit.php(38): PDOStatement->execute() #1 
C:Webxampphtdocssubmit.php(12): register(Array) #2 {main} thrown in 
C:Webxampphtdocssubmit.php on line 38
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
function pdoSet($fields, &$values, $source = array()) {
  $set = '';
  $values = array();
  if (!$source) $source = &$_POST;
  foreach ($fields as $field) {
    if (isset($source[$field])) {
      $set.="`".str_replace("`","``",$field)."`". "=:$field, ";
      $values[$field] = $source[$field];
    }
  }
  return substr($set, 0, -2); 
}

This function will produce a correct sequence for the SET operator,

`field1`=:field1,`field2`=:field2

to be inserted into query and store avtual data values in $values array for execute().

$fields = array('id','name','age','loc'); // allowed fields
$sql = "INSERT INTO `user` SET".pdoSet($fields,$values);
$stm = $dbh->prepare($sql);
$stm->execute($values);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...