检查并将数组设置为null

时间:2016-07-23 16:08:42

标签: php arrays mysqli

如果数据库中没有现有数据,我试图将result_array设置为null。结果应该以表格格式显示,但我不能将result_array作为null并继续在行$result_array[] = null;上获得错误     

global $db;
$db = new mysqli();
$db->connect("localhost", "root", "", "databasename");
$db->set_charset("utf8");

if ($db->connect_errno) {
    printf("Connection has failed: %s\n", $db->connect_error);
    exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="url">';
$html .= '<h3>name</h3>';
$html .= '</a>';
$html .= '</li>';

$search = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search = $db->real_escape_string($search);

if (strlen($search) >= 1 && $search !== ' ') {
    $query = 'SELECT * FROM tablename WHERE name LIKE "%'.$search.'%"';
    $result = $db->query($query) or trigger_error($db->error."[$query]");

    if(!$results = $result->fetch_array()){

        $resultArray[] = null;
    }
    else{

    while($results = $result->fetch_array()) {
        $resultArray[] = $results;
    }   
    }

    if (isset($resultArray)) {
        foreach ($resultArray as $result) {
            $show_name = preg_replace("/".$search."/i", "<b class='highlight'>".$search."</b>", $result['name']);
            $show_url = 'index.php';
            $out = str_replace('name', $show_name, $html);
            $out = str_replace('url', $show_url, $out); 
            $_SESSION['result']= $result['name'];
            echo($out);
        }
    }else{
        $out = str_replace('url', 'javascript:void(0);', $html);
        $out = str_replace('name', '<b>No Results.</b>', $out);
        echo($out);
    }
}
?>

1 个答案:

答案 0 :(得分:0)

你为什么不用这个?

...
$result_array = array();

if(!$results = $result->fetch_array()){
    //do nothing
}
else{

while($results = $result->fetch_array()) {
    $result_array[] = $results;
}   
...

另请使用$result_array$resultArray