2015-05-09 134 views
-1

我想知道在类中创建函数是否有一种很好的方法,以便于插入/删除/更新mysql查询。在INSERT,DELETE和UPDATE类中创建动态函数

例如

比方说,我有一个包含12行的表,我想和两个值插入查询从另一个类中。插入函数的外观如何?我希望这个函数能够处理任何数量的值。

function addUser($email, $password) { 

    $values = array(
     "email" => $email, 
     "password" => $password 
    ); 

    $table = 'users'; 
    $query = $mysql->insert($values, $table); 
} 

function insert($values, $table) { 
    // what would this look like? (note: this function is within another class. 
} 

我希望最终的和预处理语句执行查询,像:

if($stmt = $this->db->prepare($query)) { 
     $stmt->bind_param('ss', $email, $password); 
     $stmt->execute(); 

     if($stmt->fetch()) { 
      $stmt->close(); 
      return true; 
     } 
    } 
+0

不要这样做。这是个好主意,但最好不要编写自己的工具,而应该使用已经存在的,例如教义。 –

回答

0
class Mysql 
{ 
    public static function insert($values, $table) 
    { 
     if(empty($values) || empty($table)) 
     { 
      // Noting to do 
      return ""; 
     } 

     $list = array(); 

     foreach($values as $k => $v) 
      $list[] = "`". $k ."` = '". $v ."'"; 

     $list = implode(",", $list); 
     $query = "INSERT INTO `". $table ."` SET " . $list; 
     return $query; 
    } 
} 

$values = array 
(
    "email" => "my email", 
    "password" => "my password" 
); 

$table = 'users'; 
$query = Mysql::insert($values, $table); 

echo $query; 

没有理由,因为所有的数据是静态的在这里使用的构造函数。 但是如果你愿意的话,就请从static插入功能 和初始化的MySQL这样的:

$mysql = new Mysql(); 
$mysql->insert($values, $table); 
相关问题