PHP 插入数组值,表名

PHP insert with array values,tablename

我正在努力处理 PHP 插入语句。我希望它使用 array_keys($values)array_values($values).

将数据插入数据库

我已经尝试弄清楚如何做到这一点,到目前为止,我的插入内容中有这段代码,并且还包含了我的索引页。我需要在不更改索引页的情况下执行此操作,因为这是我必须完成的挑战。我已经分析了索引页,需要以某种方式使该函数与其一起工作,以便从 PHP 插入命令将数据插入我的数据库。

我也想知道是否有一种方法可以将 PDO 连接包装到一个语句中,我可以将其用于此功能和其他功能。

插入函数

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








} 

?>

索引页的一部分:

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

请注意,我在编码方面还很陌生。有什么建议吗?

试试这个,对我来说效果很好。您只需传递 table 的名称和一个以列名作为键的关联数组。

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

}