试图找到我的未定义索引的解决方案

时间:2014-04-06 14:27:57

标签: php mysql sql session pdo

我有一个包含类别列表的表格,我还有一个表格来搜索类别标题。

我正在按照我想要的方式工作,但我已经两个通知我几天都找不到解决方案了。

我知道如果我在sql语句之前放置@我解决了我的问题,但我认为这不正确。

当我传递一个值时,搜索表单正常工作,但是当我没有传递任何值时,我总是有通知说:“注意:未定义的索引:where”,因为选择加载类别列表是在没有已经将任何值传递给我在我的sql语句中使用的$_SESSION['where']

有人在那里看到解决这个问题的解决方案吗?

我有这个错误:

注意:未定义的索引:我的“SELECT * FROM categories {$ _SESSION ['where']} ...”

我知道我有这个错误,因为

我的PHP代码,用于在会话中存储用户在我的搜索字段中传递的sql语句:

if(isset($_POST['sendForm']))
{
$search = $_POST['search'];
if(!empty($search) && $search != 'Search...:')
{
    $_SESSION['where'] = "WHERE t LIKE '%$search%'";
    header('Location: index2.php?exe=posts/categories');
}
else
{
    unset($_SESSION['where']);
    header('Location: index2.php?exe=posts/categories');
}
}

然后我做我的sql语句:

我的sql statment的php代码:

$pag = (empty($_GET['pag']) ? '1' : $_GET['pag']);
$max = 3; 
$begin = ($pag * $max) - $max;

$readCategory = $pdo->prepare("SELECT * FROM categories {$_SESSION['where']} ORDER BY name DESC LIMIT :begin, :max");
$readCategory->bindParam(':begin', $begin, PDO::PARAM_INT);
$readCategory->bindParam(':max', $max, PDO::PARAM_INT);
$readCategory->execute();



$num_readCategory = $readCategory->rowCount();

if(!$num_readCategory >= 1)
{
echo 'There are not categories yet';
}

2 个答案:

答案 0 :(得分:1)

您应该像使用$ _GET参数一样解决问题:

$where = isset($_SESSION['where']) ? $_SESSION['where'] : '';
$readCategory = $pdo->prepare("SELECT * FROM categories {$where} ORDER BY name DESC LIMIT :begin, :max");

另外,我通常在函数/方法中封装这种访问:

function get_session_param($name, $default = null) {
   if (isset($_SESSION[ $name ])) {
       return $_SESSION[ $name ]; 
   }
   return $default;
}

答案 1 :(得分:0)

如果您的搜索字词为空,则表示您未设置$_SESSION['where']变量,因此未定义。

相反,只需将其设置为空字符串:

else
{
    $_SESSION['where'] = "";
    header('Location: index2.php?exe=posts/categories');
}