我正在浏览我的代码,而且我正在运行这么多查询,但这些查询的时间越来越长。如果我只想存储一个带有值的变量,我必须这样做:
switch($type) {
case "next":
if ($stmt = $mysqli->prepare("SELECT sort_order FROM user_slides WHERE user_id = ? AND sort_order > ? ORDER BY sort_order LIMIT 1")) {
$stmt->bind_param('is', $user_id, $sortId);
$stmt->execute();
$stmt->bind_result($next_sort_id);
$stmt->store_result();
$stmt->fetch();
return $next_sort_id;
$stmt->close();
}
break;
case "first":
if ($stmt = $mysqli->prepare("SELECT MIN(sort_order) as max_slides FROM user_slides WHERE user_id = ?")) {
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($first_sort_id);
$stmt->store_result();
$stmt->fetch();
return $first_sort_id;
$stmt->close();
}
break;
case "last":
if ($stmt = $mysqli->prepare("SELECT MAX(sort_order) as max_slides FROM user_slides WHERE user_id = ?")) {
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($last_sort_id);
$stmt->store_result();
$stmt->fetch();
return $last_sort_id;
$stmt->close();
}
break;
}
必须有一种更简单的方法来做到这一点。我可以这样做:
$first_sort_id = QUERY HERE
$last_sort_id = QUERY HERE
所以它不必太久,它可以很好而且很短。
有谁知道我需要做些什么来实现这个目标?
答案 0 :(得分:2)
<强>第一强>
如果您使用return
,则永远不会执行$stmt->close();
语句。
<强>第二强>
摆脱两个变种,你只需要一个。不要被语义含义所迷惑。
<强>第三强>
简单的重组可能是这样的:
switch($type)
{
case "next":
$Query = "SELECT sort_order";
break;
case "first":
$Query = "SELECT MIN(sort_order)";
break;
case "last":
$Query = "SELECT MAX(sort_order)";
break;
}
if ($stmt = $mysqli->prepare("$Query as max_slides FROM user_slides WHERE user_id = ?"))
{
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($value);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $value;
}
else
return NULL;