简体   繁体   English

需要正确的PHP / MySQL语法帮助

[英]Proper PHP/MySQL syntax help needed

I've been chasing a bug all day in my code. 我整天都在代码中追寻一个错误。 Here's the long and short of it: 这是它的长短:

I have a variable that is passed through a query string and I want to use that variable in my MySQLi query. 我有一个通过查询字符串传递的变量,我想在我的MySQLi查询中使用该变量。 A-like so: 像这样:

$variable;

$info = dbConnect('query');
$eInfo = "SELECT *
FROM tablename
WHERE fieldname = '$variable%'";
$eiData = $info->query($eInfo) or die(mysqli_error());
$eInfo = $eiData->fetch_assoc();

The emphasis is the % after the variable name. 重点是变量名后的%。 I'm no PHP expert but I remember picking this trick up a while back and it has worked for me on all my DB-driven websites EXCEPT the new one I'm developing. 我不是PHP专家,但我记得前一段时间已经掌握了这一技巧,除了我正在开发的新网站之外,它对我所有的数据库驱动网站都有效。

The above query returns no data from the table. 上面的查询不返回表中的任何数据。

BUT... 但...

if I omit the % as follows: 如果我省略%,如下所示:

$variable;

$info = dbConnect('query');
$eInfo = "SELECT *
FROM tablename
WHERE fieldname = '$variable'";
$eiData = $info->query($eInfo) or die(mysqli_error());
$eInfo = $eiData->fetch_assoc();

The query executes and I get my data. 查询执行,我得到我的数据。

WHY after writing queries where I want to use a variable using the syntax '$variable%' would this no longer work? 为什么在使用“ $ variable%”语法编写要在其中使用变量的查询后,这将不再起作用? Just dropping the % ('$variable') makes it work A-OK, which has me utterly baffled. 只需放下%('$ variable')就可以正常工作,这让我非常困惑。

For what it's worth, I run a dedicated server and suPHP was recently installed, if that has any remote chance of helping make sense here (PHP 5.2.17 is my current version). 对于它的价值,我运行一台专用服务器,并且最近安装了suPHP,如果在这里有任何机会可以帮助您理解(PHP 5.2.17是我的当前版本)。

Again, I'm no PHP whiz, but after checking code form older sites I have done with MySQLi queries, the % was always there when appending a variable into a query. 再说一次,我不是PHP专家,但是在检查完我使用MySQLi查询完成的旧网站的代码后,将变量附加到查询中时,%总是存在。

I'm completely dead in the water here. 我完全死在这里的水中。 Any help you can provide would be so insanely appreciated that it defies explanation. 您所能提供的任何帮助都会令人发指,以至于无法解释。

如果要将变量放在难以解释变量名结尾的字符串中,请使用{$var}如下所示:

$eInfo = "SELECT * FROM tablename WHERE fieldname LIKE '{$variable}%'"; 

The % is a wildcard for LIKE queries. %LIKE查询的通配符。 So if you use % in a query with WHERE var = 'cow%' , it's going to search the database for the literal string cow% . 所以,如果你使用%与查询WHERE var = 'cow%' ,它会在数据库中搜索文字字符串cow%

  1. cow
  2. cows
  3. cow% (match) cow% (匹配)
  4. the cow

In a Like query: WHERE var LIKE 'cow%' the following will match: 在“赞”查询中: WHERE var LIKE 'cow%'将会匹配:

  1. cow (match) cow (比赛)
  2. cows (match) cows (比赛)
  3. cow% (match) cow% (匹配)
  4. the cow

See MySQL Pattern Matching . 参见MySQL模式匹配

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

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