<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>查询系统</title>
</head>
<body>
<?php
error_reporting(E_ALL^E_NOTICE);
$keywords = '';
if(isset($_POST['subBtn'])){//点击查询按钮
$keywords = $_POST['keywords'];
}
$mysqli = db();//获取数据库对象
?>
<div>
<form action="search.php" method="post">
<input name="keywords" value="<?=$keywords?>" />
<button name="subBtn" type="submit" >查询</button>
</form>
</div>
<table>
<?php showTable($keywords); ?>
</table>
</body>
</html>
<?php
function showTable($keywords){
$arr = queryData($keywords);
$num_rows = $arr['num_rows'];
$data = $arr['data'];
if($num_rows>0){
showTh();
foreach($data as $key=>$row){
showTr($row);
}
}else{
showTrEmpty('数据为空');
}
return $num_rows;
}
function showTh(){
echo '
<tr>
<th>ID</th>
<th>标题</th>
<th>日期</th>
<th>其他</th>
</tr>
';
}
function showTr($row){
$host = 'http://fgj.wuhan.gov.cn/';
$href = $row->href;
$a = '<a href="'.$host.$href.'" target="_blank" >'.redKeyWords($row->title).'</a>';
echo '<tr>';
echo '<td>'.$row->id.'</td>';
echo '<td>'.$a.'</td>';
echo '<td>'.$row->release_date.'</td>';
echo '<td></td>';
echo '</tr>';
}//showTr
function redKeyWords($value){
global $keywords;
if( strlen($keywords)>0 ){//设置关键字红色
$str = '<span style="color:red">'.$keywords.'</span>';
$value=str_replace($keywords,$str,$value);
}
return $value;
}
function showTrEmpty($value){
echo '<tr>';
echo '<td cols=4 >'.$value.'</td>';
echo '</tr>';
}
function queryData($keywords){
global $mysqli;
$WHERE = '';
if( isset($keywords) &&strlen($keywords)>0){
$WHERE = "WHERE title LIKE '%{$keywords}%' ";
}
$sql = "
SELECT * FROM new
{$WHERE}";
$result_obj = $mysqli->query($sql);
while($row = $result_obj->fetch_object() ){
$data[] = $row;
}
//echo $sql;
$num_rows = $result_obj->num_rows;
$arr = array(
'num_rows'=>$num_rows,
'data' => $data,
);
return $arr;
}
function db(){
header("Content-type: text/html; charset=utf-8");
date_default_timezone_set('Asia/Shanghai');
$host = '127.0.0.1:3307';
$user = 'root';
$password ='root';
$database = 'house';
$mysqli = new mysqli($host,$user,$password,$database);
$query = 'SET NAMES UTF8';
$mysqli->query($query);
if($mysqli->errno){
printf("连接数据库错误<br/> %s",$mysqli->error);
exit;
}else{
echo '连接成功!success</br>';
}
return $mysqli;
}
?>