doushi7394 2012-11-12 16:29
浏览 36
已采纳

改进使用PDO并添加UPDATE语句的SELECT

I'm using the following code to select data from a MySQL table. Can someone tell me how to improve this as it seems a bit messy?

Also, I need to run an UPDATE statement to increment the value in the "views" column each time a customer is queried from the database. Each customer row in the database has a column named "views". For example, say ABC Corp has 100 views. If I search for ABC Corp and the database returns the record, the "views" column for this record should be updated to 101. What is the best way to do this?

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);
}
  • 写回答

1条回答 默认 最新

  • douchangmian0305 2012-11-12 16:42
    关注

    How about something like this,

     $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);
    

    For the UPDATE statement,

       //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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算