I'm trying to store some JSON data as string into database, but db_query change my JSON {} to table prefix.

So I have wrong JSON in DB as result.

How can I prevent such behavior?

1 Answer 1


You shouldn't be using db_query for inserts (the docs specifically say you shouldn't) but that's not actually the source of this problem.

You should use db_insert, and your data needs to be sent to the DB as a string.

// Mock json data -- notice it's stored as a string
$json_data = '[{
  "first_name": "Ralph",
  "last_name": "Wallace",
  "email": "[email protected]",

  'fieldcontainingjson' => $json_data,

Update in light of your comment stating that you can't use db_insert:

First, you should consider if db_merge() will work for you. But we won't argue that point and will just try to get this to work with db_query.

Make sure you're using placeholders correctly with db_query(). This should work:

$json_data = '[{
 "first_name": "Ralph",
 "last_name": "Wallace",
 "email": "[email protected]",

db_query('INSERT INTO {my_table} (fieldcontainingjson) VALUES (:json)', array(':json' => $json_data));

In the future it's considered best practices to share your code that's not working for you.

  • I cant use db_insert. Query uses structures that is unsupported by ORM. Like "INSERT ON DUPLICATE KEY UPDATE"
    – Braggae
    Commented Sep 1, 2015 at 15:51
  • @Braggae Updated my answer.
    – Aaron
    Commented Sep 1, 2015 at 16:01
  • Thanks @Aaron, after I started to use placeholders it work correctly.
    – Braggae
    Commented Sep 2, 2015 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.