运行循环php的问题

时间:2015-10-01 19:10:42

标签: php loops curl

我编写了一个代码,用于从多个url的文本区域进行curl,以存储来自URL的响应数据。问题是编程只是在数据库中一次又一次地重复存储第一个数据。请帮我解决这个问题。

这是遇到问题的代码:

<?php
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
if(isset($_POST['submit']))
{

    $count=0;
    $url_text=$_POST['content'];
    $urls=explode(",",$url_text);
    if(count($urls)>20)
    {
        echo "Url Should not exceed 20";           
    }
    else
    {

        for($j=0;$j<count($urls);$j++)
        {

            if($urls[$j]!='')
            {

                $url=$urls[$j];
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_TIMEOUT, '180');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_ENCODING, "");
                $cUrlResponse = curl_exec($ch);
                $httpResponseArr = curl_getinfo($ch);
                curl_close($ch);

                $new=explode("<td>",$cUrlResponse);
                for($i=1;$i<count($new);$i++)
                {

                    $new_input=explode("</td>",$new[$i]);
                    $content_input=explode(":",$new_input[0]);
                    $content[]=trim($content_input[1]);

                }
                $stmt4 = $db->prepare("insert into example (data1,data2,data3) values ('$content[0]','$content[1]','$content[2]')");
                $stmt4->execute();
                $count++;

            }
            echo $count." Rows Inserted Successfully....";

        }

    }

}
?>
<form method="post" method="">

    <textarea name="content"></textarea>
    <br>
    <input type="submit" name="submit" value="Submit" />

</form>

2 个答案:

答案 0 :(得分:1)

您将项目附加到<label>Payment Method <select name="payment" id="payment" required> <option value="DC">Debit Card</option> <option value="CC">Credit Card</option> <option value="Cash">Cash</option> <option value="GB">Gold Bullion</option> </select> </label> 数组,但是您没有重置该数组,因此前三个值保持不变,然后将其插入到db中。

答案 1 :(得分:0)

您需要重置$content数组。你设置它的方式,数据只是叠加到它而不是覆盖。

content变量之前添加$content = array();

作为旁注,缩进将采用 LONG 方式:

$new