将数据从数据库写入txt文件

时间:2013-10-09 15:41:53

标签: php html mysql

我无法将数据从数据库写入txt文件,只能从数据库写入最后一条记录。

示例工作代码:

include '01_config.php';
db_connect();
if(empty($_POST))
{
    define('DB_HOST','localhost');
    define('DB_USER','root');
    define('DB_PASS','password');
    define('DB_NAME','data_base');
    $select_db = mysql_select_db(DB_NAME);
    if($select_db)
    {
        mysql_query("SET NAMES utf8");
    }
    else
    {
        die('***');
    }

    $query = "SELECT user_id, user_email FROM users WHERE user_position = 'yes' ORDER BY user_id ASC";
    $result = mysql_query($query);
    if($result===false && trim(mysql_error))
    {
        echo("*** \n");
    }
        while($art = mysql_fetch_assoc($result))
    {
        $out[]=$art;
    }
    $i=0;
    echo "|form action=\"11.php\" method=\"post\"|\n";
    foreach($out as $art){
        $art['user_email'] = htmlspecialchars($art['user_email'],ENT_QUOTES);
        echo  <<<EOT
        <textarea name="text$i" style="width:450px; height:190px; border: 3px solid #cccccc; font-family: Tahoma, sans-serif; font-size: 12px;">
        BEGIN:VCARD
        EMAIL;TYPE=INTERNET:{$art['user_email']}
        END:VCARD
        |/textarea||br /|
        EOT;
        $i++;
    }
    echo '|input type="submit" value="Save to file" /||/form|';
}else if(isset($_POST['text0']) && isset($_POST['text1']) && isset($_POST['text2']) && isset($_POST['text3'])){
    $file = "13.txt";
    $fp = fopen($file, "w");
    flock($fp, 2);
    fwrite($fp, $_POST['text0']);
    fwrite($fp, $_POST['text1']);
    fwrite($fp, $_POST['text2']);
    fwrite($fp, $_POST['text3']);
    flock($fp, 3);
    fclose($fp);
    echo "successfully saved!<br />";
}else{
    die("Error!!!");
}
db_close();

如何更改代码以写入数据库中的所有记录? 非常感谢任何帮助。

(有些"<"">"已改为"|",抱歉。)

2 个答案:

答案 0 :(得分:0)

fopen()文件删除所有以前内容的方式。将模式从"w"(覆盖)更改为"a"(追加)。参考:http://php.net/manual/en/function.fopen.php

答案 1 :(得分:0)

这只是为了说明如何做到这一点。您需要开始使用MySQLiPDO 尝试沿着这些方向尝试,然后尝试将其合并到您的代码中:
(我测试过它对我有用)

$query = "
    SELECT user_id, user_email
    FROM users
    WHERE user_position = 'yes'
    ORDER BY user_id ASC";

//  $query = "SELECT user_email FROM users ORDER BY user_id ASC";

$result = mysql_query( $query );

$totalNumRows = mysql_num_rows( $result );
echo 'Total rows : ' ,$totalNumRows ,'<br>';

if( $totalNumRows > 0 )
{
    $file = "13.txt";
    $fp = fopen($file, "w");
    flock($fp, 2);
    while( $row = mysql_fetch_assoc( $result ) )
    {
        fwrite( $fp, $row['user_email'] );
    //  fwrite( $fp, "\r\n" );  // If you need line breaks
    }
    flock( $fp ,3 );
    fclose( $fp );
}