如何在循环中打开链接?

时间:2018-04-04 06:09:22

标签: javascript php mysql loops

我编写了一个脚本来更新我的数据库,每次更新过程完成后我都要打开一个新链接

<?php
$con = mysql_connect("localhost","user","pass","db");
if (!$con){
    die ("connection error: ". mysql_error());
}
mysql_query("set @date1=(select date_add(max(date),interval 1 day) from mail.PB)");
mysql_query("set @date2=(select max(date) from Report.Traffic_City)");
$b=mysql_query("select count(*) day from date.datemonthyear_telkomsel where date between @date1 and @date2");
$day=array();
while($row=mysql_fetch_array($b)){
    for ($i=0; $i < $row['day']; $i++) {
mysql_query..................
$link="<script>window.open('http://localhost/link/mail/report.php');</script>";
    echo $link;
  } 
}
?>

使用上面的脚本,我的数据更新成功,但循环过程完成后链接打开(在循环的同时打开多次)。

report.php是发送上次更新数据的脚本。 我的计划是,每次数据更新过程完成打开report.php链接(所以发送的数据是最新数据),如果有3个最近的数据

  

(例如2018-03-31,2018-04-01,2018-04-02)

所以发送的数据是3封电子邮件,其中包含2018-03-31,2018-04-01,2018-04-02的数据。

1 个答案:

答案 0 :(得分:2)

有几个问题:

  1. 您的PHP代码正在服务器上运行,构建响应以发送给客户端。该响应可能是缓冲的,因此如果您希望输出主动进行,则需要刷新输出流。

    根据this answer,您还需要确保在循环之前设置响应的charset

    header( 'Content-type: text/html; charset=utf-8' );
    

    (假设您使用的是UTF-8。)

  2. 浏览器可能拒绝打开脚本要求作为页面加载的一部分的弹出窗口,并且几乎肯定会拒绝打开重复的窗口。相反,我建议只输出页面内容。

  3. 所以也许:

    <?php
    header( 'Content-type: text/html; charset=utf-8' );
    $con = mysql_connect("localhost","user","pass","db");
    if (!$con){
        die ("connection error: ". mysql_error());
    }
    mysql_query("set @date1=(select date_add(max(date),interval 1 day) from mail.PB)");
    mysql_query("set @date2=(select max(date) from Report.Traffic_City)");
    $b=mysql_query("select count(*) day from date.datemonthyear_telkomsel where date between @date1 and @date2");
    $day=array();
    while($row=mysql_fetch_array($b)){
        for ($i=0; $i < $row['day']; $i++) {
            // mysql_query..................
            $msg="<p>Some useful information here...</p>";
            echo $msg;
        } 
    }
    ?>
    

    如果显示report.php页面而不仅仅是文本非常重要,您可以通过ajax检索它并在页面上的元素中显示其内容,而不是使用弹出窗口,并使用其他脚本标记在循环中输出以刷新内容。 (或者将其加载为iframe并刷新它。)