2

以下脚本会生成包含所需数据的 txt 文件,但它会在文本文件中生成两次数据。

 mysql_connect($hostname_MySQLCon, $username_MySQLCon, "") or die(mysql_error()); 
 mysql_select_db($database_MySQLCon) or die(mysql_error()); 
 $data = mysql_query("
    SELECT sales_flat_order.increment_id, sales_flat_order.gift_message_id, sales_flat_order.status, gift_message.gift_message_id, gift_message.message
    FROM sales_flat_order
    JOIN gift_message ON sales_flat_order.gift_message_id = gift_message.gift_message_id
    WHERE sales_flat_order.gift_message_id IS NOT NULL
    GROUP BY sales_flat_order.increment_id
    /* AND sales_flat_order.status = 'pending' */;") 
 or die(mysql_error());  
 while($result = mysql_fetch_array( $data )) 
 { 
    $dataRow[] = implode("|", $result);
 } 
$theFile = 'orders-meta.txt';
if (!$handle = fopen($theFile, 'a')) {
    exit;}
if (fwrite($handle, implode("\r\n", $dataRow)) === FALSE) {
    echo "Cannot write to file ($theFile)";
exit;}
echo "Success, the file was written.";
fclose($handle);

txt 文件中的示例输出:

100000001|100000001|1121|1121|pending|pending|1121|gift message|gift message
100000002|100000002|1123|1123|pending|pending|1123|Gift message|Gift message

为什么它会产生每个值两次?以及如何更改它以使输出为:

100000001|1121|pending|1121|gift message
100000002|1123|pending|1123|Gift message

非常感谢任何帮助。

谢谢

4

4 回答 4

3

因为您使用的是mysql_fetch_array()而不是mysql_fetch_row().

默认$result_type为:mysql_fetch_array_MYSQL_BOTH

数组 mysql_fetch_array ( 资源 $result [, int $result_type = MYSQL_BOTH ] )

这将产生这样的数组:

array(
    0 => 100000001
    'increment_id' => 100000001,
    1 => 1121,
    'gift_message_id' => 1121,
    2 => 'pending',
    'status' => 'pending',
    3 => 1121,
    4 => 'gift message',
    'message' => 'gift message'
)

为什么你以如此低效的方式存储数据?为什么不这样做:

$theFile = 'orders-meta.txt';
if (!$handle = fopen($theFile, 'a')) {
    exit;
}

while($result = mysql_fetch_array( $data )) { 
    fwrite($handle, implode("|", $result));
    fwrite($handle, "\n\r");
} 

fclose($handle);
于 2012-10-04T11:05:56.020 回答
1

默认情况下,mysql_fetch_array返回具有数字键和关联键的混合数组 - 因此每个值都是重复的。将您的 fetch 行更改为:

mysql_fetch_array($data, MYSQL_ASSOC)
于 2012-10-04T11:05:52.933 回答
1

文档

返回与获取的行相对应的字符串数组,如果没有更多行,则返回 FALSE。返回数组的类型取决于 result_type 的定义方式。通过使用 MYSQL_BOTH(默认),您将获得一个包含关联索引和数字索引的数组。使用 MYSQL_ASSOC,你只能得到关联索引(因为 mysql_fetch_assoc() 有效),使用 MYSQL_NUM,你只能得到数字索引(因为 mysql_fetch_row() 有效)。

mysql_fetch_array获取每个结果两次,一次作为 assoc 数组,一次作为数字索引数组(默认情况下)。这就是为什么你会得到重复的行。

话虽如此,请不要mysql_*在弃用过程中使用它,阅读文档页面上的阅读框,然后单击链接PDO或链接mysqli_*,或链接herehere

于 2012-10-04T11:07:56.483 回答
0

阅读手册:

mysql_fetch_array ( 资源 $result [, int $result_type = MYSQL_BOTH ] )

然后尝试:

while($result = mysql_fetch_array( $data, MYSQL_NUM )) 
于 2012-10-04T11:05:40.507 回答