简体   繁体   中英

PHP insert with array values,tablename

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?

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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