user8072194
user8072194

Reputation:

JSON.parse return multiple values for single keys

I have a table set up in a mysql database.. firstName, lastName, email, password, allow, allow.

I loaded a fake person into and i'm testing XMLHttpRequest() funcionality.

For some reason instead of returning data like this:

[{"firstName":"Theodore","lastName":"Roosevelt","email":"[email protected]","password":"12345678","active":"N","allow":"Y"}]

It's returning data like this:

[{"firstName":"Theodore","0":"Theodore","lastName":"Roosevelt","1":"Roosevelt","email":"[email protected]","2":"[email protected]","password":"12345678","3":"12345678","active":"N","4":"N","allow":"Y","5":"Y"}]

I can't figure out why it's duplicating and numbering values. Here is my super simple html/js:

<body>
    <div id="results">
        <button type="button">Get Data</button>
    </div>
</body>

<script>
    $("button").click(function(){
        $.ajax({url: "selectTest.php", success: function(result){
            $("#results").html(result);
        }});
    });
</script>

And here are my php files (one calls a function in another):

First:

<?php
include('config.php');
include('web_db_operations.php');
$email = '[email protected]';
echo getAllUserInfo_userTable($email);
?>

Second:

function getAllUserInfo_userTable(string $email){
    include 'config.php';
    $sql = 'SELECT * FROM userTable WHERE email= :email';
    $stmt = $conn->prepare($sql);       
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->execute();
    $getResults = $stmt->fetchAll();
    $myJSON = json_encode($getResults);
    return $myJSON;
    }

I've been using session variables up to this point, but I would like to start learning how to do things asynchronously and this is all new to me.

Thank you.

Upvotes: 0

Views: 307

Answers (1)

Musa
Musa

Reputation: 97717

fetchAll() returns the columns by both name and index by default, see here, you have to specify one if you don't want that.
To only get the names use,

$getResults = $stmt->fetchAll(PDO::FETCH_ASSOC);

Upvotes: 1

Related Questions