0

this php code for sql query, if I have multi sql sever into text file and I want get servers from this file. how I can save var_dump for each sever into "serverip.txt"

<?

$list =file('servers.txt');
$username = "root";
$password = "1";
foreach($list as $server)
$link= connecttodb($server,$username,$password);
function connecttodb($server,$username,$password)
{

$rez=fopen("test.txt","ab");
   if ($link=mysql_connect ("$server","$username","$password",TRUE))
   {
   fwrite($rez,"".$server." \r\n");
    echo "Connected successfully to >> " .$server ;

        $result = mysql_query('SHOW DATABASES');
echo "<br>";

ob_flush();
ob_start();
while ($row = mysql_fetch_assoc($result)) {
   var_dump($row);
    file_put_contents("$server.txt", ob_get_flush());
}


    }

}
ini_set('max_execution_time', 10);
return $link;
    ?>

I have this error

Warning: file_put_contents(ServerIp .txt) [function.file-put-contents]: failed to open stream: Invalid argument in C:\AppServ\www\connectdb.php on line 24

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Yasser Abo Reida
  • 353
  • 1
  • 4
  • 8
  • Don't. Use an *actual* encoding format like [JSON](http://php.net/manual/en/function.json-encode.php). – Sammitch Aug 13 '16 at 01:04
  • Don't. Use an actual encoding format like JSON. ??? how ?? – Yasser Abo Reida Aug 13 '16 at 01:06
  • try `ob_start()` and then `ob_get_clean();` – ArtisticPhoenix Aug 13 '16 at 01:23
  • I typically dont use output buffering this way, but I think the main issue is this. `The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE flag. Otherwise ob_get_flush() will not work.` As in `ob_start(null, 0, PHP_OUTPUT_HANDLER_FLUSHABLE )` – ArtisticPhoenix Aug 13 '16 at 01:34
  • @ArtisiticPhoenix I've had to do something similar to this before where I had to assign a variable to an `ob_` function and set it outside the conditionals. Rather than injecting the `ob_` function inside the `file_put_contents()` function. – Funk Forty Niner Aug 13 '16 at 01:36
  • @Fred-ii- yea it could be creating a PHP warning, you know the one, I forget what it says ... lol When you try to use the return value in a write context. – ArtisticPhoenix Aug 13 '16 at 02:01

2 Answers2

2

Perhaps something more precise, like print_r would work, where it has a mode for storing the output

while ($row = mysql_fetch_assoc($result)) {
    file_put_contents("$server.txt", print_r($row, true));
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
0

I think instead of

ob_get_flush()

You want

$var = ob_get_clean();
file_put_contents("$server.txt", $var );

To put it all togather you would need to do this

while ($row = mysql_fetch_assoc($result)) {
   ob_start();
   var_dump($row);
   file_put_contents("$server.txt",ob_get_clean());
}

http://php.net/manual/en/function.ob-get-clean.php

Get current buffer contents and delete current output buffer ... Returns the contents of the output buffer and end output buffering. If output buffering isn't active then FALSE is returned.

-Note- the end output buffering this is why we need to restart it ob_start() on each iteration of the loop.

For ob_get_flush()

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE flag. Otherwise ob_get_flush() will not work.

That said it may not be the best approach for your goal. As an alternative method, you can use this function

function getVarType( $var, $escapeHtml = true ){
    $strArg = 'unknown';
    switch ( gettype( $var ) ){
        case 'boolean':
            return ( $var ? 'true' : 'false' );
        case 'integer':
            return intval( $var );
        case 'double':
            return floatval( $var );
        case 'string':
            if( $escapeHtml ){
                $var = htmlentities( $var, ENT_NOQUOTES, 'UTF-8', false);
            }

            return "'".$var."'";
        case 'resource':
            return 'Resource id #'.intval( $var );
        case 'NULL':
            return 'NULL';
        case 'array':
            return "Array";
        case 'object':
            return 'Object('.get_class( $var ).')';
        case 'unknown type':
        default:
            return'UNKNOWN TYPE';
    }
}  

 $row = array_map( 'getVarType', $row );

However I think in PHP 7 they reversed the Parameters for array map. This is from an Exception/Error handling class I just wrote, you can modify it to more closely match var_dump if you want. Currently, it's setup to match the exception stack trace printout.

By the way if you want a really killer debuggin class, you can use the one from my framework

https://github.com/ArtisticPhoenix/Evo/blob/master/EVO/Debug.php

With some small modification it may fit your needs ( perhaps a bit overkill )

This is what it outputs

$G = ['one'=>1, 'two' => 2, 3=>['foo', 'bar']];
EVO_Debug::dump( $G );

==================================== EVO_DEBUG::DUMP =====================================
Output from FILE[ C:\UniServerZ\www\Evo\EVO\bootstrap.php ] on LINE[ 72 ]
------------------------------------------------------------------------------------------
array(3){
     ["one"] => int(1),
     ["two"] => int(2),
     [3] => array(2){
          [0] => string(3) "foo",
          [1] => string(3) "bar",
     },
}
==========================================================================================

Although you want to use

 EVO_Debug::export( $G );

It can also output private properties, and class constants. I only post the link because it's not trivial to deal with all the possible variable types, and it doesn't help here that PHP is Non-Typed language.

David
  • 3,285
  • 1
  • 37
  • 54
ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • good point Fred. Also I don't think this is the best way to save the data. – ArtisticPhoenix Aug 13 '16 at 01:37
  • I'd like to set something up myself, but TBH, I am bushed. At this time of night, my head is mush. – Funk Forty Niner Aug 13 '16 at 01:38
  • I have this ^ similar idea, but its setup for outputting a trimmed exception stack trace. Basically I have a few calls in my Framework that are always the same, so I want to remove them from the stacktrace, but the exception class `getTraceAsString` is final, so no overloading it. So I prune it down and then create my own string stack trace from the normal array version. Basically it's a way to get a stacktrace for debugging, that is similar to the exception classes output. – ArtisticPhoenix Aug 13 '16 at 01:46