aocferreira
aocferreira

Reputation: 693

PHP script to read from database

I have a database named teste with a table called exemplo with 2 columns (id, nome): Want a php script to select all the information in the nome column, and echo that information and place them in a txt file. What's wrong in the code? I can only see the first value and not the second.. And with an infinite loop!

$link = mysql_connect('localhost', 'root', '123');
if (!$link) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db('teste', $link);

/* Desired */
$file = fopen("myfile.txt","w");

$result = mysql_query("SELECT * FROM exemplo");
$array = mysql_fetch_array($result);
while ($array) {
  echo $array['nome'];

  fputs($file ,$array['nome']); 
}

mysql_close($link);

Upvotes: 1

Views: 1497

Answers (5)

Mat
Mat

Reputation: 206699

mysql_fetch_array returns a single row. You need to call it in a loop:

while ($array = mysql_fetch_array($result)) {
    echo $array['nome'], "\n";
    // do more stuff
}

Upvotes: 0

castis
castis

Reputation: 8223

This should work. you were leaving fputs out of the data loop.

<?php

$link = mysql_connect('localhost', 'root', '123');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('teste', $link);

/* Desired */

$file = fopen("myfile.txt","w");

$result = mysql_query("SELECT * FROM exemplo");
while($array = mysql_fetch_array($result))
{
    echo $array['nome'];
    fputs($file, $array['nome'] ."\n");
}

mysql_close($link);

Upvotes: 0

onteria_
onteria_

Reputation: 70507

That's because mysql_fetch_array only returns one result at a time, so $array is always true. You want this:

while ($array = mysql_fetch_array($result)) {
  echo $array['nome'];
  fputs($file ,$array['nome']); 
}

Upvotes: 0

Marc B
Marc B

Reputation: 360702

    $array = mysql_fetch_array($result);

This only fetches one row of results. It doesn't stuff the entire result set into your array. You need to do:

while($row = mysql_fetch_array($result)) {
   echo $row['nome'];
   fputs($file, $row['nome']);
}

Upvotes: 3

tim
tim

Reputation: 10176

You assign $array once and than loop over it in while($array) so this keeps running and running as $array is unchanged! Try changing your code like that:

<?php

        $link = mysql_connect('localhost', 'root', '123');
        if (!$link) {
                die('Could not connect: ' . mysql_error());
        }

        mysql_select_db('teste', $link);

        /* Desired */

        $file = fopen("myfile.txt","w");

        $result = mysql_query("SELECT * FROM exemplo");
        while ($array = mysql_fetch_array($result)) {
        echo $array['nome'];

        fputs($file ,$array['nome']); }
        mysql_close($link);
?>

Upvotes: 0

Related Questions