zero-perfoliate
zero-perfoliate

Author Topic: Using JSON data in mysql_query()  (Read 156 times)

Offline collegemike

  • PHP Workers
  • **
  • Posts: 5
  • Karma: +0/-0
Using JSON data in mysql_query()
« on: August 06, 2010, 09:11:54 PM »
Dear All,

I'm writing a database abstraction layer in PHP which takes serialized JSON objects formatted as SQL commands, converts them to text, and then runs the query against a MySQL database and returns a JSON object containing the data.

When I run the code however with the simplest query I can think of (literally 'SELECT * FROM table') is returns this error:

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 'index' at line 1

The relevant code is below. Keep in mind parts irrelevant parts have been ommitted.

Making the JSON object

Code: [Select]
         $command = '{
"command" : "SELECT * FROM index",
"status" : null,
"message" : null,
"data" : {}
}';

Running the query

Code: [Select]
public function runCommand($JSONCommand = null){
//Check JSON for null
if(is_null($JSONCommand))
return null;

//Decode the command
$JSONCommand = json_decode($JSONCommand);

                        ...

                        //Connect to MySQL database
$mysql = mysql_connect($this->_hostDB,
$this->_userDB, $this->_passwordDB)
or die ("Can't connect to MySQL database " . $this->_hostDB);
mysql_select_db($this->_nameDB);

//Escape the command string
$command = mysql_real_escape_string($JSONCommand->{'command'});

//Run query
$query = mysql_query($command) or die (mysql_error());

                        ...
}

Offline collegemike

  • PHP Workers
  • **
  • Posts: 5
  • Karma: +0/-0
Re: Using JSON data in mysql_query()
« Reply #1 on: August 07, 2010, 03:07:06 AM »
Problem solved. It turns out 'index' is a keyword in SQL. I was able to fix the issue by placing tick marks (`) around index.

 

zero-perfoliate