-1

php数组有问题。我正在尝试发送带有写入 $variable 数组的路径的 get_headers() 请求,回答我想写入 MySQL 数据库,已经花了几个小时,但没有找到如何做到这一点。它只返回 1 个结果,但如果 echo 结果来自数组 - 例如可以看到 3 个结果。请帮帮我:)

    foreach($array_variable as $variable) {
$url = "http://".$site.$variable;
$file_headers = @get_headers($url);
if($file_headers[0] == 'HTTP/1.1 200 OK') {

    $test = $url;
     echo $test;  //here it works fine, I can see all available results
      $sql = mysql_query("INSERT INTO table (col_1, col_2) VALUES ($smthing, $test)"); //here problem is that result duplicates many-many times

}
 echo $test; //but here I have problems, can see only 1 result (last one)
 $sql = mysql_query("INSERT INTO table (col_1, col_2) VALUES ($smthing, $test)"); //here problem is, only 1 result goes to our database
4

1 回答 1

0

首先,不要使用MySQL它已弃用的东西。

使用MySQLi(我是为了改进)http://www.php.net/manual/en/book.mysqli.php

您使用一个foreach变量array,因此对于每个变量它将进入数据库,有INSERT多少?variablesarray

是什么$smthing

你说array唯一包含 3 个值但你得到超过 30INSERTS可能是你没有关闭你的foreachthis 是需要的,}或者你得到了多个回复headers

如果你在循环外foreach回显,你只会看到数组的最后一个值。

这可能也有帮助https://stackoverflow.com/a/12782327/3754261

试试这个:

foreach($array_variable as $variable) {
    $url = "http://".$site.$variable;
    $file_headers = @get_headers($url);
    if($file_headers[0] == 'HTTP/1.1 200 OK') {

    $test = $url;
    echo $test;  //here it works fine, I can see all available results
    $sql = mysql_query("INSERT INTO table (col_1, col_2) VALUES ($smthing, $test)");     //here problem is that result duplicates many-many times
    }

}

在没有条件语句的情况下也值得尝试

你的结果是什么?

foreach($array_variable as $variable) {
    $url = "http://".$site.$variable;
    $file_headers = @get_headers($url);

    $test = $url;
    echo $test;  //here it works fine, I can see all available results
    $sql = mysql_query("INSERT INTO table (col_1, col_2) VALUES ($smthing, $test)");     //here problem is that result duplicates many-many times


}
于 2014-07-06T08:46:01.547 回答