sql >> Base de Datos >  >> RDS >> Mysql

Declaración de inserción múltiple de PDO

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

No es la sintaxis correcta

en su lugar puedes hacer:

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

o incluso

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

Sería más fácil ejecutarlo sin enlazar:

insertar datos

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;
}  

Pero si realmente necesita vincular, puede hacerlo de la siguiente manera:

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;
}

uso:

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