2011-10-18 47 views
-2

写一个类似的查询我有一个PHP字符串以同查询 - 这样的事:如何在PHP

$select = "select category_id, category_name from categories where category_name like %"'.$category.'"%; 

但我敢肯定,这是完全错误的,我在万元感到困惑引号:)

什么是正确的方式来把这个查询在一起?

谢谢!

回答

0

我敢肯定,这只是:

$select = "select category_id, category_name from categories 
      where category_name like '%$category%'"; 
+1

你忘了百分比字符 – Andre

+0

修正了,谢谢。 –

2

如果您正在寻找“最佳实践”,您应该使用mysqli class来调查prepared statements。话虽这么说,

  1. 你的报价是向后绕$category变量(这是"',它应该是'"
  2. %“在你的说法应该是引号内('),不在外面他们
1

您可以使用位置参数。不知道你使用的是哪个数据库服务器,但是说你正在使用PDO层,然后看看PDO::prepare

1

这将是更好地做一个不同的方式,但要回答这个问题,如果你使用双引号,你不需要用点来连接变量

$select = "select category_id, category_name from categories where category_name like '%{$category}%'"; 
1

你搞砸了引号

"select [...] like '%".$category."%'"; 

这将成为

select [...] like '%something%' 

但你应该使用的查询参数,以避免SQL注入

2

你想要的,不是外面字符串中的%通配符。

另外,如果你想评估字符串中的php变量,你应该支持这个变量。

" select category_id, category_name from categories where category_name like '%{$category}%' " 

或连接它

" select category_id, category_name from categories where category_name like '%" . $category . "%' " 
1

这将是相对功能:

$select = "select category_id, category_name from categories where category_name like '%" 
    .mysql_real_escape_string($category)."%'"; 

然而,你可能会想逃离另外有一个LIKE内部特殊含义的字符,包括%

备注此外,mysql将无法使用索引来优化此查询,这意味着它不会在大型数据库上执行。您可能希望调查myISAM全文索引,以便在大型数据集上进行文本搜索。