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