如何进行完整的动态插入查询?

时间:2012-10-05 12:38:21

标签: php dynamic insert

到目前为止我已尝试过这个......

class Test {

public $table = 'users'
public $fields = ('id', 'username', 'password');
public $id = "";
public $username = "yousufiqbal";
public $password = "123456";

public function fields_to_string(){
    foreach ($fields as $field) {
        // some stuff here
    }
}

public function properties_to_string(){
    // some stuff here
}

public function insert(){
    global $dbh;
    $sql = "INSERT INTO {$this->table} ($this->fields_to_string()) VALUES ($this->properties_to_string());";
    $dbh->exec($sql);
}

}

4 个答案:

答案 0 :(得分:2)

我会这样做:

class Test {

    public $table;
    public $fields;
    public $values;

    public function __construct($fields, $values, $table){
        $this->fields = $fields;
        $this->values = $values;
        $this->table = $table;
    }

    public function fields_to_string(){
        return "`".implode("`, `", $this->fields)."`";
    }

    public function properties_to_string(){
        return "'".implode("', '", $this->values)."'";
    }


    public function insert(){
        global $dbh;
        $sql = "INSERT INTO `{$this->table}` (".$this->fields_to_string().") VALUES (".$this->properties_to_string().");";
        $dbh->exec($sql);
        echo $sql; // for test purposes
    }
}

$fields = array('username', 'password');
$values = array('Mihai', 'stackoverflow');

$test = new Test($fields, $values, 'users');
$test->insert();

// INSERT INTO `users` (`username`, `password`) VALUES ('Mihai', 'stackoverflow');

答案 1 :(得分:1)

将字段值作为数组可能更好。这个例子可以帮助您:

class Test
{    
  public $table = 'users';
  public $fields = array( 'id', 'username', 'password' );
  public $values = array( "", "yousufiqbal", "123456" );

  public function insert()
  {
    global $dbh;
    $fields = '`' . implode( '`,`', $this->fields ) . '`';
    $values = implode( ',', $this->values );
    $sql = "INSERT INTO `$this->table` ( $fields ) VALUES ( $values )";
    $dbh->exec( $sql );
  }    
}

下一步是实现参数绑定,以防止SQL注入!

答案 2 :(得分:1)

    class Test {
     public $fields = array('id', 'username', 'password');
     public $properties = array('id' => "", 'username' => "yousufiqbal",'password' =>"123456");
     public function fields_to_string(){        
       $fields_str = implode(',', $this->fields);  
       return $fields_str;
    }

   public function properties_to_string(){
      $properties_str = implode(',', "'".$this->properties."'"); 
      return $properties_str;
    }

   public function insert(){
    global $dbh;
    $sql = "INSERT INTO `{$this->table}` ($this->fields_to_string()) VALUES ($this->properties_to_string());";
    $dbh->exec($sql);
    }
   }

答案 3 :(得分:-1)

//这里的一些东西

return implode( ',', $this->fields );

对于值:

return "'" . implode( "','", $this->values ) . "'";