php - 通过应用条件在mysql中查询串联

标签 php mysql

为什么这个查询不起作用?...可能是这种查询吗?我想使用此查询从 mysql 数据库中检索数据..但它不起作用..

<?php 
$mysqli=new mysqli('localhost','root','','informationdb');
if(isset($_POST['Submit'])){
    $countryid=$_POST['countryid'];    //from <select></select>
    $cityid=$_POST['cityid'];          //from <select></select>
    $locationid=$_POST['locationid'];  //from <select></select>
    $subjectid=$_POST['subjectid'];    //from <select></select>
    $degreeid=$_POST['degreeid'];      //from <select></select>
    $q=' ';
    if($countryid!='0'){
        $q="select * from tblinformation where countryid='".$countryid."' ";
    }
    if($cityid!='0'){
        $q.= "and cityid='"$cityid"' ";
    }
    else if($locationid!='0'){ 
        $q.= "and locationid='"$locationid"' ";
    }
    else if($subjectid!='0'){ 
        $q.= "and subjectid="$subjectid" ";
    }
    else if($degreeid!='0'){
        $q.= "and degreeid='"$degreeid"' ";
    }
    $rst=$mysqli->query($q);
}

最佳答案

您缺少用于字符串连接的 .:

if ($cityid != '0') {
    $q .= "and cityid = " . $cityid . " ";
}

其他参数也类似。

此外,如果 $countryid 为 0,则永远不会使用 select * from tblinformation 子句初始化 $q。您应该将查询的这一部分放在所有条件之外的 $q 中。

参见 https://stackoverflow.com/questions/26519890/mysqli-filter-results-from-form-post/26520095#26520095为动态构建 WHERE 子句的代码提供更好的结构。

关于php - 通过应用条件在mysql中查询串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28593823/

相关文章:

php - Laravel 中的“播种”是什么意思?

PHP 我应该使用 pg_* 函数还是 PDO?

mysql - 如何将此 Access 查询转换为 mySQL 查询?

php - 如何为具有多对多关系的业务目录建立mySQL表结构?

长字符串的 MySQL 索引

MySQL 数据库在 Apache Solr 上建立索引,如何通过 URL 访问它

php - 合并列中具有相同字段的多行

php - 在 Twig 中有条件地扩展模板

php - PHP 中的段错误,使用 SOAP 连接到 SalesForce

MySQL 慢查询 ~ 10 秒