简体   繁体   中英

PHP PDO MySQL Insert error, but works as direct query on MySQL

Im using PHP PDO to let my Android app talk to a MySQL database.

Here's my PHP file:

<?php
$pdo = new PDO("mysql:host=x;dbname=x", "x", "x");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "INSERT INTO k_user_groep(group, user, rol) VALUES (?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($_GET['groupid'], $_GET['user'], $_GET['rol']));
?>

The table is designed as follows: groupid references a unique index in other table, user references a primary key in other table, rol references nothing.

Directly in MySQL the following query works:

INSERT INTO `k_user_groep`(`group`, `user`, `rol`) VALUES ('1', 'test', 'v');

This is my call on the PHP file:

x.php?groupid=1&user=test&rol=v

It returns the following:

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 MySQL server version for the right syntax to use near 'group, user, rol) VALUES ('1', 'test', 'v')' at line 1' in x.php:7 Stack trace: #0 x.php(7): PDOStatement->execute(Array) #1 {main} thrown in x.php on line 7

Any advice?

group is a reserved word in mySQL.

It works in your second example because you're wrapping the column name in backticks.

显然,这与您在PDO代码和MySQL客户端中尝试的查询不同—您在客户端中引用了所有标识符,而在PDO代码中没有引用任何标识符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM