【问题标题】:Push results from MYSQL Query into an Array将 MYSQL 查询的结果推送到数组中
【发布时间】:2014-02-03 08:54:57
【问题描述】:

我在使用以下功能时遇到问题。基本上它应该做的是检查数组中的每个项目 ($idDiscontinuedArray) 是否是其各自表中的已终止值(1 或 0)。

现在我不确定将这些答案放在一个数组中以使下一部分更简单。目前它会单独吐出$rows。

结果是:Array ( [discontinued] => 1, ) Array ( [discontinued] => 1 ) Array ( [discontinued] => 0 ) Array ( [discontinued] => 0 ) Array ( [discontinued] => 1 ).... 我宁愿有Array [1] => 1 [2] => 1 [3] => 0 [4] => 0 [5] => 1....

脚本的下一部分是检查 ALL $rows = 1 是否意味着脚本结束。如果不是这种情况,这将运行函数changeDiscontinued($dbh, $id, $idDiscontinuedArray)。

function checkDiscontinued($dbh, $idDiscontinuedArray) {
try {
    foreach ($idDiscontinuedArray as $id) {
        $stmt = $dbh->query("SELECT discontinued FROM `$id` ORDER BY `date` DESC LIMIT 1");
        $rows = $stmt->fetch(PDO::FETCH_ASSOC);
        print_r($rows);
        }
        if $rows['discontinued'] == TRUE) { 
            //echo $id . "Action if true";
        } else {
            changeDiscontinued($dbh, $id, $idDiscontinuedArray);
            echo $id . "Items already discontinued!";
            }       
    }
    catch (PDOException $e) {
    echo $e->getMessage();
    }
}

【问题讨论】:

  • else 语句中的 $id 变量将始终是 $idDiscontinuedArray 中的最后一个值,这是您的意图吗? changeDiscontinued() 应该做什么?
  • 您使用 $id 作为表名,您打算这样做吗?
  • 有人能说 SQL 注入漏洞很重要吗?您已经在使用 PDO,请准备好该语句...
  • 贾斯汀是什么意思?愿意分享吗?

标签: php arrays function if-statement foreach


【解决方案1】:

我没有测试这段代码,但它检查了准备好的语句,以及如何将项目推送到数组中。如果您需要更多帮助,我们可以进行聊天。

$discont = array();

function checkDiscontinued($dbh, $idDiscontinuedArray) {
try {
    foreach ($idDiscontinuedArray as $id) {
        $sql = $dbh->prepare("SELECT discontinued FROM $id ORDER BY `date` DESC LIMIT 1");
        $stmt = $sql->execute(array($id));
        $rows = $stmt->fetch(PDO::FETCH_ASSOC);
        print_r($rows);
        }
        if $rows['discontinued'] == TRUE) { 
            //echo $id . "Action if true";
        } else {
            changeDiscontinued($dbh, $id, $idDiscontinuedArray);
            echo $id . "Items already discontinued!";
            array_push($doscont, $id);
            }       
    }
    catch (PDOException $e) {
        echo $e->getMessage();
    }
}

【讨论】:

  • 如果这对您有用,请不要忘记将其标记为答案。
  • 感谢您的回复 - 我收到错误 - SQLSTATE[42000]: 语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 ''19474' ORDER BY date DESC LIMIT 1' 附近使用正确的语法
  • 尝试在 ? 周围加上反引号,即 sql 语句中的?。
  • 让它工作只是因为 $id 不是一个数组,它是一个单一的数字,foreach 循环处理不同的 id。现在,当 mysql 表实际上为真时,检索到的答案为假。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多