douwen7905 2019-07-06 04:34
浏览 78
已采纳

使用PHP进行MySQL搜索

I'm writing a code for MySQL search but it is not working

im using PHP class and this is the code:

data_model.php

<?php
$data = new Data();
if(isset($_GET['q'])) {
    $data->$_GET['q']();
}
class Data {

    function __construct(){
        if(!isset($_SESSION['id'])){
            header('location:../../');   
        }
    }


    function getSubject($search){
        global $con;
        $q = "select * from subject where code like '%$search%' or title like '%$search%' order by code asc";
        $r = mysqli_query($con, $q);
        return $r;
    }]

subject.php

<?php
include "data/data_model.php";

$search = isset($_POST["search"]); 
$subject = $data->getSubject($search);
?>

<form action="subject.php" method="post">
   <label>
       <input type="text" class="form-control" name="search" placeholder="Search Subject..." >
   </label>
   <button type="submit" name="search" class="btn btn-success" value="search"><i class="fa fa-search"></i> Search</button>
</form>

is there anything wrong in my code? I also use the getSubject in getting data from the db table to my html table and it has no problems but in searching it is not working?

Can anyone help me? Thanks in advance.

  • 写回答

2条回答 默认 最新

  • drryyiuib43562604 2019-07-06 04:57
    关注

    Shouldn't it be like this?

    $data = new Data();
    if(isset($_GET['q'])) {
        $data->getSubject($_GET['q']);
    }
    

    Also, this:

    <?php
    include "data/data_model.php";
    
    $search = isset($_POST["search"]); 
    $subject = $data->getSubject($search);
    ?>
    

    Won't work as expected, because isset() returns TRUE/FALSE depending if there's "search" in $_POST. This is what works:

        <?php
            include "data/data_model.php";
    
    
            $search = isset($_POST["search"]) ? $_POST["search"]:  '';
            $subject = $data->getSubject($search);
            ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办