0

ok so im continuing on my journey of learning to adapt to PDO and also OOP and at a slow rate.

Here is my issue. im trying to create a function to handle updates to mysql, it feels so complicated to the point i would be just as well to type it out manually. I will be doing a lot of handling big updates from forms so i wanted to make this function reusable but i think i way over complicated it, is there a more concise way while also keeping the code easy to review?

this is my update function:

 // take data from arrays, loop through and print each out
 // concatenate this onto SET and concatenate the where clause
 // on the end unless there is no criteria in which case print nothing
 public function update_sql($table="users",$update_array,$criteria=""){

 $sql = 'UPDATE `'.$table.'` SET ';
 $sqlFieldParams = array();       
 // creating an array with `user_id` = :user_id etc etc
 foreach ($update_array as $fieldName => $fieldValue) {
     $sqlFieldParams [] = $fieldName . '= :' . $fieldName;
 }

 // concatenate but don't print where if there is no criteria passed
 $sql .= implode(', ', $sqlFieldParams) . ($criteria ? ' WHERE ' . $criteria : "");
 $this->query("$sql");
 }

my function to bind and execute which i also use for insert and other statements that need binding.

 public function bind_execute($bind_array){
 // bind the values
 foreach ($bind_array as $field => $item) {
     $this->bind(':'.$field,$item);
 }

 // execute the update
 $this->execute();
 }

and a couple more reusable functions that are used in this script just for reference

    // prepare our SQL Queries
public function query($query){
    $this->stmt = $this->dbh->prepare($query);
}

// use switch to select the appropriate type for the value been passed
// $param = placeholder name e.g username, $value = myusername
public function bind($param, $value, $type = null){
    if (is_null($type)) {
        switch (true) {
            case is_int($value):
                $type = PDO::PARAM_INT;
                break;
            case is_bool($value):
                $type = PDO::PARAM_BOOL;
                break;
            case is_null($value):
                $type = PDO::PARAM_NULL;
                break;
            default:
                $type = PDO::PARAM_STR;
        }
    }
// run the binding process
$this->stmt->bindValue($param, $value, $type);
}

// execute the prepared statement
public function execute(){
    return $this->stmt->execute();
}

And now my monstrous update statement

 $this->user_id = $_GET['id'];
 $this->user_activation_hash = $_GET['verification_code'];

 // create an array to pass these values to be set to the update function
 $update_array = array(
 'user_active'               => '1',
 'user_activation_hash'      => 'NULL',
 );

 // create the where clause
 $criteria = 'user_id = :user_id AND user_activation_hash = :user_activation_hash';

 // create the update statement
 // pass in values table, array & criteria
 $database->update_sql('users',$update_array,$criteria);

 // these are other values that need binding from the where clause
 $criteria_array = array(
    'user_id'                => "'.$this->user_id.'"
 );

 // join the set values of the update with the where values
 // in the one array to merge then in a for loop next
 $bind_array = array_merge($update_array, $criteria_array);

 $database->bind_execute($bind_array);

Thoughts, feedback? Better approach? I guess its only 5 lines if you strip it down but i think i might have over-complicated it?

4

1 回答 1

0

我有以下用于简单 PDO 插入或更新的功能。没有什么花哨但基本的:

function PDOInsertUpdate($Query, $Parameters)
{
    try 
    {
        $PDOConnection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
        $PDOConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $Statement = $PDOConnection->prepare($Query);
        foreach ($Parameters as $Key => $Val)
            $Statement->bindValue($Key+1, $Val);
        $Statement->execute();
        $PDOConnection = null;
        return true;
    } 
    catch(PDOException $e) 
    {
        // you doe do something with error message like 
        // die('ERROR: ' . $e->getMessage());
        return false;
    }

}   

我会调用该函数,如下例所示:

$Query = "insert into users set firstname=?, lastname=?, username=?, password=?";
$Paramaters = array($firstname, $lastname, $username, $password);

if (PDOInsertUpdate($Query, $Parameters))
{
  //after success
}
else
{
  //something went wrong!
}
于 2013-08-24T03:11:56.540 回答