php - 为什么我的 MySQL INSERT 语句返回错误? PDOException SQLSTATE[42000] :

标签 php mysql pdo insert

我的 mySQL 遇到问题,我真的不知道发生了什么。我知道它与我的语法有关,但不确切是什么。

if(isset($_POST['newBtn'])) {
// Check that everything has values and something has been changed
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$title = $_POST['title'];
$smalldesc = $_POST['smalldesc'];
$fulldesc = $_POST['fulldesc'];
// username = $admin
// date = getdate(today in unix time stamp)
date_default_timezone_set('UTC');
$date = new DateTime();
$date = $date->getTimestamp();
if("Testing form. Not relevant.") {
    echo "<div class='alert alert-warning'>You submitted blank data somewhere, or did not change any data from it's default.</div>";
} else {
    $sqladd = "INSERT INTO theories(theory_name,small_desc,full_desc,author,create_date) VALUES ($title,$smalldesc,$fulldesc,$admin,$date)";
    try {
    $sth = $dbh->query($sqladd);

    echo "<div class='alert alert-success'><b>Success!</b>You Have created a new theory that is availible for viewing to the public.</div>";
} catch(PDOExecption $e) {
echo "<div class='alert alert-error'><b>Error!</b>Could not add to database.<br />". $e->getMessage() ."</div>";
}
}
}

我收到此错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax
error or access violation: 1064 You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use near 'Form,I 
shouldn't be having this much of an issue with php.,I really hate when PH' at line 1' in 
/srv/http/mt-chillad/users/admin-theories.php:42 Stack trace: #0 /srv/http/mt-
chillad/users/admin-theories.php(42): PDOStatement->execute() #1 {main} thrown in 
/srv/http/mt-chillad/users/admin-theories.php on line 42

最佳答案

哎呀,使用参数绑定(bind)

try {
    $stmt = $sbh->prepare('INSERT INTO theories(theory_name,small_desc,full_desc,author,create_date) VALUES (?, ?, ?, ?, ?)');
    $stmt->execute([$title,$smalldesc,$fulldesc,$admin,$date]);

    // and so on

发生错误的原因是您直接将未经清理和未加引号的值插入到查询中。

进一步阅读

关于php - 为什么我的 MySQL INSERT 语句返回错误? PDOException SQLSTATE[42000] :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672870/

相关文章:

php - 无法在 AFS 的 linux 终端上更改 http 写入权限?

mysql - 使用前缀和总和连接表

mysql - 资源 ID #22 已插入数据库字段

php - 简单的 MYSQL 查询后无法访问用户的名字

php - pdo 检索数据并填充记录

PHP PDO - bindValue PARAM_BOOL 作为字符串

php - 在 PHP 和 PDO 中创建异常以防止重复

php - 获取字符串php中的日期

php - 未使用 Referrer-Policy 设置 header

PHP 5.6.2 + Postgres + Apache 2.4 不适用于 Yosemite