从SQL数据库中选择在特定列中包含特定文本字符串的所有行


Select from SQL database all rows that CONTAIN a certain text string in specific column

我一直在看其他帖子,比如this和this,但对我的特定案例无效。

我有一张这样的桌子:

|    Name    |    Reference    |    Etc...    |
|------------|-----------------|--------------|
|  John Doe  |                 |  Blah blah   |
|  Jane Doe  |   John Doe      |  Blah blah   |
| Mike Small |   Jane Doe      |  Blah blah   |
|  Steve Ex  |   John Doe      |  Blah blah   |
| Mary White |   Mike Small    |  Blah blah   |

我希望能够找到哪些名称也是另一个名称的引用,并将它们转换为链接,这样用户就可以点击它们,并获得一个引用的名称列表。

例如,如果用户单击John Doe,他/她将得到这样的表:

|    Name    |    Reference    |    Etc...    |
|------------|-----------------|--------------|
|  Jane Doe  |   John Doe      |  Blah blah   |
|  Steve Ex  |   John Doe      |  Blah blah   |

目前我被困在这里:

function find_items_by_ref($ref) {
  db_connect();
  $query = sprintf("SELECT * FROM items WHERE reference LIKE '%s'", mysql_real_escape_string($ref));
  $result = mysql_query($query);
  $row = mysql_fetch_array($result);
  return $row;
}

我试过LIKECONTAINSlike '%' || TEXT || '%'等,但都不起作用。有什么想法吗?


我正在下面给出的答案中尝试这两种可能性。对于第一个,我遇到了一些麻烦。当我想echo从SQL Select获得的数组元素时,我会得到一个警告:非法的字符串偏移量'X'。。。错误如果我在其中一个检索到的数组上运行var_dump,这就是我得到的结果。我不太清楚出了什么问题。对我来说似乎是一个工作阵列:

array (size=16)
0 => string '37' (length=2)
'id' => string '37' (length=2)
1 => string 'Steve Ex' (length=8)
'name' => string 'Steve Ex' (length=8)
2 => string 'John Doe' (length=8)
'reference' => string 'John Doe' (length=8)
3 => string 'Blah blah' (length=9)
'etc' => string 'Blah blah' (length=9)

好的。解决了它。这个问题太愚蠢了。。。猜猜谁觉得自己是个真正的混蛋。不管怎样,问题是我试图将一个数字作为一行传递给SQL行。当用户想通过ID获取单行信息时,我错误地复制了我使用的Select函数。问题一直存在,我就像躲在树后面的大象一样错过了它。不管怎样,就在这里…很抱歉。工作代码为:

function find_items_by_ref($ref) {
  db_connect();
  $query = sprintf("SELECT * FROM items WHERE INSTR(reference,'".mysql_real_escape_string($ref)."')>'0' ORDER BY name ASC");
  $result = mysql_query($query);
  $result = db_result_to_array($result);
  return $result;
}

感谢@dimanic的帮助!

function find_items_by_ref($ref) {
  db_connect();
  $query = "SELECT * FROM items WHERE INSTR(reference,'".mysql_real_escape_string($ref)."')>'0'";
  $result = mysql_query($query);
  $row = mysql_fetch_array($result);
  return $row;
}

在这种情况下,INSTR比LIKE快

或者,如果你需要LIKE,你应该正确使用它:

$query = "SELECT * FROM items WHERE reference LIKE '%".mysql_real_escape_string($ref)."%'";