PHP插入数组值,表名 [英] PHP insert with array values,tablename

查看:67
本文介绍了PHP插入数组值,表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力处理PHP插入语句.我希望它通过使用array_keys($values)array_values($values)将数据插入数据库中.

I am struggling with a PHP insert statement. I want it to insert data into the database by using array_keys($values) and array_values($values).

我试图弄清楚该如何做,到目前为止,我在插入物中已经包含了这段代码,并且还包含了我的索引页.我需要在不更改索引页的情况下执行此操作,因为这是我必须完成的挑战.我已经分析了索引页,需要以某种方式使该函数与之配合使用,以便通过PHP insert命令将数据插入到数据库中.

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.

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

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.

插入功能

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

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

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

}

这篇关于PHP插入数组值,表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆