【问题标题】:How to get data from array to string php如何从数组中获取数据到字符串php
【发布时间】:2014-07-06 06:41:45
【问题描述】:

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

【问题讨论】:

  • foreach 结束后$test 包含最后分配的值。你期待什么?
  • 感谢您的回复。我是 php 新手,所以有些问题可能有点愚蠢,抱歉 :) 正如我之前写的 - 我想从数组中获取有效数据并写入我的数据库(mysql),这可能吗?
  • $test 仅在响应为 200 时才被初始化。可能是在某些早期迭代中它不满足该条件,因此未设置 $test,并且没有任何内容写入数据库.
  • 啊,不是。对于这种情况,我当然有另一条规则,如果不满足响应 200,则将警告写入数据库。我想知道,如何正确地将这些数据从 $test 变量写入 mysql 数据库,因为当我尝试对其进行序列化()或 json_encode 时 - 它可以工作,但仍然写入 30 多个(其中一半是重复的)字段到数据库。

标签: php mysql arrays variables get-headers


【解决方案1】:

首先,不要使用 MySQL 已弃用。

使用MySQLi(i 用于改进)http://www.php.net/manual/en/book.mysqli.php

您在array 变量上使用foreach,因此对于每个变量,它将INSERT 进入数据库,array 中有多少variables

$smthing 是什么?

您说 array 仅包含 3 个值,但您得到了超过 30 个 INSERTS 这可能是您没有关闭您的 foreach 这是需要 } 或者您收到来自 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


}

【讨论】:

  • 谢谢,你给了一个关于break的好主意; :) 真丢脸,不知道我是怎么错过的 :) 再次感谢!
猜你喜欢
  • 2018-08-16
  • 1970-01-01
  • 2020-11-06
  • 2019-07-03
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 2015-03-26
  • 2018-01-19
相关资源
最近更新 更多