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 :(';
}