I'm trying to create an entity (using entity->save()) in a hook_update_N function. The errors appear at the mysql insert query in the entity's insert function; the insert strings are wrapped in mysql_real_escape_string().

I get a series of warnings:

mysql_real_escape_string(): A link to the server could not be established mod_person.entity.inc:402

mysql_real_escape_string(): Access denied for user 'xxx'@'localhost' (using password: NO) mod_person.entity.inc:403

Followed by the error:

SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'val' at row 1 

When I remove the mysql_real_escape_string() from the mysql insert query code it works! However now I'm worried that leaves the server vulnerable.

My questions are:

[1] Why does using mysql_real_escape_string() work in normal site operation and not through hook_update_N?

[2] Do I need to use mysql_real_escape_string() with Drupal 7 database queries or is there another way?

I suppose I could remove the mysql_real_escape_string() for the update and then put them back but that feels like I'm missing the point somewhere.

Many thanks for any help.

  • Drupal 7 uses PDO, so none of the mysql_* functions should be used. The entity class needs to use db_insert, db_update, etc
    – Clive
    Commented Oct 16, 2015 at 17:22

1 Answer 1


Similar to what Clive said, you will want to use the Database API (db_update, db_insert) or use an Entity Metadata wrapper.

  • thanks - so I was using direct concatenation in the db_query() using mysql_real_escape_string(). Are you suggesting that I should be using the array of variables argument in db_query() to substitute variables into the query - and does that ensures security?
    – RobotEyes
    Commented Oct 19, 2015 at 16:18

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.