PHP insert with array values,tablename

旧街凉风 提交于 2019-12-02 17:01:13

问题


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

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.

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.

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?


回答1:


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

}


来源:https://stackoverflow.com/questions/34138058/php-insert-with-array-values-tablename

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!