简体   繁体   English

PHP插入数组值,表名

[英]PHP insert with array values,tablename

I am struggling with a PHP insert statement. 我正在努力处理PHP插入语句。 I want it to insert data into the database by using array_keys($values) and array_values($values) . 我希望它通过使用array_keys($values)array_values($values)将数据插入数据库。

I have tried to work out how I can do this and so far I have this code in my insert and have also included my index page. 我试图弄清楚如何做到这一点,到目前为止,我的插入式代码中也包含了此代码,并且还包括了索引页。 I need to do it without changing the index page as it is a challenge I have to complete. 我需要在不更改索引页的情况下执行此操作,因为这是我必须完成的挑战。 I have analysed the index page and need to somehow make the function work with that to insert data into my database from the PHP insert command. 我已经分析了索引页,需要以某种方式使该函数与之配合使用,以便从PHP insert命令将数据插入到数据库中。

I also wonder if there's a way to wrap the PDO connection into one statement which I can use for this and other functions. 我还想知道是否有一种方法可以将PDO连接包装到一个可以用于此功能和其他功能的语句中。

Insert Function 插入功能

  <?php
function insert(array $values, $tablename)
{

    //cosntruct sql statment 


    $sql = "INSERT INTO $tablename $values";

    //pick apart vaules 


   //this line fetches the result set and fetch assoc to prevent multiple rows beign fetched 
    $ResultSet = dbconnect()->query($sql); 

   //returns the results 
   return $ResultSet;



    //array keys and array vaules


    //connection 



    // checks results 








} 

?>

Part of the Index page: 索引页面的一部分:

 if(isset($_POST['table']))
    {
        $tableName = $_POST['table'];
    }
    if(isset($_POST['insert']))
    {
        $values = array();
        $tableName = $_POST['tablename'];

        foreach($_POST as $key => $value)
        {
            if(!empty($value) && ($value != "Submit") && ($key != "insert") && ($key != "table") && ($key != "tablename"))
            {
                $values[$key] = $value;
            }
     } 
     $count = insert($values, $tableName);    
    }

Note that I am quite new at coding. 请注意,我是编码方面的新手。 Any suggestions? 有什么建议么?

try this, it works fine for me. 试试这个,对我来说很好。 You just have to pass the name of the table and an associative array which has the name of the columns as keys. 您只需要传递表名和一个以列名作为键的关联数组。

public function insert($table, $data)
{

    $query='INSERT INTO '.$table.' (';
    foreach($data as $key => $value)
    {
        $query .= $key.','; 
    }
    $query = substr($query, 0, -1);
    $query .= ') VALUES (';
    foreach($data as $key => $value)
    {
        $query .= ':'.$key.',';
    }
    $query = substr($query, 0, -1);
    $query .= ');';

    $insert = $this->db->prepare($query);
    $insert->execute($data);

}

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

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