【问题标题】:php - dynamic mysql_query in for loop from url arrayphp - 来自 url 数组的 for 循环中的动态 mysql_query
【发布时间】:2013-07-10 11:01:13
【问题描述】:

我在堆栈上寻找过类似的东西,但没有完全一样的东西。

我(我想我)需要在循环中生成一个唯一的 MySQL 查询,因为每次迭代都需要查找不同的表。循环来自一个爆炸的 $_GET 数组。

问题是基于循环迭代创建一个不同命名的 mysql 查询。我已经在 $var 名称不同但不起作用的地方完成了它,我认为是因为它是字符串而不是变量?

任何帮助表示赞赏

$temps = explode(",", $_GET['temps']);
$tempCount = count($temps); 

for ($i=0; $i<$tempCount; $i++)
{
/*'normal' database lookup
$check = mysql_query("SELECT * FROM _db_".$temps[$i]."");       
    $checks = array();
    while ($row = mysql_fetch_assoc($check)) {
    $checks[] = $row;
    }*/


//here's where I'm trying to build a 'dynamic' lookup for each loop iteration

$checkTemp=$check.$temps[$i];
$checkTempArray=$check.$temps[$i].'Array';

$checkTemp = mysql_query("SELECT * FROM _db_".$temps[$i]."");       
    $checkTempArray = array();
    while ($row = mysql_fetch_assoc($checkTemp)) {
    $checkTempArray[] = $row;
    }
}

【问题讨论】:

  • $check 没有被使用
  • “不同名称”的 MySQL 查询是什么意思?
  • 我已经对其进行了修改,因此您可以看到每次迭代的 db 表名称都不同。因此,需要存储的数组必须具有不同的名称以供以后查找(foreach 等)。例如数组 $checkJohn 和 $checkSally
  • $checkTemp = mysql_query("SELECT * FROM db".$temp[$i]."");要么使用 $temps[$i] 要么只使用 $temp,$temp[$i] 没有任何意义
  • 谢谢,我已经修改了。但我也需要创建一个动态创建的数组,以供以后查找。这是我的主要问题

标签: php mysql for-loop


【解决方案1】:

如果我理解正确,您正在尝试在 $_GET["temps"] 中由 , 分隔的所有表中添加 SELECT *

$temps = explode(",", $_GET['temps']);
$tempCount = count($temps); 

$allResults = array();
for ($i=0; $i<$tempCount; $i++)
{
    $checkTemp = mysql_query("SELECT * FROM _db_".mysql_real_escape_string($temps[$i]));
    $allResults[$temps[$i]] = array();
    while ($row = mysql_fetch_assoc($checkTemp))
    {
        $allResults[$temps[$i]][] = $row;
    }
}
// Now for example $allResults["john"][3] contains the fourth row in the table _db_john
print_r($allResults["sally"][2]); // print the third row in _db_sally

【讨论】:

  • 嗨。我已经修改了我的代码以显示附加了 temp 变量的 _db。所以 url '&temps=john,sally' 将查找 _db_john 和 _db_sally
  • @gavin 我改变了答案,它现在将结果存储在数组中。
  • 谢谢,我试试看
【解决方案2】:

您的代码中似乎有错字

$checkTemp = mysql_query("SELECT * FROM db".$temp[$i].""); 

随便用

$temps[$i] or just  $temp 
$temp[$i] doesn't makes any sense

所以您的查询应该改为

$checkTemp = mysql_query("SELECT * FROM db".$temps[$i]."");  

编辑: 对于您的数组部分,您可以使用

 $$temp = array();
 while ($row = mysql_fetch_assoc($checkTemp)) {
    $$temp[] = $row;
 }

【讨论】:

  • 谢谢,boom_Shiva。我现在已经修改了。我还需要创建一个动态创建的数组,以供以后查找。这似乎不起作用
  • 我已经简化了,只使用了 $temps[i]。
猜你喜欢
  • 2010-12-16
  • 2019-03-18
  • 2013-05-31
  • 2014-11-07
  • 1970-01-01
  • 2021-03-06
  • 2011-01-30
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多