简体   繁体   English

如何在php中将数组值作为键值对插入到数据库表中

[英]How to insert array values to a database table as key value pairs in php

I am using array where I insert data to a table call z_error_log.我正在使用数组,将数据插入到调用 z_error_log 的表中。 These inserted data gives me an output as follows in the table under the column 'data'.这些插入的数据在“数据”列下的表中为我提供了如下输出。

(user_role,email,nic,password,payment,reg_date)=(2,dfghjkbhjn@gmail.com,123456789045,$2y$10$R4MOTLHlhe1M9GCt0utxQO3d43oFrH.34ivCPPtHpral.cM/kW5sq,0,2020-01-13 14:44:27)

But What I actually need to do is, to insert those data to the table where it stored as follows.但我真正需要做的是,将这些数据插入到存储如下的表中。

user_role = 2,email=dfghjkbhjn@gmail.com,nic=123456789045,password=$2y$10$R4MOTLHlhe1M9GCt0utxQO3d43oFrH.34ivCPPtHpral.cM/kW5sq,payment,reg_date=2020-01-13 14:44:27

I need to assign the value right after its name as in the above.我需要在其名称后立即分配值,如上所示。

Here I add the Part of the class Vendor_cont and function in the Log_model.php file where I use to enter data to the z_error_log table.在这里,我在 Log_model.php 文件中添加了 Vendor_cont 类的 Part 和函数,我用来将数据输入到 z_error_log 表中。

================Vendor_cont.php==================== ================Vendor_cont.php====================

class Vendor_cont
{

//CLASS Content

  }
            }

            // ===================EDITED If Recaptcha Fail=====================================

             else {

                             $userData = array(
                             'user_role'=>'2',
                             'email' => $email,
                             'nic' => $nic,
                             'password' =>$password,
                             'payment' =>0,
                             'reg_date' =>date('Y-m-d H:i:s')
                          );

                $_SESSION['Emessages'] = 'Recaptcha Failed. Please try again later'; 

                $this->LModel->createErrorLog(3,'Vendor_cont/register_vendor/recaptcha_fail',$email,$userData);


                }

        //========================================================================================

}

==================Log_model.php================== ==================Log_model.php==================

    public function createErrorLog($user,$function,$error_data,$data_obj){ 

            $ip=$_SERVER['REMOTE_ADDR'];
            $browser_os=  $_SERVER['HTTP_USER_AGENT'];

            $data= (array) $data_obj;

            // print_r($data);

            if (is_array($data)) {
                $val = '(' . implode(',', array_keys($data)) . ')';
                $val .= '=(' . implode(',', $data) . ')';
            } else {
                $val = $data;
            }


    // =============EDITED==============

            $oStmt= $this->oDb->prepare('INSERT INTO z_error_log (`function`, `error_data`,`data`,`user` ,`ip`,`browser_os`) VALUES (:function,:error_data,:data,:user,:ip,:browser_os)');
            $oStmt->bindParam(':function', $function, \PDO::PARAM_STR);
            $oStmt->bindParam(':error_data', $error_data, \PDO::PARAM_STR);
            $oStmt->bindParam(':data', $val, \PDO::PARAM_STR);
            $oStmt->bindParam(':user', $user, \PDO::PARAM_INT);
            $oStmt->bindParam(':ip', $ip, \PDO::PARAM_STR);
            $oStmt->bindParam(':browser_os', $browser_os, \PDO::PARAM_STR);
            $oStmt->execute();

            return  $this->oDb->lastInsertId();

        }

I really appreciate your help.我真的很感谢你的帮助。 Thanks in advance.提前致谢。

Please modify your createErrorLog() function using below code.请使用以下代码修改您的 createErrorLog() 函数。 I hope you can get your desired output by using this.我希望您可以通过使用它来获得所需的输出。

$email = "test@gmail.com";
$nic ="nic";
$password ="Pass@123";

$userData = array(
     'user_role'=>'2',
     'email' => $email,
     'nic' => $nic,
     'password' =>$password,
     'payment' =>0,
     'reg_date' =>date('Y-m-d H:i:s')
);
foreach($userData as $key=>$val) {
    $finalValue .= $key.'='.$val.',';
}
echo rtrim($finalValue,",");

Replace your createErrorLog() function in your model file with below code and you are done.Remember to create data column in database as text type and pass the value as string.用下面的代码替换模型文件中的 createErrorLog() 函数,你就完成了。记住在数据库中创建数据列作为文本类型并将值作为字符串传递。

public function createErrorLog($user,$function,$error_data,$data_obj){ 
        $ip=$_SERVER['REMOTE_ADDR'];
        $browser_os=  $_SERVER['HTTP_USER_AGENT'];
        $data= (array) $data_obj;

        foreach($data as $key=>$val) {
            $finalValue .= $key.'='.$val.',';
        }
        $val = rtrim($finalValue,",");

        // =============EDITED==============
            $oStmt= $this->oDb->prepare('INSERT INTO z_error_log (`function`, `error_data`,`data`,`user` ,`ip`,`browser_os`) VALUES (:function,:error_data,:data,:user,:ip,:browser_os)');
            $oStmt->bindParam(':function', $function, \PDO::PARAM_STR);
            $oStmt->bindParam(':error_data', $error_data, \PDO::PARAM_STR);
            $oStmt->bindParam(':data', $val, \PDO::PARAM_STR);
            $oStmt->bindParam(':user', $user, \PDO::PARAM_INT);
            $oStmt->bindParam(':ip', $ip, \PDO::PARAM_STR);
            $oStmt->bindParam(':browser_os', $browser_os, \PDO::PARAM_STR);
            $oStmt->execute();
            return  $this->oDb->lastInsertId();
    }

MySQL does not understand array so either you can convert into json or add every data into seperate column For adding in seperate column you could use implode with column names could do the trick. MySQL 不理解数组,因此您可以转换为 json 或将每个数据添加到单独的列中对于添加单独的列,您可以使用带有列名的 implode 可以解决问题。 Your posted question is quite huge, can you trim it with dummy code Also refer this你发布的问题非常大,你能用虚拟代码修剪它吗?也参考这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM