?
Solved

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

Posted on 2014-07-13
4
Medium Priority
?
675 Views
Last Modified: 2014-09-22
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

0
Comment
Question by:elastik
  • 2
  • 2
4 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 40193390
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
 
LVL 31

Assisted Solution

by:Marco Gasi
Marco Gasi earned 668 total points
ID: 40193410
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
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1332 total points
ID: 40193545
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
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1332 total points
ID: 40194408
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

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
Backups and Disaster RecoveryIn this post, we’ll look at strategies for backups and disaster recovery.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses
Course of the Month16 days, 19 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question