gpt4 book ai didi

php - 新手问题: PDO and MYSQL INSERT Query problem

转载 作者:可可西里 更新时间:2023-11-01 08:00:12 24 4
gpt4 key购买 nike

我正在尝试更加安全并开始使用 PDO 和准备好的语句。这是向我推荐的,我已经在这两个网站上阅读过: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/http://webdevrefinery.com/forums/topic/1272-your-mysql-code-sucks

我碰壁了,我不明白为什么以下内容不起作用。我正在尝试插入一行(以记录 404 错误)。我已经阅读了有关命名和未命名占位符的信息,我认为命名占位符方法更易于维护。我也第一次尝试使用“try”和“catch”。所有这些对我来说都是全新的,所以请善待!我没有收到任何错误,但代码没有更新数据库 - 我返回了零行。

代码如下:

$referer = $_SERVER['HTTP_REFERER'];
$domainName = "http://domain.com";
$_dtNow = date("d-m-Y H:i:s");
$_referer = $domainName.$_SERVER['REQUEST_URI'];
$_thisPage = $domainName.$url;
$_ip = $_SERVER['REMOTE_ADDR'];
$_host = $_SERVER['REMOTE_HOST'];
if(isset($_SERVER['HTTP_USER_AGENT'])) {$_ua = $_SERVER['HTTP_USER_AGENT'];} else {$_ua = "unset";}

$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = 'databaseName';
$username = 'username';
$password = 'password';
// Construct the DSN, or "Data Source Name". Really, it's just a fancy name
// for a string that says what type of server we're connecting to, and how
// to connect to it. As long as the above is filled out, this line is all
// you need :)
$dsn = "mysql:host=$host;port=$port;dbname=$database";

try {
// Connect!
$db = new PDO($dsn, $username, $password);
$data = array(
'dateTime' => $_dtNow,
'referer' => $_referer,
'page' => $_thisPage,
'ip' => $_ip,
'host' => $_host,
'ua' => $_ua
);
$statement = $db->prepare("INSERT INTO 404s (dateTime, referer, page, ip, host, ua) value (:dateTime, :referer, :page, :ip, :host, :ua)");
$statement->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}



?>

最佳答案

您确定表名是 404s 吗?这听起来像是一个不正确的标识符。

 INSERT INTO 404s (dateTime, referer, page, ip, host, ua) value (:dateTime, :referer, :page, :ip, :host, :ua)

尝试:

 INSERT INTO `404s` (dateTime, referer, page, ip, host, ua) value (:dateTime, :referer, :page, :ip, :host, :ua)

`404s` 周围使用反引号

注意请记住,构造如:

create table `404` ( `33` integer);

有效。

当您构建复杂的请求时,使用 ` 对于避免某种痛苦的 SQL 错误非常有用,尤其是当您从内省(introspection)算法格式化请求时。

像表、列和数据库一样需要保护。

关于php - 新手问题: PDO and MYSQL INSERT Query problem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6357642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com