我没有花太多时间优化我的代码或改进它的模块化,因为我一直在学习 PHP,但我认为是时候这样做了。我要改进的第一件事是我的 SQL 调用。我做了很多不同的 SQL 查询,它们都遵循几种不同的模式。我通常只是复制一个,将其粘贴到某个地方并更改我需要的内容。显然,这是我需要将它们模块化的危险信号。
我的问题是我不明白我该怎么做,因为我访问的每个表都有不同数量的变量,有时我想要一两个,而其他我想要整个表。此外,有时我想按 id 选择,有时按名称等。我只是在这里寻找正确方向的一点,只是在弄清楚我应该如何做到这一点时遇到了一些麻烦。以下是我的一些查询示例:
function pricesByAlcohol($alcID) {
$query = 'SELECT store_id, price FROM price WHERE alc_id = '.$alcID;
//echo $query."<br>";
$i= 0; //index
$result = array();
if ($stmt = $this->db->prepare($query)){
/* execute statement */
if($stmt->execute()) {
$stmt->bind_result($store_id, $price);
while($stmt->fetch()) {
$result[$i] = array('store' => $store_id,
'price' => $price);
$i++;
//echo $id." ".$img."/".$text."<br>";
}
} else
//echo "error";
/* close statement */
$stmt->close();
} else {
//echo "Prepare in fetchActiveAds failed: (" . $stmt->errno . ") " . $stmt->error;
}
return $result;
}
function store($storeID) {
$query = 'SELECT name, address, gps FROM store WHERE id = '.$storeID;
//echo $query."<br>";
if ($stmt = $this->db->prepare($query)){
/* execute statement */
if($stmt->execute()) {
$stmt->bind_result($name, $address, $gps);
while($stmt->fetch()) {
$result = array('name' => $name,
'address' => $address,
'gps' => $gps);
//echo $id." ".$img."/".$text."<br>";
}
} else
//echo "error";
/* close statement */
$stmt->close();
} else {
//echo "Prepare in fetchActiveAds failed: (" . $stmt->errno . ") " . $stmt->error;
}
return $result;
}
function getAlcoholIDByNameSize($name, $size) {
$query = 'SELECT id FROM alcohol WHERE size_id = '.$size.' AND name = "'.$name.'"';
//echo $query."<br>";
if ($stmt = $this->db->prepare($query)){
/* execute statement */
if($stmt->execute()) {
$stmt->bind_result($id);
while($stmt->fetch()) {
$result = $id;
//echo $id." ".$img."/".$text."<br>";
}
} else
//echo "error";
/* close statement */
$stmt->close();
} else {
//echo "Prepare in fetchActiveAds failed: (" . $stmt->errno . ") " . $stmt->error;
}
return $result;
}
谢谢