如何在执行pdo预处理语句时为命名变量创建函数?

时间:2017-05-23 03:44:31

标签: php mysql pdo

我的问题是:创建一个可以处理命名变量的函数是否可行,所以我不需要逐个描述$stmt->execute(array());中的变量。我的意思是什么变量的例子:

:categoryId=> $categoryId;

MyProject:

$stmt = $connect->prepare('INSERT INTO category (categoryName, categorySort) VALUES (:categoryName, :categorySort)');
            $stmt->execute(array(
                ':categoryName' => $categoryName,
                ':categorySort' => $categorySort,
                ));

来自Akintunde的Fucntion我已经改变了:

    function doSave($array, $table) {
if (count($array) == 0) {
    throw new Exception('Array cant be empty');
} else {
    //prepare the query first
    $prepare_1 = 'INSERT INTO' . '`' . $table . '`'; //start preparing
    $columns = array();
    foreach ($array as $key => $value) {
        $columns[] = ':' . $key . ','; //gets all columns and add commas
    }
    //now you can combine everything and prepare
    $connect->prepare($prepare_1 . ')(VALUES(' . $columns . ')'); //remember to add the values. also test this section as its not tested
    foreach ($array as $key => $value) {
        $connect->bindParam(':' . $key, $value, PDO::PARAM_STR);
    }
    $connect->execute();
}
}

使用它:

$array = array('categoryName' => ':categoryName', 'categorySort' => 'categorySort');
$connect->doSave($array, 'category');

这里有错误:

Fatal error: Call to undefined method PDO::doSave() in C:\xampp\htdocs\program\admin\add-category.php on line 38

我忘记改变什么或遗失什么?

如果问题不明确,请提醒我。

0 个答案:

没有答案