gpt4 book ai didi

PHP 将字段放入数组并更新另一个表上的数组结果不起作用?

转载 作者:行者123 更新时间:2023-11-29 11:50:57 24 4
gpt4 key购买 nike

您好:)可能我的标题有点难以理解,抱歉我无法使其变得更简短。不管怎样,我所做的是创建了一个脚本,该脚本将从表中获取列数据,其中行上的时间戳已超过 30 天。然后,它将把这些 ID 存储在一个数组中,然后循环访问另一个表上的数组。遗憾的是,没有任何反应,并且当我运行脚本时似乎没有收到错误。

脚本内容如下:

<?php

// connects to the DB
include ('connectdb.php');

//query that gets the "trade_id" from the table with all the trades, where the "open_time" is older than 30 days, "close_price" is NULL.
$result = $db->query("SELECT trade_id FROM trades WHERE open_time < (NOW() - INTERVAL 30 DAYS) AND close_price IS NULL");
// create an array
$rows = array();
// loop through the table and drop the data into the array
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$rows[] = $row;
}

$count = count($rows);
$i = 0;
//loops through the table
while($i < $count){
//updates the table "orders" where the unique_ID matches the trade_ID, and will change the column "notified" to -1
$update = $db->prepare("UPDATE orders SET notified=? WHERE unique_id=$rows[$i]");
$update->execute(array(-1));
//updates the table "trades" where the trade_ID matches the trade_ID, and will change the column "close_price" to -1
$update2 = $db->prepare("UPDATE trades SET close_price=? WHERE trade_id=$rows[$i]");
$update2->execute(array(-1));
$i++;
}
// Closes connection
$db = null;

?>

我在整个代码中都留下了注释,但是我确信我在 $result 中完成的时间脚本可能是错误的。再次,我不确定为什么它不更新行。我非常感谢任何帮助:)

最佳答案

这是我如何尝试的粗略答案。

$result = $db->query("SELECT trade_id FROM trades WHERE open_time < (NOW() - INTERVAL 30 DAYS) AND close_price IS NULL");
// create an array
$rows = array();
// loop through the table and drop the data into the array
$rows = $result->fetchAll(PDO::FETCH_ASSOC)){
foreach($rows as $row){
//updates the table "orders" where the unique_ID matches the trade_ID, and will change the column "notified" to -1
$update = $db->prepare("UPDATE orders SET notified=? WHERE unique_id= ?");
$update->execute(array(-1, $row['trade_id']));
//updates the table "trades" where the trade_ID matches the trade_ID, and will change the column "close_price" to -1
$update2 = $db->prepare("UPDATE trades SET close_price=? WHERE trade_id=?");
$update2->execute(array(-1, $row['trade_id']));
}
// Closes connection
$db = null;
  1. 使用 fetchAll 可以一次性获取所有记录,不需要 while 和变量赋值。
  2. 使用 foreach 而不是 while,这样您就不需要创建自己的计数器。
  3. 参数化更新查询;否则可能会遭受二阶 SQL 注入(inject)..

关于PHP 将字段放入数组并更新另一个表上的数组结果不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34075667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com