0

I have a column named ip_management.id_address in my database. I want to select all IP addresses and save them in a flat file (.txt). I tried to put them into an array first and then save it to text file.

Here's my code:

$query = "SELECT ip_address FROM ip_management";
$result = mysql_query($query);
$result_array = array();
while($row = mysql_fetch_assoc($result)) {
    $result_array[] = $row;
}                 
print_r($result_array);
$file_handle = fopen($create_name, 'w') or die("Error: Can't open file");
foreach($result_array as $key => $value) {
    fwrite($file_handle,$value."|");
}

But I get this result in my text file:

Array|Array|Array|...

I want IP addresses to appear in my text file, something like this:

10.10.10.10|11.11.11.11|12.12.12.12|...

What's wrong with my code?

toro2k
  • 19,020
  • 7
  • 64
  • 71
user2699175
  • 929
  • 2
  • 9
  • 16
  • result of `print_r ($result_array);` ? – Sahil Mittal Sep 19 '13 at 06:34
  • Avoid using the `mysql_*` functions if you can, they are [deprecated since PHP 5.5](http://www.php.net/manual/en/function.mysql-query.php) and they will be removed in future versions. – toro2k Sep 19 '13 at 07:14

3 Answers3

1

You want to write the ip address element of the array to file, not the entire row.

So change the code that writes to file:

fwrite ($file_handle, $value['ip_address'] . '|');
xyz
  • 116
  • 4
1

please use following code i have made some changes it also reduces your line of code

<?php

$query = "SELECT ip_address FROM ip_management";
$result = mysql_query($query);

while($row = mysql_fetch_array($result)) {
    $str.=$row['ip_address']."|";
}                 

$file_handle = fopen($create_name, 'w') or die("Error: Can't open file");
fwrite($file_handle,$str);
fclose($file_handle);

?>
Faizan Khan
  • 638
  • 6
  • 13
0

Change this line:

 { $result_array[] = $row; }

to

 { $result_array[] = $row['ip_address']; }
Arfeen
  • 2,553
  • 5
  • 29
  • 48