0

我正在使用以下代码从 MySQL 表中选择数据。有人可以告诉我如何改进它,因为它看起来有点乱吗?

此外,每次从数据库中查询客户时,我都需要运行 UPDATE 语句来增加“视图”列中的值。数据库中的每个客户行都有一个名为“views”的列。例如,假设 ABC Corp 有 100 次观看。如果我搜索 ABC Corp 并且数据库返回记录,则该记录的“views”列应更新为 101。最好的方法是什么?

if ($search && ($group && $group !== "*")) {
  $sql = "SELECT * FROM customers WHERE description LIKE :description AND groupId LIKE :groupId";
  $result = $conn->prepare($sql);
  $result->bindValue(":description", "%" . $search . "%", PDO::PARAM_STR);
  $result->bindValue(":groupId", $groupId, PDO::PARAM_INT);
} else if ($search) {
  $sql = "SELECT * FROM customers WHERE description LIKE :description";
  $result = $conn->prepare($sql);
  $result->bindValue(":description", "%" . $search . "%", PDO::PARAM_STR);
} else if ($group !== "*") {
  $sql = "SELECT * FROM customers WHERE groupId LIKE :groupId";
  $result = $conn->prepare($sql);
  $result->bindValue(":groupId", $groupId, PDO::PARAM_INT);
} else {
  $sql = "SELECT * FROM customers";
  $result = $conn->prepare($sql);
}
4

1 回答 1

2

这样的事情怎么样

 $sql = "SELECT * FROM customers ";
 $and = $grp = FALSE;

 if($search || ($group && $group !== "*") {
 $sql .= " WHERE ";
 if ($search) {
  $sql .= " description LIKE :description ";
  $and = TRUE;
 } 

 if ($group && $group !== "*") {
   if( $and === TRUE )
     $sql .= " AND ";        
   $sql .= " groupId LIKE :groupId ";  
   $grp = TRUE;     
 }     
 } 

 $result = $conn->prepare($sql);
 if( $and === TRUE)
  $result->bindValue(":description", "%" . $search . "%", PDO::PARAM_STR);

 if( $grp === TRUE)
   $result->bindValue(":groupId", $groupId, PDO::PARAM_INT);

对于UPDATE声明,

   //say $cust_name is the requested customer to be searched
   $sql = "SELECT views from customers where customer_name = '" $cust_name."'";
   $res = $conn->query($sql);
   $views = $res->fetchColumn() + 1;
   //sets 'views' to num_of_customers/rows returned.
   $sql = "UPDATE customers SET VIEWS = " .$views." WHERE customer_name = '" $cust_name."'";
   $res = $conn->query($sql);
于 2012-11-12T16:42:30.533 回答