使用表作为变量表或动态表将PHP数组插入MySQL

时间:2018-06-27 08:07:58

标签: php mysql mysqli mysql-insert-id

我有一个php数组:

$cont_array = Array("613:m-ent:id=one","930:m-lk:id=one;x=180;y=79;which=1","1080:m-lev:id=one;");

我想将其插入到具有表名作为变量的MySQL表中,例如$table_name = "user1"

此外,我想用第一个":"来破坏每个数组元素。执行我的php代码后,我得到的只是一个空表。

我需要帮助。这是我的代码:

<?php
$connection = mysqli_connect('localhost','root','','prueba');

$cont_array = Array("613:m-ent:id=one","930:m-clk:id=one;x=180;y=79;which=1","1080:m-lev:id=one;");
$table_name = "user1";


$sql_1 = "DROP TABLE IF EXISTS `".$table_name."`;";
$sql_1 .= "CREATE TABLE `".$table_name."` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `usercod` varchar(20) NOT NULL DEFAULT '',
        `pid` varchar(1000) NOT NULL DEFAULT '',
        `name` varchar(1000) NOT NULL DEFAULT '',
        `time` varchar(1000) NOT NULL DEFAULT '',
        `all_act` varchar(1000) NOT NULL DEFAULT '',
        PRIMARY KEY (`id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;";

mysqli_multi_query($connection,$sql_1);


foreach ($cont_array as $row){
    $break_e = explode(':', $row, 2);
    $sql="INSERT INTO`".$table_name."` (usercode,pid,name,time,all_act) VALUES ("user","pid_value","user_name",'$break_e [0]','$break_e [1]');";
    mysqli_query($connection,$sql);
}
?>

这就是我得到的: This is what I get:

这就是我想要得到的: This is what I would like to get:

1 个答案:

答案 0 :(得分:0)

您的SQL似乎在SQL语句下面有问题检查。

$sql = "INSERT INTO $table_name (usercod,pid,name,time,all_act) VALUES  ('user','pid_value','user_name','".$break_e [0]."','".$break_e [1]."')";