php script won't write remote mysql array to local file

Hello everyone,

I am trying to write a script that will select two columns from a remote mysql database and write them to a local file. I am pretty new to php. After I run the script no text file is created. No errors.  I have lamp running. I am also able to echo the info that I would like to write to a local file. After I run the script I do not see the data.txt file created in the local directory. Any suggestions?

<?php

$test=5;
echo $test;

// mysqli
$mysqli = new mysqli("databasehost", "dbuser", "dbpassword", "dbasename");

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

if ($result = mysqli_query($mysqli, "SELECT * FROM dbtable")) {
    printf("Select returned %d rows.\n", mysqli_num_rows($result));

while($row = $result->fetch_array())
  {
$results = print_r($b, true); 
 file_put_contents('data.txt', print_r($result, true));

  echo $row['user_email'] . " " . $row['user_pass'];
  echo "<br />";
  }

    /* free result set */
    mysqli_free_result($result);
}
?>

Open in new window

elastikAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Marco GasiFreelancerCommented:
file_put_contents accept a string as data to write and you're passing it an array. You can do this:
file_put_contents('data.txt', implode(',', $result));

Open in new window

You can read about implode here: http://docs.php.net/manual/en/function.implode.php
0
Marco GasiFreelancerCommented:
I apologize, my previous comment was wrong.
Since the $result is a mysqli_result, I think you can't use this way. First you're trying to save the file within a loop which processes the result itself; secondly, probably you should (i never tested it) use  file_put_contents('data.txt', print_r($result->fetch_array(), true)).
I think you should try this:
if ($result = mysqli_query($mysqli, "SELECT * FROM dbtable")) {
    printf("Select returned %d rows.\n", mysqli_num_rows($result));
    
    file_put_contents('data.txt', print_r($result->fetch_array(), true));
   while($row = $result->fetch_array())
   {
       $results = print_r($b, true);
       echo $row['user_email'] . " " . $row['user_pass'];
       echo "<br />";
   }

    /* free result set */
    mysqli_free_result($result);
}

Open in new window

0
Ray PaseurCommented:
Where to start...?

Maybe if you're new to PHP this will help:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

If you're new to PHP and MySQL this may help:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Most PHP functions return values.  If you're not 100% sure what the function returns, you can look it up on the PHP.net web site.

When you're not sure about the contents of a variable, you can use var_dump() to print it out.

PHP if() statements have else clauses.  This is very important in programming.  If you do not have an else clause for every if() control structure, ask yourself, "Why not?"
0
Ray PaseurCommented:
Since I do not have your data base, this is untested code, but hopefully you can read the code and comments and recognize our motivations for writing it this way.  Please read it over (and especially, please read the man page references) and then post back if you still have questions.

<?php // demo/temp_elastik.php

// SEE: http://www.experts-exchange.com/Database/MySQL/Q_28474886.html
// REF: http://php.net/manual/en/mysqli.overview.php
// REF: http://php.net/manual/en/class.mysqli.php
// REF: http://php.net/manual/en/class.mysqli-stmt.php
// REF: http://php.net/manual/en/class.mysqli-result.php
// REF: http://php.net/manual/en/class.mysqli-warning.php
// REF: http://php.net/manual/en/class.mysqli-sql-exception.php <-- DID NOT WORK PHP 5.3+, MySQL 5.1+
// REF: http://php.net/manual/en/mysqli.construct.php
// REF: http://php.net/manual/en/mysqli.real-escape-string.php
// REF: http://php.net/manual/en/mysqli.query.php
// REF: http://php.net/manual/en/mysqli.errno.php
// REF: http://php.net/manual/en/mysqli.error.php
// REF: http://php.net/manual/en/mysqli.insert-id.php
// REF: http://php.net/manual/en/mysqli-result.num-rows.php
// REF: http://php.net/manual/en/mysqli-result.fetch-array.php
// REF: http://php.net/manual/en/mysqli-result.fetch-object.php

// MAKE THE PHP ERRORS VISIBLE
error_reporting(E_ALL);
ini_set('display_errors', TRUE);

// MAKE THE BROWSER OUTPUT EASY TO READ
echo '<pre>';

// ASSIGN A VARIABLE AND WRITE IT TO THE BROWSER OUTPUT STREAM (WHY?)
$test=5;
echo $test;

// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";

// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);

// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
    $err
    = "CONNECT FAIL: "
    . $mysqli->connect_errno
    . ' '
    . $mysqli->connect_error
    ;
    trigger_error($err, E_USER_ERROR);
}

// ACTIVATE THIS TO SHOW WHAT THE DB CONNECTION OBJECT LOOKS LIKE
// var_dump($mysqli);

// ALWAYS CREATE THE QUERY STRING IN A SEPARATE VARIABLE
// SO YOU CAN PRINT IT OUT IF IT FAILS FOR ANY REASON
// NEVER USE SELECT * LIKE WE HAVE HERE, INSTEAD SELECT
// THE COLUMNS EXPLICITLY BY NAME
$sql = "SELECT * FROM dbtable";

// RUN THE QUERY, THEN TEST FOR ERRORS
$res = $mysqli->query($sql);

// IF mysqli::query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res = $mysqli->query($sql))
{
    $err
    = 'QUERY FAILURE:'
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    . ' QUERY: '
    . $sql
    ;
    trigger_error($err, E_USER_ERROR);
}

// ACTIVATE THIS TO SHOW THE RESULTS OF THE QUERY
// var_dump($res);

// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num     = $res->num_rows;
$num_fmt = number_format($num);
if (!$num)
{
    echo PHP_EOL . "QUERY: $sql ";
    echo PHP_EOL . "FOUND NO DATA ";
}
else
{
    echo PHP_EOL . "QUERY: $sql ";
    echo PHP_EOL . "$num_fmt ROWS OF DATA ";
}
echo PHP_EOL;

// ITERATE OVER THE RESULTS SET AS AN ASSOCIATIVE ARRAY TO SHOW WHAT WE FOUND
echo PHP_EOL . 'USING MySQLi_Result::Fetch_<i>Assoc</i>(): ';
echo PHP_EOL;
while ($row = $res->fetch_assoc())
{
    // ROW BY ROW PROCESSING IS DONE HERE
    print_r($row);
    echo PHP_EOL;

    // ACCUMULATE THE ROWS OF DATA HERE
    $rows[] = implode(',', $row);
}

// COLLAPSE THE ROWS ARRAY INTO A STRING
$out = implode(PHP_EOL, $rows);
if (!empty($out))
{
    if (file_put_contents('data.txt', $out))
    {
        echo PHP_EOL . "DATA WRITTEN SUCCESSFULLY";
    }
    else
    {
        echo PHP_EOL . "UNABLE TO WRITE DATA";
    }
}
else
{
    echo PHP_EOL . "NOTHING TO WRITE";
}

Open in new window

Best of luck with your PHP adventures, ~Ray
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.