当我尝试使用以下代码从 $_SESSION['user']['id'] 中获取我的 (int) 用户 ID 的值时:
$userId = '';
if (isset($_SESSION['user'])) {
$userId = $_SESSION['user']['id']; //56) uitlezen van de sessievariabele...
// TODO: 57) statement voor een select uit te voeren... user en deleted...
$sql_notes_select_where
= 'SELECT '
. '`note_id` AS `id`,'
. '`note_title` AS `title`,'
. '`note_content` AS `content`'
. 'FROM `notes` '
. 'WHERE '
. '`note_deleted` is null and'
. '`user_id`=:userid'
;
try {
// 58) Connectie openen met db...
$db = getDbConnection();
/**
* Zie ook: http://courses.olivierparent.be/php/databases/pdo-php-data-objects/
*/
if ($stmt_notes_select_where = $db->prepare($sql_notes_select_where)) {
// TODO: 59) Binding uitvoeren user...
$stmt_notes_select_where->bindValue(':userid', $userId);
$stmt_notes_select_where->execute();
}
// TODO: 60) Het opvragen van het aantal rijen...
//$results = ...;
$results = $db->query($sql_notes_select_where);
// 61) Het sluiten van de connectie met de db.
closeDbConnection($db);
} catch (PDOException $e) {
switch ($e->getCode()) {
case '23000':
$error = "Er bestaat al een gebruiker met <strong>{$_POST['email']}</strong> als e-mailadres.";
break;
default:
$error = 'Er is een fout gebeurd: ' . $e->getMessage();
break;
}
}
我收到此错误消息。
Er is een fout gebeurd: 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 ':userid' at line 1
最佳答案
在 MySQL 中执行查询时返回给您的是什么?您的列数据类型是否与您要绑定(bind)的值相同?
尝试以下操作:
SELECT note_id AS `id`,
note_title AS `title`,
note_content AS `content`
FROM `notes`
WHERE
note_deleted is null and
user_id= :userid
;
编辑
设置 2 个 session 变量,第一个是 $_SESSION['user']
,第二个是登录时的 $_SESSION['id of your user']
。
<?php
$DB_host = "localhost";
$DB_user = "your user";
$DB_pass = "your pass";
$DB_name = "your database";
//try to put the id in the session
//Then
$userId = $_SESSION['id'];
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
<body>
<?php
$selectAll = "SELECT note_id AS id,
note_title AS title,
note_content AS content
FROM notes
WHERE
note_deleted is null and
user_id= :id";
$stmtAll=$conn->prepare($selectAll);
$stmtAll->bindValue(':id', $userId);
$execAll=$stmtAll->execute();
$result=$stmtAll->fetchAll();
foreach($result as $rows){
var_Dump($rows) ?>
<table>
<tr>
<td>
<?php echo $rows['title'];
?>
</td>
这是我的结果(有效):
关于php - SQLSTATE[42000] : Syntax error or access violation: 1064 (bindvalue as integer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34472298/