8

I'm writing a small web service in PHP and I'm having a bit of trouble getting my head around the following scenario.

My plan is to be able to send an array of data to a function, which would then build a query for MySQL to run. In the array I plan for the key to be the column name, and the value to be the value going in to the columns. i.e. $myData = array('userName'=>'foo','passWord'=>'bar'); $myClass = new users();

$myClass->addUser($myData);

Then, in my function I currently have:

function addUser($usrData){
   foreach($usrData as $col => $val){

      // This is where I'm stuck..

   }
}

Basically, I am wondering how I can separate the keys and values so that my query would become:

INSERT INTO `myTable` (`userName`,`passWord`) VALUES ('foo','bar');

I know I could probably do something like:

function addUser($usrData){
   foreach($usrData as $col => $val){
      $cols .= "," . $col;
      $values .= ",'".$val."'";
   }
}

But I thought there might be a more elegant solution.

This is probably something really simple, but I have never came across this before, so I would be grateful for any help and direction.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Dave
  • 1,076
  • 5
  • 15
  • 30

9 Answers9

7

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;";
}
Matt Bradley
  • 4,395
  • 1
  • 20
  • 13
  • @Rikudo - Out of curiosity, What is wrong with using the mysql_* functions? – Dave Aug 13 '11 at 16:27
  • 1
    They are (unofficially) deprecated, Much better alternatives exist such as MySQLi (Good) and PDO (Awesome). – Madara's Ghost Aug 13 '11 at 16:28
  • 1
    When you say "unofficially" deprecated, do you mean they are to be deprecated in the near future, or that it is not really best practice and that there are much better alternatives? - Just trying to understand the reasoning :) – Dave Aug 13 '11 at 16:31
  • Thanks Matt. I've used this along with my own sanitation functions and it's working great. PDO was not an option for me unfortunately. – Dave Aug 16 '11 at 10:26
3

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

gray_15
  • 411
  • 1
  • 7
  • 13
3

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)).
          "' )";
Satish
  • 696
  • 1
  • 11
  • 22
wadkar
  • 960
  • 2
  • 15
  • 29
1

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.

Brad
  • 159,648
  • 54
  • 349
  • 530
0

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

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.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

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)
?>
MikeRogers0
  • 721
  • 6
  • 14
  • can you not use `array_keys($array)` directly on `implode()` ? why do `foreach $key => $value` when you can get the respective keys and values using `array_keys($array)` and `array_values($array)` ? Please correct me if I am missing a point/doing something wrong – wadkar Aug 13 '11 at 16:37
  • Ah I totally forgot about array_keys/array_values when I was writing this - my bad. I'll update it asap. – MikeRogers0 Aug 18 '11 at 10:53
-1
//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)");
}
-1

How to insert bulk records in array format using mysqli insert query.

$i = 1;
$fields = '';
foreach($usrData as $col => $val){
    if($i < count($usrData)){
        $col = $this->conn->real_escape_string($col);
        $val = $this->conn->real_escape_string($val);
        $fields .= "`$col` = '".$val."'";
        $fields .= ', ';
        $i++;
    }else{
        $col = $this->conn->real_escape_string($col);
        $val = $this->conn->real_escape_string($val);
        $fields .= "`$col` = '".$val."'";
    }
}
$sqls = "INSERT INTO table_name SET $fields;"; 
$result = mysqli_query($this->conn, $sqls);
if($result){
    return $this->conn->insert_id;
}else{
    return false;
}
Antoine
  • 1,393
  • 4
  • 20
  • 26