0

我的数组像这样显示,但我似乎无法将它保存到数据库中。因此,当我var_dump($result);在 $result 是我的数组时这样做时,会显示以下内容

array
0 => 
array
  'Credit Weighting' => string '5' (length=1)
  'Teaching Period(s)' => string 'Teaching Periods 1 and 2.' (length=25)
  'No. of Students' => string '-.' (length=2)
1 => 
array
  'Credit Weighting' => string '5' (length=1)
  'Teaching Period(s)' => string 'Teaching Periods 1 and 2.' (length=25)
  'No. of Students' => string '-.' (length=2)
2 => 
array
  'Credit Weighting' => string '10' (length=2)
  'Teaching Period(s)' => string 'Teaching Periods 1 and 2.' (length=25)
  'No. of Students' => string '-.' (length=2)

下面是我的 PDO 查询,用于将上述内容保存到 mysql 中,但没有发生任何事情。请问我做错了什么?

$result = array();  
$placeholder = array();
$values = "?, ?, ?";
foreach ($result as $array){
$placeholder[] = $value;

        $result[] = $array['CreditWeighting'];
        $result[] = $array['TeachingPeriod'];
        $result[] = $array['NoofStudents'];         
} 

$sql = "INSERT INTO data_array_copy (CreditWeighting,TeachingPeriod,NoofStudents)
                             VALUES (". implode('), (', $placeholder) . ")"; 
$stmt = $conn->prepare($sql);
$stmt->execute($result);
4

2 回答 2

1

尝试这个:

<?php 
//If your array is:
/*
$result = array(0=>array('Credit Weighting'=>'5',
                         'Teaching Period(s)'=>'Teaching Periods 1 and 2.',
                         'No. of Students'=> '-.'),
                1=>array('Credit Weighting'=>'5',
                         'Teaching Period(s)'=>'Teaching Periods 1 and 2.',
                         'No. of Students'=> '-.'),
                2=>array('Credit Weighting'=>'10',
                         'Teaching Period(s)'=>'Teaching Periods 1 and 2.',
                         'No. of Students'=> '-.'));
*/
//The query
$sql = "INSERT INTO data_array_copy (CreditWeighting,TeachingPeriod,NoofStudents)
               VALUES (?,?,?)"; 
//Prepare the query
$stmt = $conn->prepare($sql);

//Loop through the $result array
foreach ($result as $array){
    //Bind and execute the values to the prepared query
    $stmt->bindParam(1, $array['Credit Weighting']);
    $stmt->bindParam(2, $array['Teaching Period(s)']);
    $stmt->bindParam(3, $array['No. of Students']);
    $stmt->execute($result);
}
?>

在http://php.net/manual/en/pdo.prepared-statements.php上还有其他绑定参数的方法,但在您熟悉其细节之前,使其尽可能易读。通过这种方式,您或其他开发人员可以在没有 var_dump'ing 数组获取键名等情况下看到发生了什么。:)

于 2012-06-30T00:20:42.883 回答
-1

好的,以防万一有人可能需要知道可以做到这一点的更简单方法。这是运行良好的解决方案。

$result = array();  
foreach($result as $snode) { 

 foreach($snode as $key => &$val) {
  $val = mysql_real_escape_string($val);      
 }

$query = sprintf("INSERT INTO data_array_copy (
        CreditWeighting,
        TeachingPeriod,
        NoofStudents) 
                    VALUES ('%s')",implode("','",$snode));

mysql_query($query) or die (mysql_error());
echo $query. '<br />'; 
}

这很好用!

于 2012-06-30T01:51:22.087 回答