将数组插入mysql

时间:2012-06-29 23:58:41

标签: php sql

我的数组显示得像,但我似乎无法将其保存到数据库中。所以当我{$ 1}}而$ result是我的数组时,会显示以下内容

var_dump($result);

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

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)

2 个答案:

答案 0 :(得分: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数组来获取关键名称等。 :)

答案 1 :(得分:-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 />'; 
}

这很棒!