0

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);
?>

Edited by Djmann1013: Mistyped some things

4
Contributors
3
Replies
30
Views
2 Years
Discussion Span
Last Post by matrixdevuk
1

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

Votes + Comments
This is what happens when I code late at night. Thanks for helping!
0

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?

-1

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. ;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.