Multiple query criteria for the spelling of SQL discourse, seeking guidance

Source: Internet
Author: User
Spelling tips for multiple query criteria for SQL statements.
Spelling tips for multiple query criteria for SQL statements.


$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 name has a value
Sql=select * from TB1 where name like "% $name%"

When the value is at the same time, SQL is wrong.


Of course you can use it.
if ($id =$_get[' id ']&& $name =$_get[' name '])
{
Where.= "and";
}

I cite only two conditions, the actual project I have more than 10 conditions, this way certainly not.
Find a better way to stitch

Share to:


------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--------------------
Personally, I think I'm a 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--------------------
Citation:
I personally think I'm this simple

$sql = "SELECT * from tb1 where 1=1";
  • Related Article

    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.