-2

私はこれまでにこれを試しました...

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

4 に答える 4

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');
于 2012-10-05T12:46:06.000 に答える
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 インジェクションを防ぐことです。

于 2012-10-05T12:47:33.160 に答える
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);
    }
   }
于 2012-10-05T12:48:38.223 に答える
-1

// ここに何か

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

値について:

return "'" . implode( "','", $this->values ) . "'";
于 2012-10-05T12:43:45.743 に答える