0

I'm working on a simple project where I'm collecting the JSON data from a register page and trying to insert in mysql database using prepared statement.

This is sample query after getting the details from form

INSERT INTO `registered_users`(`USER_EMAIL`, `USER_NAME`,`USER_PWD`, `ADDED_BY`) VALUES ('aaaa@aaa.ddd ','aaaaaaa','$2y$10$NEJFPvgnR/WhDkZKWChknOzfAe6Pzk.9LOYip9y36OOoyHDQKVFPm','aaaa@aaa.ddd') 

I checked manually by running this query , it got inserted which means there's no issue with insert statement , don't know what is the issue with prepared statement , please help .

Here's the code

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 * @author : Mahaveer
 * @date : 25/03/2018
 */

require_once 'database_connection.php';

class DBWebServices extends DBConnection {

    function insertUserData($register_json) {


        try {


            //decode json data to make array
            $json_data_array = json_decode($register_json, true);

            //reference : https://stackoverflow.com/questions/37367992/php-inserting-values-from-the-form-into-mysql
            //https://stackoverflow.com/questions/1290975/how-to-create-a-secure-mysql-prepared-statement-in-php
            //https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection

            $query = "INSERT INTO registered_users(`USER_EMAIL`,`USER_NAME`, `USER_PWD`, `ADDED_BY`) VALUES ((?),(?),(?),(?)); ";

            //prepare the stament
            $stmt = $this->connectDB()->prepare($query);


            if (!($stmt)) {
                echo "Prepare failed: (" . $stmt->errno . ") " . $stmt->error;
            }

            //Then start binding the input variables to the prepared statement:



            if (!$stmt->bind_param("ssss", $email, $name, $pwd, $modified_by)) {
                echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
            }



            $email = $json_data_array['register_user_email'];
            $name = $json_data_array['register_user_name'];
            $pwd = $json_data_array['user_password'];
            $modified_by = $json_data_array['register_user_email'];



            //Execute the query


            if (!($query_result=$stmt->execute())) {
                echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
            }


            if (!$query_result) {

                echo $stmt->error;
            }


            $stmt->close();
            //defining response in case of success or failure
            $response = array();

            if ($query_result) {
                // successfully inserted into database
                $response["success"] = 1;
                $response["message"] = "User successfully added.";
                // echoing JSON response
                echo json_encode($response);
            } else {
                //insert failed
                $response["success"] = 0;
                $response["message"] = "User cannot be added.";

                // echoing JSON response
                echo json_encode($response);
            }
        } catch (Exception $ex) {
            echo 'Exception occurred ' . $ex->getTraceAsString();
        }
    }

}

Code For Database connection :

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

    
class DBConnection {
    
    protected function connectDB() {
        // import database connection variables
        require_once './config.php';

        // Connecting to mysql database & choosing database
        $conn = new mysqli(DB_HOST, DB_USER_NAME, DB_PWD, DB_NAME);
        
        // Check connection
        if ($conn->connect_error) {
             die("Connection failed: " . $conn->connect_error);
               }
        
        echo 'Connection to database was successful....';
        return $conn;

    }    

}

Error stack trace produces following message :

Exception occurred #0 C:\xampp\htdocs\LockerWebApp\webservices_php\locker_web_services.php(62): mysqli_stmt->execute() #1 C:\xampp\htdocs\LockerWebApp\webservices_php\validate_n_submit_user.php(94): DBWebServices->insertUserData('{"register_user...') #2 C:\xampp\htdocs\LockerWebApp\user_registraion.php(7): include('C:\\xampp\\htdocs...') #3 {main} 

and Error Message is : mysql server has gone away which is weird.

I'm stuck here it's my first php project and due to this error I can not move forward...

  • do you get any errors? – Gobbin Mar 30 '18 at 07:36
  • No there's no error, that's what concerning me. – Mahaveer Prajapati Mar 30 '18 at 07:37
  • maybe there's some kind of silent transaction, that you simply have to commit? I'd trace DB server logs, and see what queries were actually executed. – murison Mar 30 '18 at 07:50
  • Thanks, I added the mentioned code, but no error produced. – Mahaveer Prajapati Mar 30 '18 at 07:53
  • @MahaveerPrajapati What is the output you get with `var_dump($query_result);`? And how do you get the current mysql connection handle to check for error messages? Specially the `$mysql->error` field. – Progman Mar 30 '18 at 08:03
  • Here's the dump of all variables : `$stmt = $this->connectDB()->prepare($query); var_dump($stmt);` .object(mysqli_stmt)#3 (10) { ["affected_rows"]=> int(0) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(9) ["field_count"]=> int(0) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) } `var_dump($bind_value);` bool(true) `var_dump($query_result);` bool(false) – Mahaveer Prajapati Mar 30 '18 at 08:28
  • @Progman I have defined a method in a class to connect to database and using the reference by extending it. ` class DBConnection { protected function connectDB() { // import database connection variables require_once './config.php'; // Connecting to mysql database & choosing database $con = new mysqli(DB_HOST, DB_USER_NAME, DB_PWD, DB_NAME) or die("Error in database connection".mysqli_error()); echo 'Connection to database was successful....'; return $con; } }` – Mahaveer Prajapati Mar 30 '18 at 08:29
  • @MahaveerPrajapati Save the connection you get with `connectDB()` in a variable and then run `var_dump($yourVariable->error);` to see the error message why the query/execute failed. – Progman Mar 30 '18 at 08:37
  • I think there's no error with db connection, I tried to take dump and it produced this result `$dbcon = $this->connectDB(); echo "Var DUMP of db object ..."; var_dump($dbcon->error);` Output : ...Var DUMP of db object ...string(0) – Mahaveer Prajapati Mar 30 '18 at 08:52
  • @MahaveerPrajapati Please edit your question to show the source code you have right now and the source code of your DBConnection class. Do not add it in the comment. And use the `connectDB()` method only once because it creates a new connection each time when used and the error message will most likely be in the other connection stored, when you have more than one connection. – Progman Mar 30 '18 at 09:18
  • @Progman , Hi I have added class which I have written for database connection, and it's getting used only once `$stmt = $this->connectDB()->prepare($query);` The problem is it does not even throw any error or warning. This is latest PHP which I'm using (7.2). – Mahaveer Prajapati Mar 30 '18 at 16:39
  • @MahaveerPrajapati The error message is in the `$dbcon->error` field. You have to save the connection you get from `$this->connectDB()` in a variable and use it for your prepared statement AND for getting the error message. – Progman Mar 30 '18 at 17:36
  • @Progman thanks ! I saved database connection to a variable and after executing the query I closed the connection , it really helped. I was in assumption that PHP automatically closes database connection after executing the query... Thank you so much... – Mahaveer Prajapati Mar 30 '18 at 18:57

2 Answers2

2

As per suggestion from @pragman I updated the code, I saved database connection to a variable and after executing the query closed the connection and it worked.

Here's the code snippet :

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 * @author : Mahaveer
 * @date : 25/03/2018
 */

require_once 'database_connection.php';

class DBWebServices extends DBConnection {

    function insertUserData($register_json) {


        try {


            //decode json data to make array
            $json_data_array = json_decode($register_json, true);

            //reference : https://stackoverflow.com/questions/37367992/php-inserting-values-from-the-form-into-mysql
            //https://stackoverflow.com/questions/1290975/how-to-create-a-secure-mysql-prepared-statement-in-php
            //https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection

            $query = "INSERT INTO registered_users(`USER_EMAIL`,`USER_NAME`, `USER_PWD`, `ADDED_BY`) VALUES ((?),(?),(?),(?)); ";
            
            $dbcon = $this->connectDB();

            //prepare the stament
            $stmt = $dbcon->prepare($query);


            if (!($stmt)) {
                echo "Prepare failed: (" . $stmt->errno . ") " . $stmt->error;
            }

            //Then start binding the input variables to the prepared statement:



            if (!$stmt->bind_param("ssss", $email, $name, $pwd, $modified_by)) {
                echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
            }



            $email = $json_data_array['register_user_email'];
            $name = $json_data_array['register_user_name'];
            $pwd = $json_data_array['user_password'];
            $modified_by = $json_data_array['register_user_email'];



            //Execute the query


            if (!($query_result=$stmt->execute())) {
                echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
            }


            if (!$query_result) {

                echo $stmt->error;
            }


            $stmt->close();
            $dbcon->close();
            //defining response in case of success or failure
            $response = array();

            if ($query_result) {
                // successfully inserted into database
                $response["success"] = 1;
                $response["message"] = "User successfully added.";
                // echoing JSON response
                echo json_encode($response);
            } else {
                //insert failed
                $response["success"] = 0;
                $response["message"] = "User cannot be added.";

                // echoing JSON response
                echo json_encode($response);
            }
        } catch (Exception $ex) {
            echo 'Exception occurred ' . $ex->getTraceAsString();
        }
    }

}
1
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 * @author : Mahaveer
 * @date : 25/03/2018
 */

require_once 'database_connection.php';
class DBWebServices extends DBConnection{


function insertUserData($register_json) {


    try{


    //decode json data to make array
    $json_data_array = json_decode($register_json,true);


echo $json_data_array['register_user_name'];
echo $json_data_array['register_secret_q'];
echo $json_data_array['register_secret_answer'];
echo $json_data_array['user_password'];
echo $json_data_array['userIPAddress'];
echo $json_data_array['timestamp'];
echo $json_data_array['timestamp'];
echo $json_data_array['register_user_email'];


    //reference : https://stackoverflow.com/questions/37367992/php-inserting-values-from-the-form-into-mysql
    //https://stackoverflow.com/questions/1290975/how-to-create-a-secure-mysql-prepared-statement-in-php
    //https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection

    $query = "INSERT INTO registered_users(USER_EMAIL,USER_NAME,SECRET_Q,SECRET_A,USER_PWD,USER_IP,TIMESTAMP,LAST_MODIFIED,ADDED_BY) 
                  VALUES (?,?,?,?,?,?,?,?,?) ;";


    //prepare the stament
    $stmt = $this->connectDB()->prepare($query);



    $bind_value=$stmt->bind_param("sssssssss", $json_data_array['register_user_email'],
                          $json_data_array['register_user_name'],
                          $json_data_array['register_secret_q'],
                          $json_data_array['register_secret_answer'],
                          $json_data_array['user_password'],
                          $json_data_array['userIPAddress'],
                          $json_data_array['timestamp'],
                          $json_data_array['timestamp'],
                          $json_data_array['register_user_email']);  

    if(!$bind_value){

        echo "Is problem with bind values?: (" . $bind_value->errno . ") " . $bind_value->error;
    }


    //Execute the query
    $query_result = $stmt->execute();
    $stmt->close();

   //defining response in case of success or failure
    $response = array();

    if($query_result){
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "User successfully added.";
        // echoing JSON response
        echo json_encode($response);

    }else {
        //insert failed
        $response["success"] = 0;
        $response["message"] = "User cannot be added.";

        // echoing JSON response
        echo json_encode($response);


    }

    } catch (Exception $ex) {
        echo 'Exception occurred '.$ex->getTraceAsString();

    }    

}   


}
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98