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

前端 未结 3 1891
梦毁少年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));
    
    0 讨论(0)
  • 2021-01-29 11:27
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    echo json_encode($row);
    

    You don't need the while loop, if you only have one row in your result.

    0 讨论(0)
  • 2021-01-29 11:30

    You only select needed fields, so you can just do

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

    EDIT: You mention now that name is unique, so above is all you need.

    0 讨论(0)
提交回复
热议问题