我将一些值传递给php文件,然后应该使用PDO将数据插入MySQL表中。 这是文件:
<?php
function makeInsert($query, $paramArray){
include 'db.php';
try {
$pdo = new PDO("mysql:host=localhost;dbname=$db_name", $db_user, $db_pass);
$stmt = $pdo->prepare($query);
foreach($paramArray as $k => $v){
$stmt->bindParam($k, $v, PDO::PARAM_STR);
}
$stmt->execute();
return $stmt;
} catch (PDOException $e) {
$error = "Error!: " . $e->getMessage();
return $error;
die();
}
}
?>
我从这个函数调用makeInsert:
<?php
include "./insert.php";
function run(){
$registration = "success";
$ammountInput= "12.34";
$kanalInput= "9";
$datumInput = "08.2017";
$datumArray = explode(".", $datumInput);
if ($registration == "success"){
$response_array['status'] = 'success';
$indexnameYear = ":year";
$indexnameMonth = ":month";
$indexnameAmount = ":amount";
$indexnameChannel = ":channel";
$parameter = array($indexnameYear => $datumArray[1], $indexnameMonth => $datumArray[0], $indexnameAmount => $ammountInput, $indexnameChannel => $kanalInput);
$insertIncomeQuery = "INSERT INTO `income`(`id`, `year`, `month`, `amount`, `channel`) VALUES (NULL, " . $indexnameYear . ", ". $indexnameMonth .", ". $indexnameAmount .", ". $indexnameChannel .")";
//make the insert :-)
$returnValue = makeInsert($insertIncomeQuery, $parameter);
if($returnValue === "Success"){
echo "All done.";
}else if (strpos($returnValue, "Error!") !== false){
echo "Sorry!:" . $returnValue;
}
}else{
echo "something happened";
}
}
?>
当我调用run()函数时,它会向我插入一条记录到我的数据库中,如下所示:
正如您所看到的ID正确(自动增量值),但所有其他值都不是我在run()
函数中提供的值。看来参数列表中的最后一个值kanalInput
是9
)用于每个其他参数。
在我的逻辑中,我的foreach声明只能出错,但我不知道为什么。
有人暗示我如何解决这种奇怪的行为吗?