gpt4 book ai didi

php - 将 MYSQLI 查询结果写入 php 中的文本文件

转载 作者:行者123 更新时间:2023-11-28 03:00:23 25 4
gpt4 key购买 nike

<body>

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "random";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT Channel_Location, Product, Active FROM channels
ORDER BY RAND()
Limit 5";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
echo "<tr><br><td>".$Channel_Location."</td></tr>";

}

} else {
echo "0 results";
}

$myfile = fopen("Log.txt", "w") or die("Unable to open file!");
$txt = "$result";
fwrite($myfile, $txt);
fclose($myfile);

mysqli_close($conn);

?>

</body>

基本上我的问题是我正在尝试将 $result 的输出写入文本文件,但出现以下错误

enter image description here

文本文件应该有 5 行文本,如果我更改 $txt = "$Channel_Location" 我将得到一个结果,但不是所有 5 行

最佳答案

  $output = '';
$outputArray=[];
while($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
echo "<tr><br><td>".$Channel_Location."</td></tr>";
$output .= $row['Channel_Location']."\n";
$outputArray[] = $row;
}

file_put_contents('Log.txt',$output);

// or you can use json_encode to save whole query result!!
file_put_contents('log.txt',json_encode($outputArray));

关于php - 将 MYSQLI 查询结果写入 php 中的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34922493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com