如何通过PHP通知阻止我的PHP发送错误信息?

时间:2015-05-06 13:16:27

标签: php mysql

我目前正在开发一个项目,我需要从数据库中的3个不同的表中获取一些数据并回显它们,以便我可以在jQuery中使用结果。 我正在向PHP发送带有3个变量的GET请求。第一个用于确定哪个'命令'需要执行,另外2个用于确定需要查询哪个表和哪一行。

这是我到目前为止的代码:

} elseif($_GET['command']=='getpage') {
    $mypid = $_GET['id'];
    $mytable = $_GET['table'];

    $link = mysqli_connect($dbserver,$userdb,$passdb,$db_typo) or die(mysqli_error($link));

    if($mytable == 'tableName1'){
        $query = 'SELECT * FROM table1 WHERE uid = "'.$mypid.'"'; //I need 6 elements from this table
    } elseif($mytable == 'tableName2'){
        $query = 'SELECT * FROM table2 WHERE uid = "'.$mypid.'"'; //I need 7 elements from this table
    } elseif($mytable =='tableName3'){
        $query = 'SELECT * FROM table3 WHERE uid = "'.$mypid.'"'; //I need 8 elements from this table
    } else {
        echo 'no such table supported for this command';
    }

    $result = mysqli_query($link, $query) or die(mysqli_error($link));

    $pagecontent = array();
    while($row = mysqli_fetch_assoc($result)){
        $pagecontent[] = array(
            'id' => utf8_encode($row['uid']),
            'name' => utf8_encode($row['name']),
            'text1' => utf8_encode($row['text1']), //not every table has this
            'text2' => utf8_encode($row['text2']),
            'img' => utf8_encode($row['image']),
            'parent' => utf8_encode($row['parent']), //not every table has this
            'sub_parent' => utf8_encode($row['sub_parent']), //not every table has this
            'deleted' => utf8_encode($row['deleted'])
        );
    }

    echo '{"content": '.json_encode($pagecontent).'}';
}

我需要从数据库中获取超过50个页面。所以,当我让发送GET请求的jQuery函数运行时,我最终会发送垃圾邮件错误。

  

PHP注意:未定义的索引:第171行/var/www/my.php中的text1

我不想要。

还有另一种解决这个问题的方法吗?而不只是将查询和while循环放在if语句中?

2 个答案:

答案 0 :(得分:3)

添加检查是否存在数组键

'text1' => isset($row['text1']) ? utf8_encode($row['text1']) : '',

答案 1 :(得分:1)

我不知道为什么你不想要if来检查索引,但是你可以在while

中添加另一个循环

并添加这些变量:

while($row = mysqli_fetch_assoc($result)){
    $temp = array();
    foreach($row as $key => $value) {
        $temp[$key] = utf8_encode($value);
    }
    $pagecontent[] = $temp;
    // $pagecontent[] = array_map('utf8_encode', $row);
}

echo json_encode(array('content' => $pagecontent));

这只是获取$row内的所有内容,对所有值进行编码,然后将其推入容器内。

旁注:不要手工构建JSON字符串,创建最终的数组结构,然后进行编码。