PDO多插入语句

时间:2014-06-22 00:29:19

标签: php mysql pdo

我有一个单个输入字段的工作插入,但当我尝试添加更多时,它似乎打破了一切。我有一个数据库连接工作正常,当我更改“isset”以使其中断3列时,正确地包含在页面顶部。

这是我的陈述声明;

if(isset($_POST['title, question, tags']))
{
$success = insertData('questions', 'title', $_POST['title']);
$success = insertData('questions', 'question', $_POST['question']);
$success = insertData('questions', 'tags', $_POST['tags']);
if(!$success)
    echo 'Sorry failed :(';
}

我从函数php文件中调用的函数;

function insertData($tablename, $columnName, $value)
{
$sql = 'INSERT into '.$tablename.'('.$columnName.') VALUES(:Value)';
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql);
$statement->bindValue(":Value", $value, PDO::PARAM_STR);

$bReturn = false;

try
{
    $statement->execute();
    $bReturn = true;
}
catch(PDOExecption $e)
{
    echo $e->getMessage();
}
return $bReturn;
}

有谁知道我在哪里出错?

1 个答案:

答案 0 :(得分:2)

if(isset($_POST['title, question, tags']))

语法不正确

你可以这样做:

if(isset($_POST['title']) && isset($_POST['question']) && isset($_POST['tags']))

甚至

if(isset($_POST['title'], $_POST['question'], $_POST['tags']))

在没有绑定的情况下执行它会更容易:

<强> insertData

function insertData($tablename, $params){
//build query string
$column_string = implode(',', array_keys($params));
$value_string = implode(',', array_fill(0, count($params), '?'));
$sql_string = "INSERT INTO {$tablename} ({$columnString}) VALUES ({$value_string})";
//prepare query
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql_string);

//execute query
$success = $statement->execute(array_values($params));

//return boolean success
return $success;
}  

但是如果你真的需要绑定,可以通过以下方式实现:

function insertDataBind($tablename, $params){
//build query string
$column_string = implode(',', array_keys($params));
$value_string = implode(',:', array_keys($params));
$sql_string = "INSERT INTO {$tablename} ({$column_string}) VALUES (:{$value_string})";
//prepare query
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql);
//bind 
    foreach($params as $key=>$value){
        $statement->bindValue($key, $value);
    }
//execute query
$success = $statement->execute();

//return boolean success
return $success;
}

<强>用法:

if(isset($_POST['title'], $_POST['question'], $_POST['tags'])){

$params = array('title' => $_POST['title'],
                'question'=>$_POST['question'],
                'tags'=>$_POST['tags']
                );

$success = insertData('questions', $params);

if(!$success)
    echo 'Sorry failed :(';
}