PDO mysql and PHP: Undefined index and Trying to get property of non-object

时间:2015-06-15 15:12:13

标签: php mysql pdo

Anyone please help me fix my php code here. Im working with php and PDO and I have been switching codes around but nothing works. Any help will be appreciated.

Here is the code for my index page:

<?php
require_once 'init.php';

$supportQuery = $conn -> query("
SELECT id, title, content
FROM table");

while ($row=$supportQuery ->fetchObjecy()) {
$support[]=$row;
}
?>

<?php if(!empty($support)): ?>
<?php foreach($support as $supp): ?>
<a href="page.php?id=<?php echo $supp->id; ?>&title=<?php echo $supp->title; ?>">
<?php echo $supp->title; ?></a>
<?php endforeach; ?>
<?php else: ?>
No items found.
<?php endif; ?>

This code works the way I like it to work but when I run code and click the link, that is where I am getting errors.

Here is my php code for page.php:

<?php
require_once 'init.php';

$articleQuery = $conn -> prepare("
SELECT id, title, content
FROM table WHERE id='$id' and title='$title'");

while ($row=$articleQuery ->fetchObject()) {
$support[]=$row;
}
$articleQuery->execute();
?>

<?php if(!$_SESSION($support)): ?>
<?php echo $support->id; ?>
<?php echo $support->title; ?><br/>
<?php echo $support->content; ?>
<?php else: ?>
<p>Are you inventing titles? Sorry but this page   doesnt exist nowhere.</p>
<?php endif; ?>

I need your help please. I am getting the following error messages:

Notice: Undefined index: title and id in /page.php
Notice: Undefined variable: support in /page.php
Notice: Trying to get property of non-object in /page.php

♡nbgmalimit

1 个答案:

答案 0 :(得分:0)

好的,开始......

1)在第二个代码块中,您需要在尝试获取结果之前执行语句。

2)你应该在执行之前绑定值$ id和$ title以避免sql注入。

查看手册中的示例,了解如何执行这两个操作...... http://php.net/manual/en/pdostatement.execute.php

3)您将该行作为对象获取,并将结果对象作为值添加到$ support ARRAY中。

4)假设id和title是唯一的,你不需要循环它并将它添加到数组中,因为你应该只返回1行。只需使用fetch。将PDO :: FETCH_ASSOC用于获取样式将返回一个数组。将PDO :: FETCH_OBJ用于获取样式将返回一个对象。 http://php.net/manual/en/pdostatement.fetch.php

尝试这样的事情......

$row = null;        
$stmt = $conn->prepare("SELECT id, title, content FROM table WHERE id = :id and title = :title");
$stmt->bindParam( ":id", $id, PDO::PARAM_INT );
$stmt->bindParam( ":title", $title, PDO::PARAM_STR );
$result = $stmt->execute();
if ($result) {
    $row = $stmt->fetch(PDO::FETCH_OBJ);
} else {
    // handle error
}
?>

<?php if(!empty($row)): ?>
<?php echo $row->id; ?>
<?php echo $row->title; ?><br/>
<?php echo $row->content; ?>
<?php else: ?>
<p>Are you inventing titles? Sorry but this page   doesnt exist nowhere.</p>
<?php endif; ?>