我正在尝试检索附加到特定用户的所有计划的计划信息。他们登录并且他们的用户名保存在会话中,我知道我需要结合MySQL WHERE
语句使用它。这是我的代码:
<?php
$servername = "localhost";
$username = "root";
$password = "XXX";
$dbname = "name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name ='$_SESSION['user_name']'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["plan_id"]. "<br>";
echo "id: " . $row["plan_name"]. "<br>";
echo "id: " . $row["plan_type"]. "<br>";
echo "id: " . $row["plan_active"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
注意我在$_SESSION['user_name']
语句中使用了WHERE
。我做错了什么?什么都没有显示出来。
答案 0 :(得分:1)
您未在查询中正确传递$_SESSION['user_name']
变量。
试试这个: -
替换: -
$sql = "SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name ='$_SESSION['user_name']'";
: -
$sql = "SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name ='" . $_SESSION['user_name'] . "'";
我建议你使用准备好的陈述。那么你不会犯这些类型的错误。
答案 1 :(得分:1)
$_SESSION['user_name']
具有与其相关的相同类型的引号。我会在SQL查询之外设置$username = $_SESSION['user_name']
,然后将$username
放在sql查询中。
答案 2 :(得分:0)
@kloddant提到引号存在问题。这是正确的查询应该是这样的:
SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name = ?
部分代码如下所示:
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name = ?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $SESSION['user_name']);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($result);
/* Play with result */
/* close statement */
$stmt->close();
}
一些提示;如果您有大型用户数据库,请索引user_name字段或使用id而不是user_name。这可以使您的查询更快。