【问题标题】:Check and set array to null检查并将数组设置为空
【发布时间】:2016-07-23 16:08:42
【问题描述】:

如果数据库中没有现有数据,我正在尝试将 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);
    }
}
?>

【问题讨论】:

  • 也许它不为空
  • 但是我的数据库是空的
  • 此代码$result_array[] = null; 将(假设)将null 插入给定数组的新位置。见an example
  • 旁注:当你运行if(!$results = $result-&gt;fetch_array()){ .. }else{ while($results = $result-&gt;fetch_array()) {...时,你会从结果中漏掉一行...
  • 为什么不这样做:if($result){ /* show the values */ }else{ show No Results }

标签: php arrays mysqli


【解决方案1】:

你为什么不用这个?

...
$result_array = array();

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

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

也请使用$result_array$resultArray

【讨论】:

  • 加了 $result_array = array(); 还是不行:(
  • 你还删除了$resultArray[] = null;?
  • 是的...仍然显示错误。甚至不显示为空:(
  • 你为什么要在回答中提问?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 2020-03-11
  • 1970-01-01
  • 2011-11-04
  • 2017-09-13
  • 2020-08-07
相关资源
最近更新 更多