为什么我的MySQL INSERT语句返回错误? PDOException SQLSTATE [42000]: [英] Why is my MySQL INSERT statement returning an error? PDOException SQLSTATE[42000]:

查看:197
本文介绍了为什么我的MySQL INSERT语句返回错误? PDOException SQLSTATE [42000]:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的mySQL有一个问题,我真的不知道发生了什么.我知道它与我的语法有关,但不完全相同.

I have an issue with mySQL that I don't really know what is going on. I know it has something to with my Syntax, but not exactly what.

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

推荐答案

喜欢,请使用参数绑定

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

之所以发生错误,是因为您直接在查询中插入了未经修饰和未引用的值.

The error is happening because you are directly inserting unsanitised and un-quoted values into your query.

进一步阅读

  • http://php.net/manual/pdo.prepare.php
  • http://php.net/manual/pdostatement.bindparam.php
  • http://php.net/manual/pdostatement.execute.php
  • http://php.net/manual/pdostatement.bindvalue.php

这篇关于为什么我的MySQL INSERT语句返回错误? PDOException SQLSTATE [42000]:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆