Solved

PHP not converting to JSON format.

Posted on 2014-12-24
11
136 Views
Last Modified: 2016-05-26
I already have a existing working PHP code that is a login program. This is for a Android Application. So now I want to display the data in the database (MYSQL from my backend server). I am trying to get the information form a particular table in to JSON format so that my listview will be able to show the data.

But I am trying to prepare the php for the data to be converted to JSON format and having some issues.

my List_View.php (the one that I am facing problem presently)

<?php
/** Old code
$host="XXXXX"; //replace with database hostname 
$username="XXXXX"; //replace with database username 
$password="XXXXX"; //replace with database password 
$db_name="XXXXXX"; //replace with database name
 **/

 //private $db;

    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct() {

    }


/**$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");*/
//mysql_select_db("") or die ("cannot select DB");
$sql = "select  bet_id , bet_name, bet_brief, bet_description from bets"; 
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result))
{
while($row=mysql_fetch_assoc($result))
{
    $json['bets'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 
?> 

Open in new window


DB_Connect.php

<?php
class DB_Connect {

    // constructor
    function __construct() {

    }

    // destructor
    function __destruct() {
        // $this->close();
    }

    // Connecting to database
    public function connect() {
        require_once 'include/config.php';
        // connecting to mysql
        $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        // selecting database
        mysql_select_db(DB_DATABASE);

        // return database handler
        return $con;
    }

    // Closing database connection
    public function close() {
        mysql_close();
    }

}

?>

Open in new window


DB_functions.php (This is another php file which is used for user registration and it is using the same DB_Connect working perfectly fine with out any issues with username or acess denied.

<?php

class DB_Functions {

    private $db;

    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct() {

    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password, $preferred_name) 
    {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$salt', NOW())");
        // check for successful store
        if ($result) {
            // get user details 
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
            return mysql_fetch_array($result);
        } else {
        echo mysql_error();
            return false;
        }
    }

    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {
        $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
        // check for result 
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            $salt = $result['salt'];
            $encrypted_password = $result['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $result;
            }
        } else {
            // user not found
            return false;
        }
    }

    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $result = mysql_query("SELECT email from users WHERE email = '$email'");
        if(!$result){
            return false;
        }

        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed 
            return true;
        } else {
            // user not existed
            return false;
        }
    }

     /**
     * Check user is betExists or not
     */
    public function isbetExists($betName) {
        $result = mysql_query("SELECT bet_name from bets WHERE bet_name = '$betName'");
        if(!$result){
            return false;
        }

        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // bet exists 
            return true;
        } else {
            // bet doesnot exist
            return false;
        }
    }

    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) 
    {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password)
    {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

    /**
     * Adding new bet (my new code)
     */
     public function createNewBet($betname, $betbrief, $betdescription, $betvalue)
     {
        //$uid = uniqid('',true);
        $bet_id = uniqid('',true);
        $result = mysql_query("INSERT INTO bets(bet_name,bet_brief,bet_description) VALUES('$betname','$betbrief','$betdescription')");
         // check for successful store
        if ($result) {
            // get user details 
            $bet_id = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM bets WHERE betid = $bet_id");
            // return user details
            return mysql_fetch_array($result);
        } else {
        echo mysql_error();
            return false;
        }


     }
     /*
         public function storeUser($name, $email, $password, $preferred_name) 
    {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$salt', NOW())");
        // check for successful store
        if ($result) {
            // get user details 
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
            return mysql_fetch_array($result);
        } else {
        echo mysql_error();
            return false;
        }
    }*/



}

?>

Open in new window


config.php

<?php

/**
 * Database config variables
 */
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASSWORD", "subtle");
define("DB_DATABASE", "secret_db");
?>

Open in new window

But when I open the page of List_View.php this is what I get.

Warning: mysql_query(): Access denied for user 'bharath'@'localhost' (using password: NO) in /home1/bharath/public_html/android_login_api/include/List_View.php on line 30

Warning: mysql_query(): A link to the server could not be established in /home1/bharath/public_html/android_login_api/include/List_View.php on line 30

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home1/bharath/public_html/android_login_api/include/List_View.php on line 33

Warning: mysql_close() expects parameter 1 to be resource, null given in /home1/bharath/public_html/android_login_api/include/List_View.php on line 40 []

It is definetly the same file working presently for registering and enabling registered users to login, so it is not username or password wrong for sure. I am unable to figure out the syntax error appreciate any assistance, tks.
0
Comment
Question by:jackandjill2014
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +1
11 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 40517257
Access denied for user 'bharath'@'localhost'
Well either the user is not known or it requires a password which you are not passing

The other errors are a result of the above

Your code is a bit confusing, looks like you are trying to query a database that you are not even connected to.

Maybe your config file is being included after you attempt to connect to the db
0
 

Author Comment

by:jackandjill2014
ID: 40517259
Well that is the thing, the same file is working for DB_Functions so what is the difference for the List_View?
0
 
LVL 58

Expert Comment

by:Gary
ID: 40517260
See the amended comment.
There is no logic that we can follow as to how your files relate to each other.
0
 Database Backup and Recovery Best Practices

Join Percona’s, Architect, Manjot Singh as he presents Database Backup and Recovery Best Practices (with a Focus on MySQL) on Thursday, July 27, 2017 at 11:00 am PDT / 2:00 pm EDT (UTC-7). In the case of a failure, do you know how long it will take to restore your database?

 

Author Comment

by:jackandjill2014
ID: 40517263
HI Gary,
I guess that is basic php, if you see the line
require_once 

Open in new window


in DB_Connect and DB_Functions and also in List_View.php which means they are so called importing that class or php code. So please see that and you will be able to find the link VERY CLEARLY.
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 40517266
In List_View.php, the function __construct() is not part of a class and so anything in it is never ever called or used.  It does not matter that you used require_once because that code is never called.  The previous code on lines 26, 27, and 28 are commented out so they don't run either.
0
 
LVL 58

Expert Comment

by:Gary
ID: 40517268
Well if you had bothered to read my comment you would have seen
either the user is not known or it requires a password
instead of being snarky and expecting someone to read through nearly 300 lines of code.

The BIG clue using password: NO means the password is not being passed so something is wrong with the loading order or code logic

But obviously you know PHP better than I so I will leave you to it.
0
 

Author Comment

by:jackandjill2014
ID: 40517269
Thats right, right before you said that, I changed my code to be in a class, please see the edited List_View.php and I am getting the following error now.

<?php
/** Old code
$host="XXXXX"; //replace with database hostname 
$username="XXXXX"; //replace with database username 
$password="XXXXX"; //replace with database password 
$db_name="XXXXXX"; //replace with database name
 **/

class ListView
{

 private $db;

    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct() {
        
    }


/**$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");*/
//mysql_select_db("") or die ("cannot select DB");
$sql = "select  bet_id , bet_name, bet_brief, bet_description from bets"; 
$result = mysql_query($sql);
$json = array();
 
if(mysql_num_rows($result))
{
while($row=mysql_fetch_assoc($result))
{
	$json['bets'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 
}

?> 

Open in new window


ERROR
Parse error: syntax error, unexpected '$sql' (T_VARIABLE), expecting function (T_FUNCTION) in /home1/bharath/public_html/android_login_api/include/List_View.php on line 32
0
 

Author Comment

by:jackandjill2014
ID: 40517270
Gary, one look in my List_View.php just ONE LOOK you could tell what Dave said, IT IS NOT IN A CLASS. I guess it is better leave it to me then, since you have to go thru 300 lines of code to spot a silly mistake which only takes 2 lines of code on top of the question.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 40517596
The PHP Parse error: syntax error, unexpected ... means that something is wrong "upstream" in the PHP script file.  Usually this sort of error is caused by mismatched parentheses or braces, missing semicolons, etc.  In this case the error occurs because the script defines a variable inside a class, but not inside a class method. You may find that if you line up your control structures (curly braces) and indent the script properly, these sorts of errors will be easier to spot.

<?php
/** Old code
$host="XXXXX"; //replace with database hostname 
$username="XXXXX"; //replace with database username 
$password="XXXXX"; //replace with database password 
$db_name="XXXXXX"; //replace with database name
 **/

class ListView
{
    private $db;

    //put your code here
    // constructor
    public function __construct() 
    {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    public function __destruct() {
        
    }


    /**$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
    mysql_select_db("$db_name")or die("cannot select DB");*/
    //mysql_select_db("") or die ("cannot select DB");
    $sql = "select  bet_id , bet_name, bet_brief, bet_description from bets"; // <- ILLEGAL! YOU CANNOT DEFINE A VARIABLE INSIDE A CLASS
    $result = mysql_query($sql);
    $json = array();
 
    if(mysql_num_rows($result))
    {
        while($row=mysql_fetch_assoc($result))
        {
            $json['bets'][]=$row;
        }
    }
    mysql_close($con);
    echo json_encode($json); 
}

Open in new window

Since you're going to have to get off of MySQL (because PHP is doing away with MySQL support) you may want to read this article.  It shows the basic usage of MySQL and maps the familiar but obsolete MySQL extension to the supported data base extensions.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

In a moment I'll try post a new code example to show you how you might run this script in a way that will give you meaningful error messages.
0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 40517609
This might work better.  Obviously I cannot test it because I do not have your database, but it's probably correct in principle.  Plug in your credentials on lines 28-31 and give it a try.  Note that you do not need any object-oriented programming for something this simple.  At this level, a simple procedural script will be fine.
<?php // temp_jackandjill2014.php

// ALWAYS USE THE HIGHEST POSSIBLE ERROR REPORTING
ini_set('display_errors', TRUE);
error_reporting(E_ALL);

/**
 * References that must be understood to use PHP and MySQL(i)
 *
 * http://php.net/manual/en/mysqli.overview.php
 * http://php.net/manual/en/class.mysqli.php
 * http://php.net/manual/en/class.mysqli-stmt.php
 * http://php.net/manual/en/class.mysqli-result.php
 * http://php.net/manual/en/class.mysqli-warning.php
 * http://php.net/manual/en/class.mysqli-sql-exception.php <-- DID NOT WORK PHP 5.3+, MySQL 5.1+
 * http://php.net/manual/en/mysqli.construct.php
 * http://php.net/manual/en/mysqli.real-escape-string.php
 * http://php.net/manual/en/mysqli.query.php
 * http://php.net/manual/en/mysqli.errno.php
 * http://php.net/manual/en/mysqli.error.php
 * http://php.net/manual/en/mysqli.insert-id.php
 * http://php.net/manual/en/mysqli-result.num-rows.php
 * http://php.net/manual/en/mysqli-result.fetch-array.php
 * http://php.net/manual/en/mysqli-result.fetch-object.php
 */

// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";

// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);

// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
    $err
    = "CONNECT FAIL: "
    . $mysqli->connect_errno
    . ' '
    . $mysqli->connect_error
    ;
    trigger_error($err, E_USER_ERROR);
}

// CONSTRUCT A QUERY STRING
$sql = "SELECT  bet_id, bet_name, bet_brief, bet_description FROM bets";

// RUN THE QUERY AND TEST FOR SUCCESS - OR SHOW A MESSAGE IF THE QUERY FAILS
if (!$res = $mysqli->query($sql))
{
    $err
    = 'QUERY FAILURE:'
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    . ' QUERY: '
    . $sql
    ;
    trigger_error($err, E_USER_ERROR);
}

// RETRIEVE THE ROWS AND APPEND THEM TO AN ARRAY
while ($row = $res->fetch_object())
{
    $data['bets'][] = $row;
}

// ACTIVATE THIS TO SEE WHAT THE DATA LOOKS LIKE
// var_dump($data);

// WRITE THE JSON REPRESENTATION OF THE ARRAY
echo json_encode($data);

Open in new window

0

Featured Post

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses how to create an extensible mechanism for linked drop downs.
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question