Spelling of SQL statements with multiple query conditions

Source: Internet
Author: User
Spelling skills of SQL statements with multiple query conditions. Spelling skills of SQL statements with multiple query conditions. $ SQL = "select & nbsp; * & nbsp; from & nbsp; tb1"; if ($ id = $ _ GET ['id']) {$ where. = "& nbsp; where & nbsp; id & n specifies the spelling skills of SQL statements with multiple query conditions.
Spelling skills of SQL statements with multiple query conditions.


$ SQL = "select * from tb1 ";
If ($ id = $ _ GET ['id'])
{
$ Where. = "where id like" % $ id % "";
}
If ($ name = $ _ GET ['name'])
{
$ Where. = "where name like" % $ name % "";
}

// When the id has a value
SQL = select * from tb1 where id like "% $ id %"
// When the name has a value
SQL = select * from tb1 where name like "% $ name %"

// When both values are returned, an error occurs in the SQL statement.
SQL = select * from tb1 where name like "% $ name %" where id like "% $ id %"

// Of course you can use
If ($ id = $ _ GET ['id'] & $ name = $ _ GET ['name'])
{
Where. = "and ";
}

In my example, there are only two conditions. in actual projects, I have more than a dozen conditions. this method is definitely not feasible.
For better splicing methods:
------ Solution --------------------
$where = array();
foreach($_GET as $k=>v) $where[] = "$k like '%$v%'";
$sql="select * from tb1";
if($where) $sql .= ' where ' . join(' and ', $where);

------ Solution --------------------
$sql="select * from tb1";
$where = array();
if($id=$_GET['id'])
{
    $where[]=" id like '%$id%'";
}
if($name=$_GET['name'])
{
    $where[]=" name like '%$name%'";
}

$s=(!empty($where)) ? " where " . implode(" and " , $where) : '';
$sql.=$s;

------ Solution --------------------
I personally think this is simple.

$sql="select * from tb1 where 1=1";
if($id=$_GET['id']) $sql.=" and id like "%$id%"";
if($name=$_GET['name']) $sql.=" and name like "%$name%"";

------ Solution --------------------
Reference:
I personally think this is simple.

$sql="select * from tb1 where 1=1";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.