I've made a function to query the database. This function takes an array, the id of the user I want to update

and a query operation.

if the query operation is UPDATE

if you look at the code below, would this be a good coding practice or is this bad code?

public function query($column, $search_value, $query_operation = "SELECT"){

if(strtoupper($query_operation == "UPDATE")){

$query = "UPDATE users SET ";

if(is_array($column)){

$counter = 1;

foreach($column as $key => $value){

if($counter < count($column)){

$query .= $key . ' = ?, ';

}else{

$query .= $key . ' = ? ';

}

$counter++;

}

$query .= "WHERE id = ?";

$stmt = $this->database->prepare($query);

$counter = 1;

foreach($column as $key => &$value){

$stmt->bindParam($counter, $value);

$counter++;

}

$stmt->bindParam($counter, $search_value);

if($stmt->execute()){

$stmt = $this->database->prepare("SELECT* FROM

users WHERE id = ?");

$stmt->bindParam(1, $search_value, PDO::PARAM_INT);

$stmt->execute();

return $this->build_array($stmt);

}

}

}

}

would love to hear some feedback.

解决方案

I would NOT mix SELECT and UPDATE in the same function.

The following update function uses arrays for column names and values $columnNames & $values using unnamed parameters.

function update($tableName,$columnNames,$values,$fieldName,$fieldValue){

$sql = "UPDATE `$tableName` SET ";

foreach($columnNames as $field){

$sql .= $field ." = ?,";

}

$sql = substr($sql, 0, -1);//remove trailing ,

$sql .= " WHERE `$fieldName` = ?";

return $sql;

}

As table and column names cannot be passed as parameters in PDO I have demonstrated whitelistng of table names.

$tables = array("client", "Table1", "Table2");// Array of allowed table names.

Also array_push()to add value for last parameter (WHERE) into $values array

Use

if (in_array($tableName, $tables)) {

$sql = update($tableName,$columnNames,$values,$fieldName,$fieldValue);

array_push($values,$fieldValue);

$STH = $DBH->prepare($sql);

$STH->execute($values);

}

You can use similar technique for SELECT

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐