1

I want to create a global function insert. i have a code like this

    function insert_data($table, $field = array(), $data = array())
{
    $sql = "INSERT INTO ".$table." (";

    $i = 0;
    for($f=0; $f < count($field); $f++)
    {
        $sql .= ++$i === count($field) ? $field[$f] : $field[$f].", ";
    }
    $sql .= ") VALUES (";
    for($d=0; $d < count($data); $d++)
    {
        $sql .= end($data) === $data[$d] ? (is_string($data[$d]) ? $this->db->escape($data[$d]) : (is_null($data[$d]) ? "NULL" : $data[$d])) : (is_string($data[$d]) ? $this->db->escape($data[$d])."," : (is_null($data[$d]) ? "NULL," : $data[$d].","));
    }
    $sql .= ")";

    $qry = $this->db->query($sql);
    return $this->db->affected_rows();
}

it's work fine for me, but i want the parameters just the name of table and data with index is name of field. how to create like that? thanks for the answer

Zulyantara
  • 53
  • 1
  • 5
  • To be honest, I would either use a framework (Phalcon, Symfony, etc...) with a proper ORM that already exists or do something that's *not* universal, that you can swap out depending on the database server since different database servers have differing levels of ANSI compliance : http://stackoverflow.com/questions/3602617/database-engines-and-ansi-sql-compliance - and that can affect how you build the queries. – CD001 Nov 11 '15 at 10:14
  • @CD001 Well, yes, and you can use a real programming language like Python and not filthy PHP, but that's the way it is. – Amarnasan Nov 11 '15 at 10:23
  • @Amarnasan nah - I hate significant whitespace; I was trying to be helpful (not snarky) in highlighting that there may be a better way to approach the problem with PHP... that's why it was a comment, not an answer. – CD001 Nov 11 '15 at 10:28
  • @CD001 Yes, but when I see this kind of questions I visualize a desperate person trying to finish his task as fast as possible, and then comes people saying things like "What you should do is stop using mysql_* because it is deprecated and use PDO". That really enerves me. – Amarnasan Nov 11 '15 at 10:32

1 Answers1

0

This will do. Modify the beginning of the function, the rest stays the same:

function insert_data($table, $datas = array()){

    foreach($datas as $key => $value) {
        $field []= $key;
        $data []= $value;
    }

    $sql = "INSERT INTO ".$table." (";
    .
    .
    .
Amarnasan
  • 14,939
  • 5
  • 33
  • 37
  • so query insert is not inside of foreach? #sorry for my english, i'm from indonesian :) – Zulyantara Nov 11 '15 at 10:17
  • No, it is not inside: I just added the last line to show you where the foreach is placed inside the function (the beginning) – Amarnasan Nov 11 '15 at 10:22