PHP & MYSQL:从 id=$id 中选择


PHP & MYSQL: Select from where id=$id

所以我正在制作一个用户组函数,允许我阻止页面以降低用户级别。这是我获取信息的函数:

function grab_info($id, $requested_info){
    $id = $_SESSION['user_id'];
    $requested_info = $requested_info;
    $con = new mysqli('localhost', 'root', '', 'login');
    if ($con->connect_errno >0){
        die("Handle your connection error here");
    }
    $sql = "SELECT * FROM `users` WHERE `id` = $id";
    if (!$result = $con->query($sql)) {
        die("There as a query error for some reason handle your query error");
    }
    while($row = $result-fetch_assoc()){
        $info = $row[$requested_info];
        return $info;
    }
}

就在这儿:

$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
    die("There as a query error for some reason handle your query error");
}

是出现问题的地方。这是我获取信息的方法:

$id = $_SESSION['user_id'];
$rank = grab_info($id, 'rank');//Gets rank from our id
$meets = can_access($rank, 4, true);//We're saying our user has a rank of 1 to access this page you need a rank of 3 and only 3 hence strict
if ($meets == false){//user cant access page
    header("Location: index.php");
    die();
}

基本上,它只是一直给我"由于某种原因出现查询错误来处理您的查询错误",我卡住了。PHP新手,如果它很乱,很抱歉。

使用预准备语句并将变量转换为整数。

$stmt = $con->prepare("SELECT * FROM `users` WHERE `id` = ?");
$stmt->bind_param("i",$id);
$id = (int) $_SESSION['user_id'];
$stmt->execute();
$result = $stmt->get_result();

检查以确保实际设置了$id。如果为 null,则会导致查询爆炸。

$sql = "SELECT * FROM `users` WHERE `id`='{$id}'";

试试这个:)

$query=mysql_query("SELECT * FROM user WHERE user_email='$user_email');
Please try this: 

function grab_info($id, $requested_info){
    $id = $_SESSION['user_id'];
    $requested_info = $requested_info;
    $con = new mysqli('localhost', 'root', '', 'login');
    if ($con->connect_errno >0){
        die("Handle your connection error here");
    }
    $sql = "SELECT * FROM users WHERE id =". $id;
    if (!$result = $con->query($sql)) {
        die("There as a query error for some reason handle your query error");
    }
    while($row = $result->fetch_assoc()){
        $info = $row;
        return $info;
    }
}