Search code examples
phphtmlmysqlfwrite

PHP fwrite and sql query not working


Hello i am having a bit of trouble getting this code to work.

<?php
$filename = "test.php";
$filehandle = fopen($filename, 'a') or die("can't open file");
$test= 
    '
        $conn = mysql_connect("server", "username", "password" ) or die (mysql_error()) ;
        mysql_select_db("db", $conn);
        $query = "select * from test";
        $result =  mysql_query ($query);
        $row = mysql_fetch_array( $result );

        echo $row[\'test\'];

    ';
fwrite($filehandle, $test);
fclose($filehandle);
?>

instead of outputting the results of the query it is outputting the query instead, I imagine this is because I am storing the full query in a variable, does anyone know how i will be able to output the results of the query instead of the actual query? Thank you for all the help.


Solution

  • You should be using MySQLi or PDO

    However your code should look something like this :

    $filename = "test.php";
    $filehandle = fopen( $filename ,'a' ) or die( "can't open file" );
    $conn = mysql_connect( "server" ,"username" ,"password" ) or die ( mysql_error() ) ;
    mysql_select_db( "db" ,$conn );
    $query = "select * from test";
    $result =  mysql_query( $query );
    //  Iterate through results
    while( $row = mysql_fetch_array( $result ) )
    {
    //  var_dump[$row];
        //  Replace your-column-name below with the actual name :
        fwrite( $filehandle ,$row['your-column-name'] );
    }
    fclose( $filehandle );
    

    Find some examples from manual pages : mysql_fetch_array , mysql_fetch_assoc , mysql_fetch_array .