mysql-pdo:计算动量指标时的奇怪循环

vuktfyat  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(259)

我试图从导入的csv文件计算动量指标,这是股票市场的历史数据。我制作了“momentum\u data”表,其中包含“date,close,close14,momentum”列。我遇到的问题是用pdo将我的数据从php插入到momentum-u数据表中。
我做的最贴切的解释是使用以下代码:

foreach ($sql as $data) {
$tanggal = $data['Date'];
$close = $data['Close'];
$close[] = $data['Close'];
$jumlah = count($close);
$momentum= 0;

        for($i=14;$i<$jumlah;$i++){
          $close1 = $close[$i-14];
          $momentum = $close[$i]/$close1*100;

  $sql2->bindParam(':close14', $close);
  $sql2->bindParam(':Date', $tanggal);
    $sql2->bindParam(':close', $close1);
    $sql2->bindParam(':momentum', $momentum);
    $sql2->execute();}}

和查询:

$conn = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $pdo->prepare("SELECT * FROM csv_data ORDER BY Date");

$sql->execute();和

$conn = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql2 = $conn->prepare("INSERT INTO momentum_data VALUES (:Date,:close,:close14,:momentum)");

数据被插入到数据库中,但数据是根据数据所在的行复制的。输出将如下所示

|no|data1|data2|
|1 |1    |1    |
|2 |2    |2    |
|2 |2    |2    |
|3 |3    |3    |
|3 |3    |3    |
|3 |3    |3    |

我的代码有什么问题吗(很明显)。任何帮助或暗示都会非常感激。对不起,英语太差了。

disho6za

disho6za1#

preparing 查询和 binding 循环外的参数只需在执行语句之前重新分配循环内的变量即可~尽管我发现这里的变量命名有点混乱。

$conn = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $conn->prepare("insert into `momentum_data` (
``` `date` ,  `close` ,  `close14` ,  `momentum` )值(:date,:close,:close14,:momentum)“);如果($stmt){

$stmt->bindParam(':date', $tanggal );
$stmt->bindParam(':close', $close1 );
$stmt->bindParam(':close14', $close );
$stmt->bindParam(':momentum', $momentum );

$sql='select * from `csv_data` order by `date`;';
$results=$conn->query( $sql );

$tmp=array();/* it was confusing having $close and $close[] */

while( $rs=$results->fetch_object() ){

    $tanggal    = $rs->date;
    $close      = $rs->close;
    $tmp[]      = $rs->close;
    $jumlah     = count( $tmp );
    $momentum   = 0;

    for( $i=14; $i < $jumlah; $i++ ){
        $close1 = $tmp[ $i-14 ];
        $momentum = $tmp[ $i ] / $close1 * 100;
        $stmt->execute();
    }
}

}

相关问题