两个错误可能与 Php PDO 有关

Two errors probably related Php PDO

我是 PDO 的新手,所以要温柔。我已经创建了一个到我的数据库的连接,希望从我的 table 中拉出用户(有效)并且能够单击该用户并将他们带到基于用户 ID 的页面(有效)但是当你访问该页面时出现以下错误:

Notice: Undefined variable: user_id in C:\MAMP\htdocs\dashboardR v2.0\users.php on line 10

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

这是我的脚本:

userList.php

<?php require_once '../db_con.php'; 

try{
    $results = $db->query('SELECT * FROM users');

}catch(Exception $e) {
    echo $e->getMessage();
    die();
}

$users = $results->fetchAll(PDO::FETCH_ASSOC);

?>

<ol>
<?php
    foreach($users as $user){
        echo 
        '<li>
        <a href="users.php?id='.$user["user_id"].'">'.$user["emailAddress"].'</a>
        ' .$user["firstname"].'
        ' .$user["lastname"].'
        </li>';
    }

?>
</ol>

users.php(这是单视图)

<?php require_once '../db_con.php'; 

if(!empty($_GET['user_id'])){
    $user = $_GET['user_id'];
}

try{
    $results = $db->query('select * from users where user_id = '.$user);

} catch(Exception $e) {
    echo $e->getMessage();
    die();
}

$user = $results->fetch(PDO::FETCH_ASSOC);

?>

<h3><i class="fa fa-user"></i></span> <?php echo $user['firstname'] . ' ' . $user['lastname']; ?>
    <a href="newMember.php"><span class="newUserBtn" title="Add New User"><i class="fa fa-user-plus"></i></span></a>
</h3>  

您正在使用 users.php?id 然后在使用 GET 数组后 $_GET['user_id'].

两者应该匹配。

您可以 users.php?user_id 或将数组更改为 $_GET['id']

还要确保数组是 int,包括您的列类型。

否则将您的查询更改为

("select * from users where user_id = '$user'");