简体   繁体   English

我如何在MySQL PHP中使用OR语句

[英]How can I use OR statement in mysql php

I am trying to make a live search box for a library using ajax, mysql and php. 我正在尝试使用ajax,mysql和php为库创建实时搜索框。 I have implemented the search for the books. 我已经实现了对书籍的搜索。 ie when you type in the title of the book, it shows the suggestions. 即,当您输入书名时,它会显示建议。 However, I am trying to implement it also for the authors column in my database such that when you type in a name of an author, it shows the books that the author has written from the database but I don't seem to be getting the mysql statement on line 4 correctly. 但是,我正在尝试对数据库中的authors列也实现它,以便当您键入作者的名字时,它显示了作者从数据库写的书,但我似乎没有得到第4行上的mysql语句正确。 please help. 请帮忙。

<?php
include('config.php');
$s1=$_REQUEST["n"];
$sql="SELECT * from books where (Title like '%".$s1."%') OR (Author like '%'.s1.'%')";
$result=mysqli_query($conn,$sql);
$s="";
<?php
include('config.php');
$s1=$_REQUEST["n"];
$sql="SELECT * from books where `Title` like '%".$s1."%' OR `Author` like '%".$s1."%')";
$result=mysqli_query($conn,$sql);

You have some misplaced quotes as well as missing $ in your query code line. 查询代码行中的引号放错了位置,并且缺少$ So You need to change 所以你需要改变

Author like '%'.s1.'%'

To:- 至:-

Author like '%".$s1."%'

Note:- Your Query is wide-open for SQL INJECTION .So try to use prepared statements 注意:-您的查询对SQL INJECTION是开放的,因此请尝试使用prepared statements

Reference:- 参考:-

mysqli::prepare mysqli ::准备

PDO::prepare PDO ::准备

Personally I dont like OR's. 我个人不喜欢OR。 Instead I prefer Union. 相反,我更喜欢联盟。 Hey I get paid by the hour (actually I get salary) But I still like to over complicate things. 嘿,我按小时得到薪水(实际上我得到薪水),但我仍然喜欢使事情变得过于复杂。

<?php
include('config.php');
$s1=$_REQUEST["n"];
$sql="
    SELECT
         b.*
    FROM
        books AS b
    JOIN
        (
            SELECT
                id
            FROM
                books
            WHERE 
                Title like ?'
        UNION
            SELECT
                id
            FROM
                books
            WHERE 
                 Author like ?
        ) AS v
    ON b.id = v.id  
";

$stmt = mysqli_prepare($conn,$sql);

$stmt->bind_param("ss", '%'.$si.'%', '%'.$si.'%');
$stmt->execute();

$stmt->store_result();

$resultrow = array();
$stmt->bind_assoc($stmt, $resultrow);

while($stmt->fetch())
{
    print_r($resultrow);
}

No actually the performance is better, OR's are crap for performance. 实际上,没有哪个性能更好,或者“ OR”对性能没有好处。 And if you do it in a sub query with just the ID, then the tempory table you create by doing the union is tiny and then join and pull just what you want, sort etc... And it should be a few times faster, if you have like a couple million records. 如果您仅使用ID在子查询中执行此操作,那么通过合并创建的临时表就很小了,然后只需联接并提取所需的内容,进行排序等即可,而且速度应该快几倍,如果您有几百万条记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM