json data parsing?

So i have 2 scripts

one to pull information from the database
in php format and one that sends/receives the data in unity.
the php appears as SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
in the browser

and in unity it appears as a parse error in the debug

<?php

include_once 'dbconnect.php';


$user_name = $_POST['user'];
   
$user_name = strip_tags($user_name);

$query = "SELECT user FROM user WHERE user='$user_name'";
$result = mysqli_query($dbconnection ,$query);

$row = mysqli_fetch_row($result);
if ($row)
{
    $dataArray = array('success' => true, 'error' => '', 'user' => "$user_name",);
} else
{
    $dataArray = array('success' => false, 'error' => 'Invalid email or password.', 'email' => "");
}


header('Content-Type: application/json');
echo json_encode($dataArray);

?>

this is the unity portion

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;


[Serializable]
public class playername
{
    public bool success;
    public string error;
    public string user;
}

public class setstats : MonoBehaviour {


    public string username;
    public string xpamount;
    public int xp;
    public string[] stats;


    // Use this for initialization
    IEnumerator Start()
    {
        username = GetComponent<list>().username;
        WWWForm form = new WWWForm();
        form.AddField("user", username);
        WWW statsdata = new WWW("http://localhost/PHP/getstats.php", form);
        yield return statsdata;
        if (string.IsNullOrEmpty(statsdata.error))
        {
            playername player = JsonUtility.FromJson<playername>(statsdata.text);

            if (player.success == true)
            {
                if (player.error != "")
                {
                    Debug.Log(player.error);
                }
                else
                    Debug.Log("user has been found");
            }
            if (string.IsNullOrEmpty(statsdata.error))
            {
                Debug.Log(statsdata.error);

            }

        }

        else
        {
        }


    }

    string GetstatsValue(string stats, string index)
    {
        string Value = stats.Substring(stats.IndexOf(index) + index.Length);
        if (Value.Contains("|")) Value = Value.Remove(Value.IndexOf("|"));
        return Value;
    }

    // Use this for initialization


    // Update is called once per frame
    void Update () {
       
    }
}

Are you sure $dataArray is valid? Try printing out the result of json_encode to the PHP error log with error_log:

error_log(json_encode($dataArray));

to check that it’s valid.

-sam

this is the raw data i get from the php script when activated in a web browser

success

<b>Notice</b>:  Undefined index: user in <b>C:\xampp\htdocs\PHP\getstats.php</b> on line <b>6</b>



<b>Warning</b>:  mysqli_query() expects parameter 1 to be mysqli, boolean given in <b>C:\xampp\htdocs\PHP\getstats.php</b> on line <b>11</b>



<b>Warning</b>:  mysqli_fetch_row() expects parameter 1 to be mysqli_result, null given in <b>C:\xampp\htdocs\PHP\getstats.php</b> on line <b>13</b>

{"success":false,"error":"Invalid email or password.","email":""}

since no user is given should it not be returning the error Invalid email or password?

Your PHP scripts has errors in it which are being returned to the client. You should fix those errors and ensure you return only a valid json string. That entire text that you see in the browser is what is being parsed by JsonUtility in Unity.

-sam

does the fact im using xampp change anything about the formatting?

No, there’s an error in your PHP script. The output is telling you the error message: “Undefined index: user”.

You’re indexing into the $_POST array trying to look up a value with the key “user” but it doesn’t exist. So you’re not POSTing the right data to the site.

Are you trying to just view the site in a browser, ie you’re doing an HTTP GET? That won’t work - your code is expecting data to be submitted to it via HTTP POST. If you didn’t realise that, then it sounds like you need to read a few PHP and HTTP tutorials first :slight_smile:

-sam

the value user is being sent from unity. but from my understanding i should be receiving the error
{“success”:false,“error”:“Invalid email or password.”,“email”:“”} anytime i try to access it in the browsers

anyways i attempted to debug the unity script and the from user debugs as

UnityEngine.WWWForm
UnityEngine.Debug:Log(Object)
<Start>c__Iterator0:MoveNext() (at Assets/Scripts/setstats.cs:30)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

As I said you can’t just view the site in a browser by accessing the url. You need to POST to the server (e.g. using Postman).

In Unity, after your yield statement, try logging statsdata.text and statsdata.error to the console to see what error you get.

-sam

this is the return i get when i debug the statsdata.text

ArgumentException: JSON parse error: Invalid value.
UnityEngine.JsonUtility.FromJson[playername] (System.String json) (at C:/buildslave/unity/build/artifacts/generated/common/modules/JSONSerialize/JsonUtilityBindings.gen.cs:25)
setstats+<Start>c__Iterator0.MoveNext () (at Assets/Scripts/setstats.cs:36)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

dbconnect looks like this incase your wondering

<?php

$dbuser ='root';
$dbpassword = '';
$db = 'accounts';
$dbhost ='localhost';
$dbport = '3306';

$dblink = mysqli_init ();
$dbconnection = mysqli_real_connect($dblink, $dbhost, $dbuser, $dbpassword, $db, $dbport);

if($dbconnection)
{
    print("success");
    }else{
        die("connection failed" . mysql_error());
    }
?>

That’s a json parse exception, are you sure you logged the text and error to the console? Directly under the ‘yield’ put these two lines:

Debug.Log(statsdata.text);
Debug.Log(statsdata.error);

-sam

when i debug statsdata.error i receive this

Null
UnityEngine.Debug:Log(Object)
<Start>c__Iterator0:MoveNext() (at Assets/Scripts/setstats.cs:34)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

Ok what about statsdata.text?

-sam

ArgumentException: JSON parse error: Invalid value.
UnityEngine.JsonUtility.FromJson[playername] (System.String json) (at C:/buildslave/unity/build/artifacts/generated/common/modules/JSONSerialize/JsonUtilityBindings.gen.cs:25)
setstats+<Start>c__Iterator0.MoveNext () (at Assets/Scripts/setstats.cs:36)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

No I mean what is the contents of statsdata.text? Paste the output from Debug.Log(statsdata.text);

-sam

with just the debugs placed there these are the only errors/information that show up in the console

success

<b>Warning</b>:  mysqli_query() expects parameter 1 to be mysqli, boolean given in <b>C:\xampp\htdocs\PHP\getstats.php</b> on line <b>11</b>


UnityEngine.Debug:Log(Object)
<Start>c__Iterator0:MoveNext() (at Assets/Scripts/setstats.cs:32)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
Null
UnityEngine.Debug:Log(Object)
<Start>c__Iterator0:MoveNext() (at Assets/Scripts/setstats.cs:33)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
ArgumentException: JSON parse error: Invalid value.
UnityEngine.JsonUtility.FromJson[playername] (System.String json) (at C:/buildslave/unity/build/artifacts/generated/common/modules/JSONSerialize/JsonUtilityBindings.gen.cs:25)
setstats+<Start>c__Iterator0.MoveNext () (at Assets/Scripts/setstats.cs:37)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

Ok firstly, in dbconnect.php you are printing out “success” which you shouldn’t be doing. You don’t want to print out any other text; you should only print out the json text that you want to decode.

Secondly you have another bug in dbconnect.php. This error message gives you the hint:

mysqli_query() expects parameter 1 to be mysqli, boolean given

That’s because of this code in dbconnect.php:

$dbconnection = mysqli_real_connect($dblink, $dbhost, $dbuser, $dbpassword, $db, $dbport);

mysqli_real_connect returns a bool not a db connection object, and you’re passing that to mysqli_query. Also when you call mysqli_query you should do it like this:

mysqli_query($dblink, etc..);

i.e. pass in the $dblink

-sam

thanks so much for your help its all working now and i learned some new stuff about php