嗨,我需要我的项目一些帮助。

我的PHP代码---这些下面的代码从我的数据库中获取特定数据,由于规范化,我在join中使用了2个表。它显示我在浏览器中获取的数据以进行检查,而我想要的是将我选择的数据保存到具有特定格式的文本文件中。请在下面查看其他详细信息。


<?php

$conn = new mysqli( 'localhost', 'root', '', 'db2' );
if ( $conn->connect_errno ) {
  die( "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error );
}

$fp = fopen("result.txt", "w");

$query = "SELECT product_id FROM orders_lines"; //dont mind these
$result = $conn->query($query);	//dont mind these

$queryjoin = "SELECT orders_lines.product_id, orders.id FROM orders_lines INNER JOIN orders ON orders_lines.order_id=orders.id ORDER BY orders.id";
$resultjoin = $conn->query($queryjoin);

if ($resultjoin->num_rows > 0) {

	echo "order id | item ordered<br>";
    while($row = $resultjoin->fetch_assoc()) {

		$string = implode(",", $row);

        echo "data: " . $row["id"] . " | " . $row["product_id"] . "<br>";

		fwrite($fp, $string);
    }
} else {
    echo "0 results";
}

fclose($fp);

$conn->close();

?>





这是我的PHP代码输出的图像:Output of PHP Code

我的TextFile中的当前输出-4是order_id,2是订购的项目属于4,4,3是订购的项目也属于4 ....等等....



4,24,35,15,25,65,56,27,27,48,28,19,49,310,310,610,410,210,810,111,511,411,312,412,512,913,313,213,614,514,214,314,714,414,115,415,415,815,515,115,315,215,616,816,517,417,117,517,817,317,7





我在文本文件中的期望输出



2,3		//order id 4 -->comment
1,2,6,5		//order id 5
7		//order id 6
2,4		//order id 7
2,1		//order id 8
4,3		//order id 9
3,6,4,2,8,1	//order id 10
5,4,3		//order id 11
4,5,9		//order id 12
3,2,6		//order id 13
.....





任何帮助将不胜感激。谢谢。

最佳答案

谢谢,我明白了...这是我在寻找问题的正确答案..我的好朋友帮我..



if ($resultjoin->num_rows > 0) {
   $currentRowId = '';
   $output = '';
	while($row = $resultjoin->fetch_assoc()) {
		if($row["id"]==$currentRowId){
			echo ', '.$row["product_id"];
			$output = $output.', '.$row["product_id"];
		} else if($currentRowId=='') {
			$currentRowId = $row["id"];
			echo $row["product_id"];
			$output = $output . $row["product_id"];
		} else {
			$currentRowId = $row["id"];
			echo '<br>'.$row["product_id"];
			$output = $output . PHP_EOL . $row["product_id"];
		}
    }
	echo $output;
	fwrite($fp, $output);
} else {
    echo "0 results";
}

关于php - 将数据从MySQL导出到所需格式的文本文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40055819/

10-11 02:49
查看更多