簡體   English   中英

PHP已准備好的語句未在mysql數據庫中插入數據

[英]PHP Prepared statement not inserting data in mysql database

我正在一個簡單的項目中,在該項目中,我從注冊頁面收集JSON數據,並嘗試使用准備好的語句插入mysql數據庫中。

這是從表單獲取詳細信息后的示例查詢

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') 

我通過運行此查詢手動進行了檢查,它已插入,這意味着insert語句沒有問題,不知道prepared語句有什么問題,請幫助。

這是代碼

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

數據庫連接代碼:

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

錯誤堆棧跟蹤產生以下消息:

 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} 

錯誤消息是: mysql server has gone away這很奇怪。

我被困在這里,這是我的第一個php項目,由於這個錯誤,我無法前進...

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

    }    

}   


}

根據@pragman的建議,我更新了代碼,將數據庫連接保存到變量中,並在執行查詢后關閉了連接並正常工作。

這是代碼片段:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM