Build insert query from array MySQL and PHP

依然范特西╮ 提交于 2019-11-29 14:49:21

Try this:

function addUser($usrData) {
   $count = 0;
   $fields = '';

   foreach($usrData as $col => $val) {
      if ($count++ != 0) $fields .= ', ';
      $col = mysql_real_escape_string($col);
      $val = mysql_real_escape_string($val);
      $fields .= "`$col` = $val";
   }

   $query = "INSERT INTO `myTable` SET $fields;";
}

EDIT:
Oops ! forgot quotation around VALUES( ), removing the old code

$query = "INSERT INTO `mytable` ( ".
          mysql_real_escape_string(implode(array_keys(' , ', $userData))).
          ") VALUES ( '".
          mysql_real_escape_string(implode("' , '", $userData)).
          "' )";

FYI, your code is wide open to SQL injection currently.

Use prepared queries with PDO. You can define your parameter names, and just pass an associative array to do the inserting.

You won't be able to stick an arbitrary array in there, as you will need to name your parameters appropriately (such as :userName instead of userName), but I don't think you want to do that anyway.

My Bigginer (Easy) way to do it. It needs some refactoring, but it's quiet understandable for me.

public function insertArr( $table, $paramsArr) {

    $sql = "INSERT INTO {$table} (";
    foreach ( $paramsArr as $name=>$value ) {
        $sql .="`$name`,";
    }

    $sql = substr($sql, 0, strlen($sql)-1);
    $sql .= ") VALUES (";
    foreach ($paramsArr as $name => $value){
        $value === null? $sql .= "null," : $sql .= "'$value',";
    }
    $sql = substr($sql, 0, strlen($sql)-1);
    $sql .= ");";

    $this->link->query($sql);
    return $this->link->affected_rows;
}

Elegant solution:

function create_insert_query($tablename, $array) {
    $key = array_keys($array);
    $val = array_values($array);
    //sanitation needed!
    $query = "INSERT INTO $tablename (" . implode(', ', $key) . ") "
         . "VALUES ('" . implode("', '", $val) . "')";

    return($query);
}

How about this one?

function addUser($usrData){
   $query = "INSERT INTO `myTable` (`userName`, `passWord`) VALUES (:userName, :passWord);";
   $stmt = $pdo->prepare($query);
   foreach($usrData as $col => $val){

      $stmt->bindValue(':'.$col, $val);

   }
   $stmt->execute();
}

It should do the job for you.

Here is the code I tend to use for an insert query:

<?php
// Extend the PDO class, adding support for array to query binding
class db extends pdo{

// This makes the SQL insert query
function insert($keyValue){ 
    if(is_array($keyValue)){
        foreach($keyValue as $key => $value){
            $fields[] = '`'.$key.'`';
            $values[] = ':'.$key;
        }

        return '('.implode(' , ',$fields).') VALUES '.'('.implode(' , ',$values).')';
    }
    return '';
}

// Change the key to be :key to stop injections
function bind($keyValue){
    if(is_array($keyValue)){
        foreach($keyValue as $key => $value){
            if(is_array($value)){ // if the value is array, lets assume I want an OR statement.
                $count = -1;
                foreach($value as $sValue){
                    $count++;
                    $where[':'.$key.$count] = $sValue;
                }
            } else {
                $where[':'.$key] = $value;
            }
        }
        return $where;
    }
    return array();
}
}

// It can be used like
try {
    // Call the PDO class (Connect to the database).
    $db= new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $pass);
} catch(PDOException $e) {
    // If something goes wrong, PDO throws an exception with a nice error message.
    echo $e->getMessage();
}

// The values you want to Add
$values = array('username' => $username, 'otherdata' => $otherdata);

$db->prepare('INSERT INTO `users` '.$db->insert($values).';') // The SQL statement.
->execute($db->bind($values)); // Bind the values to the query (Stopping SQL injections)
?>
//This Will Help You To Insert Data Into Database by Array

$myData = array('user'=>'foo','name'=>'bar','player'=>'Sachin');
$get->adddd('tabelname',$myData);


function insert($tabel,$usrData) {
$count = 0;
$fields = '';
foreach($usrData as $col => $val) {
  if ($count++ != 0) $fields .= ', ';
  if($count==1){
    $field .= $col;
    $value .= "'".$val."'";
  }
  else{
     $field .= ','.$col;
     $value .= ",'".$val."'";  
      }
  $fields .= "`$col` = $val";
 }
mysql_query($query = "INSERT INTO $tabel ($field) VALUES ($value)");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!