How to hide column from my database using json_encodage in PHP

I have a database that I fetch in a json_encode in PHP, but I would like to hide a column. I have too many column to call in my SQL request, that's why I've just did a : SELECT *. So, I would like to hide login and password column, for example.

$bdd = $connect->query("
SELECT * FROM dmlog.dm LEFT JOIN dmlog.users ON users.id_user = dm.id_used
");
$rows = array();
while ($r = $bdd->fetch()) {
    $rows[] = $r;
}
json_encode($rows);

2 answers

  • answered 2020-03-25 13:38 Illya

    Just unset login and password before you insert it to $rows array

    while ($r = $bdd->fetch()) {
        unset($r["login"]);
        unset($r["password"]);
        $rows[] = $r;
    }
    

  • answered 2020-03-25 19:46 user3783243

    You need to use PDO::FETCH_ASSOC so you don't get two sets of each record. With this parameter passed to the fetch you will only get back an associative array, the column will be the index. You can then pass the ones you don't want into an unset.

    $bdd = $connect->query('SELECT * FROM dmlog.dm LEFT JOIN dmlog.users ON users.id_user = dm.id_used');
    $rows = array();
    while($r = $bdd->fetch(PDO::FETCH_ASSOC)) {
        unset($r["login"], $r["login_pass"], $r["login_email"]); //remove login, Login_email, and password from the return
        $rows[] = $r; 
    }
    echo json_encode($rows);