I am having a problem with this code. I looked into the issue and found no answer. When I run this code I get this:
username1username2{"username":"Username1", "username":"Username2"}

Instead of the desired result:
{"username":"Username1", "username":"Username2"}

Here is the code:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', '1');

    $db = mysql_connect('localhost', '', '');
    mysql_select_db("roblox");
    $query = "SELECT * FROM `bans`";
    $results = mysql_query($query);

    while ($row_users = mysql_fetch_array($results)) {
        //output a row here
        echo $row_users['username'];
        $users = array(
            'username' => $row_users['username']
        );
    }

    echo json_encode($users);
?>

Recommended Answers

All 3 Replies

Remove the code in line 12, which is echo $row_users['username']; and you shall get what you wish for.

commented: This is what happens when I code late at night. Thanks for helping! +2
Member Avatar for diafol

Instead of the desired result:

{"username":"Username1", "username":"Username2"}

Not sure if this makes much sense. You seem to be repeating a property instead of creating an array:

{"username":["Username1","Username2"]}

What is it you're after?

If you're still learning PHP, look into PDO.

Here is the code, rewritten with PDO.

<?php
    error_reporting(E_ALL); # DISABLE THIS WHEN IN PRODUCTION FOR THE LOVE OF GOD
    ini_set('display_errors', '1'); # DISABLE THIS WHEN IN PRODUCTION FOR THE LOVE OF GOD

    $db = new PDO('mysql:host=localhost;port=3306;dbname=roblox', 'user', 'pass');
    $sql = "SELECT * FROM `bans`";

    try {
        $results = $db->query($query);
    } catch (Exception $blah) {
        die("<pre>" . print_r($blah, true) . "</pre>");
    }

    while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
        //output a row here
        echo $row_users['username'];
        $users = [ // array() is no longer needed in PHP 5.6? up
            'username' => $row['username']
        ];
    }

    echo json_encode($users);

PS, you're lucky I'm helping you. I used to get a lot of hate from you on roblox when I played. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.