PDO - passing a field name as a variable

后端 未结 2 1534
粉色の甜心
粉色の甜心 2021-01-13 17:39

I\'m just migrating my code from mysql_query style commands to PDO style and I ran into a problem. THe old code looked like this :

$query_list_menu = \"SELE         


        
2条回答
  •  有刺的猬
    2021-01-13 18:11

    If $_GET['section_name'] contains a column name, your query should be:

    $query_list_menu = "SELECT " . $_GET['section_name'] . " from myl_menu_hide_show WHERE id=:id";
    

    Giving:

    $query_list_menu = "SELECT :section_name from myl_menu_hide_show WHERE id=:id";
    $result_list_menu = $db->prepare($query_list_menu);
    $result_list_menu->bindValue(':id', $_GET['id'] , PDO::PARAM_INT);  
    $result_list_menu->execute();
    

    The reason is that you want the actual name of the column to be in the query - you'd changed it to be a parameter, which doesn't really make much sense.

    I'll also add that using $_GET['section_name'] directly like this is a massive security risk as it allows for SQL injection. I suggest that you validate the value of $_GET['section_name'] by checking it against a list of columns before building and executing the query.

提交回复
热议问题