T-W
T-W

Reputation: 162

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?

Upvotes: 0

Views: 344

Answers (2)

lanzz
lanzz

Reputation: 43158

Well it clearly is not the same query you're trying in your PDO code and in the MySQL client — you have all your identifiers quoted in the client, while none are quoted in the PDO code.

Upvotes: 0

Pekka
Pekka

Reputation: 449385

group is a reserved word in mySQL.

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

Upvotes: 3

Related Questions