2013-09-10 09:10



I'm using PHP to connect to my db with mysqli. The query is made in Java code and send to my PHP script with JSON.

I have one query which is dynamic and made in my code so I can't use prepared statement.

For example I have in one time: SELECT x FROM y WHERE z = ? AND o =?. And in other time: SELECT x FROM y WHERE z = ? AND o =? and k = ? and j =?

It's by the user choice and I cant know what query will be.

My problem is that I'm exposed to SQL injection.

I thought about one step to protect my db from SQL injection and I want your opinion if it's a good idea or there is a better one. I thought about sending secret key to my PHP script and only if the key is good the SQL action will be.

For example:

if($key == "2fdgfg1sdjsdgj2JDSJDFSG2394KSDJG")
 // do SQL

This is what I use in my code. The user can select which car types he want to see from my DB.

In the Android application he have dialog in which he can select which car he want. Then I use this code in my java code:

                        int length = usersChecked.length;
                        String sqlQuery = "";
                        for (int i = 0; i < length; i++) {
                            if (usersChecked[i]) {
                                if (sqlQuery.equals(""))
                                    sqlQuery = " = " + list[i];
                                    sqlQuery = sqlQuery + " OR user = "
                                            + list[i];

                        favoritesQuery = "SELECT car, year, gas_type FROM cars_names WHERE user "
                                + sqlQuery
                                + " ORDER BY date DESC LIMIT ? , ?";
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • duanbu9345 duanbu9345 8年前

    The query is made in java code and send to my php script with JSON.

    This is what you're doing wrong.

    • The query shouldn't be of user choice
    • The query shouldn't be made in java (or rather javascript it is) code
    • The query shouldn't be sent with JSON

    The query have to be hardcoded in PHP script.

    At least you can create your query dynamically, based on the user's choice:

    $sql = "SELECT x FROM y WHERE z = ?";
    if (isset($json['o']))
        $sql .= " AND o =?";
        $values[] = $json['o']
    // and so on
    点赞 评论 复制链接分享