A better way to generate this json array from MySql data with php

前端 未结 3 1892
梦毁少年i
梦毁少年i 2021-01-29 10:56

Sql fiddle for your convenience here.

I\'m taking data from a MySql table and turning it into a json array. All works well and I have the output the way I want it, but i

3条回答
  •  执笔经年
    2021-01-29 11:17

    Taking out all the redundancy, using proper prepared statements (assuming PDO) and adding error handling (at least a stub), you end up with this:

    $stmt = $conn->prepare('SELECT name, age, address, pincode FROM json WHERE name = ?');
    $stmt->execute(array('peter'));
    
    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo json_encode($row);
    } else {
        echo json_encode(array('status' => 'error'));
    }
    

    If you expect multiple rows:

    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    

提交回复
热议问题