【问题标题】:Storing MySQL Database connections in Array将 MySQL 数据库连接存储在数组中
【发布时间】:2015-09-11 06:17:11
【问题描述】:

在查看我现有的一些代码时,我意识到我一直在打开和关闭远程数据库连接以获取有关数百个设备的信息。我现在正在尝试通过将数据库连接存储在一个数组中并在创建它之前检查特定连接是否已按名称存在来解决此问题。

$mysql_connections = array();

$devices = mysql_query("SELECT * FROM devices ORDER BY name ASC", $dp_conn);

while($row = mysql_fetch_array($devices))
{
    $whmcs_site = $row['whmcs_site'];
    $whmcs_id = $row['whmcs_id'];

    /* WHMCS Service */
    if ($whmcs_site != "" && $whmcs_id != "")
    {
        $site = get_site_details($whmcs_site, $dp_conn);

        if (in_array($site['name'], $mysql_connections))
        {
            echo "Connection already exists</br>";
            $whmcs = $mysql_connections[$site['name']];
        }
        else
        {
            echo "No connection exists...creating it named" . $site['name'] . " </br>";

            $whmcs = whmcs_connect($site);
            $mysql_connections[$site['name']] = $whmcs;
        }

只有 2 个可能的 MySQL 数据库,因此 in_array() 检查在存储这两个数据库后应该返回 true。出于某种原因,它永远不会找到现有的条目,因此它会继续在每次迭代中产生新的连接。谁能指出这里的问题是什么?

【问题讨论】:

  • 您是否进行过任何调试尝试?代码执行与预期有何不同?为什么你还在使用已弃用的 mysql_* 函数?

标签: php mysql arrays object


【解决方案1】:

您需要检查array_key_exists() 或类似名称,而不是in_array(),因为您正在比较密钥。

【讨论】:

  • 非常感谢。如果允许,我会在 6 分钟内接受。我将不得不回去阅读这些以记住未来的区别。
猜你喜欢
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 2017-07-02
  • 2012-04-25
  • 2020-06-07
  • 1970-01-01
相关资源
最近更新 更多