php - PHP while 循环中的 SQL SELECT

标签 php mysql loops while-loop

我想从中选择数据的一组表和字段。我试过下面的代码但没有成功。任何人都可以向我解释为什么这不起作用,如果可能的话,如何让它起作用。

$fields = "table1.field1, table2.field2, table3.field3, table4.field4";
$tables = "table1, table2, table3, table4";
$table = explode(', ', $tables); //explode the tables string
$field = explode(', ', $fields); //explode the fields string


$i=1;
while ($i<=4) { 
$sql = 'SELECT ' . $field[$i] . ' FROM ' . $table[$i] . ' WHERE ' . $field[$i] . ' LIKE "%' . $str . '%";';
$results = $readConn->query($sql);
$i++;
var_dump($results);
}

最佳答案

我能看到两件事:

1) 你忘记了 SELECT 关键字:

$sql = 'SELECT ' .  $field[$i] . ' FROM ' ...etc...

2) 在 SQL 中,字符串应该用单引号转义,而不是双引号。结果应该类似于 LIKE '%foo%' 而不是 LIKE "%foo%"

关于php - PHP while 循环中的 SQL SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4543073/

相关文章:

php - mysql_fetch_array() 期望参数 1 是资源,给定的字符串

php - 从 mysql 查询填充选择下拉列表时出现重复值

php - 从mysql中的同一个表获取链接行

php - Yii:在 mysql 服务器上使用自动提交关闭的事件记录

php - 分页: get total number of page

mysql - 不确定如何表达 COUNT() 语句

php - 一种在MySQL数据库中查找表单表的方法

java - 无法弄清楚为什么它没有正确解决

c# - 在 C# 中设置 for 循环迭代次数的限制

javascript - 在下面的代码中,为什么 j 应该小于 i,为什么 j<=n 不起作用(第 4 行)?