0

我正在查询一个数据库以获取与新闻文章相关的产品库存代码

$result = mysql_query('
SELECT stockcode FROM news_related WHERE news = "'.$news_id.'"');

然后我需要使用从 stockcode 列获取的数据来查询第二个数据库。我正在使用

$rows = mysql_fetch_array($result);

将信息放入数组中。如何在第二个 mysql 查询中使用该数组?

$also_result = mysql_query("SELECT * FROM WebProducts
WHERE WebProducts.stockcode THE ARRAY GOES HERE AND WebProducts.visible='Y'") or  die(mysql_error());`**
4

2 回答 2

2

对我来说听起来像是一个简单的加入。

mysql_query("SELECT * FROM WebProducts p
JOIN news_related n
ON p.stockcode = n.stockcode
WHERE n.news = " . $news_id . "
AND p.visible='Y'");
于 2013-09-06T08:27:49.573 回答
1

single query类似的Tr ,

$result = mysql_query('SELECT * FROM WebProducts WHERE WebProducts.stockcode IN 
             (SELECT stockcode FROM news_related WHERE news = "'.$news_id.'"
               AND WebProducts.visible="Y")');

从你的方法来看,它应该是,

$arrStock=array();
while($rows = mysql_fetch_array($result))
{
   $arrStock[]=$rows['stockcode'];
}
if(!empty($arrStock))
{
    $also_result=mysql_query("SELECT * FROM WebProducts WHERE WebProducts.stockcode
                  IN (".implode(',',$arrStock)." AND WebProducts.visible='Y'");

}

你知道second parametermysql_query()connection identifier,在你的情况下,two databases你应该有2 connections喜欢$con1$con2

$result = mysql_query('SELECT * FROM WebProducts WHERE WebProducts.stockcode IN 
             (SELECT stockcode FROM news_related WHERE news = "'.$news_id.'"
               AND WebProducts.visible="Y")',$con1);// use $con1 for first db

第二个查询中

  $also_result=mysql_query("SELECT * FROM WebProducts WHERE WebProducts.stockcode
              IN (".implode(',',$arrStock)." AND WebProducts.visible='Y'",$con2);
  // use $con2 for second db

mysql_deprecatedPHP中删除upcoming versions,因此请使用mysqli_*

于 2013-09-06T08:26:08.593 回答