PHP Variable in Select Statement

前端 未结 7 586
滥情空心
滥情空心 2021-01-13 17:50

I\'ve written this PHP-Script which is working, and now I want to change the row name into a variable to (not sure if row is correct), I mean the \"name\" from the selec

7条回答
  •  难免孤独
    2021-01-13 18:19

    I believe you are confusing matters (unintentionally) due to your use of the word 'row'. Judging by your example you mean field/column. It sounds like you wish to specify the fields to select using a variable which can be done by any of these methods...

    $fields = "name, age";
    
    $sql = "SELECT $fields FROM table";
    $sql = "SELECT {$fields} FROM table";
    $sql = "SELECT ".$fields." FROM table";
    

    NB it is important that you have secure date in the $fields element, I would suggest using a whitelist of allowed values i.e.

    // assuming $_POST['fields'] looks something like array('name','age','hack');
    $allowed = array('name', 'age');
    $fields = array();
    
    foreach ($_POST['fields'] as $field) {
       if (in_array($field, $allowed)) {
          $fields[] = $field;
       }
    $fields = implode(', ', $fields);
    

提交回复
热议问题