Writing MYSQLI query results to a text file in php - php

<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>
So basically my issue is i'm trying to write the output of $result to a text file but i get the following error
the text file should have 5 lines of text, if i change the $txt = "$Channel_Location" i will have one result but not all 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));

You must concatenate your data before writing the string to the file.
$text = '';
while ($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
$text = $text . $Channel_Location . "\n";
}
You can then do something like:
fwrite($myfile, $text);

fwrite writes a string to a document.
$result is an object and as such cannot be written as a string.
Your best option is when you run through the loop to print out the values, also add them to a string.
I would also recommend doing the fwrite function within the if statement as you will need values to write to it otherwise it will just open the file, write an empty variable and then close.
<?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 = '';
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
echo "<tr><br><td>".$Channel_Location."</td></tr>";
$output .= $Channel_Location . '/n';
}
$myfile = fopen("Log.txt", "w") or die("Unable to open file!");
$txt = "$output";
fwrite($myfile, $txt);
fclose($myfile);
} else {
echo "0 results";
}
mysqli_close($conn);
?>

Suppose you want to user record
$output ='';
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
$output .="<tr><br><td>".$Channel_Location."</td></tr>";
}
} else {
$output .= "0 results";
}
$myfile = fopen("Log.txt", "w") or die("Unable to open file!");
fwrite($myfile,$output);
fclose($myfile);
mysqli_close($conn);

Related

Pulling data from mySQL to a text document php

I'm trying to take the data I have from mySQL database and have it replace a certain string in a .txt file. I feel like I'm close but the string I want to replace is only getting replaced with a blank space.
<?php
$servername = "localhost";
$username = "rob1289";
$password = "databasetest";
$dbname = "RobertCornell2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM name ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
//"" . $row["first"]. "<br>";
$fname_from_db = $row["first"];
$mname_from_db = $row["middle"];
//echo $row["id"];
}
} else {
echo "0 results";
echo "<br/>Error: " . mysqli_error($conn);
}
$myFile = "freewill.doc";
$fh = fopen($myFile, 'a') or die("can't open file");
$fname_from_db = $row["first"];
$mname_from_db = $row["middle"];
$placeholders = array('fin', 'min');
$namevals = array($fname_from_db);
$path_to_file = 'freewill.doc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);
file_put_contents($path_to_file,$file_contents);
fclose($fh);
mysqli_close($conn);
?>
Could it be because $namevals (replace) has one element and $placeholders (search) has two?
From the PHP doc:
If replace has fewer values than search, then an empty string is used for the rest of replacement values.

read a list of urls and read divs

Im trying to read the data of some divs in a list of urls, but i dont find the correct way, actually i only get a white page, but if do a print_r on the commented code (the $aElements) i can see the url loaded correctly, so i think the error is on the foreach, but i can't fix it, i need the link inside the div with the id=city
require_once('simple_html_dom.php');
set_time_limit (2000);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "buss";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT url FROM business";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$html = file_get_html($row["url"]);
$aElements = $html->find('div[id=city]', 0)->find('a');
$localList = array();
// here if i do a print_r i get the html of each url listed and is fine (of $aElements)
foreach($aElements as $element) {
if(substr($element->href, 0, 1) == '/') {
$ownerName = trim(str_replace('Punto de', '', $element->plaintext));
$localList[$artistName] = $element->href;
$file = fopen("newfile.txt", "a");
fwrite($file, $localList[$ownerName] = $element->href . PHP_EOL);
fclose($file);
}
}
}
} else {
echo "0 results";
}
$conn->close();

Formatting fwrite output to a external file - Implode Error

The code I am working on queries a database through php and then placed the results into an array called CS. This array is then encoded so it can work with javascript. It is then supposed to edit the output so there is a newline after every row. The latter is where I have the problem. I get implode: invalid arguments passed every time regardless of how I edit the implode function.
Here is the code:
<?php
$servername = "*****";
$username = "****"; --> edited for privacy.
$password = "*******";
$database = "********";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// sql statement for tables and naming array to hold it in
$sql = "SELECT COURSE_ID FROM cs";
$result = $conn->query($sql);
$CS = array();
if ($result->num_rows > 0) {
// fill array with results
while($row = $result->fetch_assoc()) {
array_push($CS, $row);
}
} else {
echo "0 Results";
}
// encodes php array so it can be used in javascript
$json_array = json_encode($CS);
$conn->close();
// fills Computer_Science.js with the contents of the json_array and adds new lines in between
$json_array_lines = implode($json_array, "/n"); --> this line
$fp = fopen('..\js\DegreePlans\Computer_Science.js', 'w');
fwrite($fp, print_r($json_array_lines, TRUE));
fclose($fp);
?>
I'm at a loss on how to fix the error. Any help given will be appreciated.
I fixed it!
<?php
$servername = "*****";
$username = "****"; --> edited for privacy.
$password = "*******";
$database = "********";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// sql statement for tables and naming array to hold it in
$sql = "SELECT COURSE_ID FROM cs";
$result = $conn->query($sql);
$CS = array();
if ($result->num_rows > 0) {
// fill array with results
while($row = $result->fetch_assoc()) {
array_push($CS, $row);
}
} else {
echo "0 Results";
}
$conn->close();
//encode the array so it can be used in javascript and use regular expressions to format it.
$json_string = json_encode($CS);
$re = "/.,/";
$subst = "},\r\n"; --> right here!
$json_string = preg_replace($re, $subst, $json_string);
$fp = fopen('..\js\DegreePlans\Computer_Science.js', 'w');
fwrite($fp, print_r($json_string, TRUE));
fclose($fp);
?>

JSON_Encoded Value to be used in snother file

<?php
echo $xml = file_get_contents("C:\wamp\www\Sample API\index.php");
$result = json_decode($xml);
var_dump ($result);
?>
Index.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$db=mysqli_select_db($conn,"login");
$sql ="SELECT * FROM loginuser WHERE ID=11" or die('MySQL Error.');
$result=$conn->query($sql);
$data = array();
while($data1 = $result->fetch_assoc())
{
$data[] = array('post'=>$data1);
}
$output = (array('posts' => $data));
$out =json_encode($output);
echo $out;
?>
i am trying to get output value of index.php in this file and i'm trying this given code but $result returns the null value.Where as the included file returns the desire value but in this case json_decode returns null value.
You can just change this:
echo $out;
to:
return $out;
And then you just can require the file into the other one like this:
$xml = require_once("C:\wamp\www\Sample API\index.php");
$result = json_decode($xml);
var_dump($result);

php mysql insert into table from text file with fixed width

I'm trying to write a cron job that would run a php script which would insert data from flat (text) file with fixed columns.
My file 'data.txt' looks something like that:
first_column second_column third_column
Eg. first column has width of 30 characters + 1 space for separation from next column, second 20 characters + 1 space for separation, third 15 (including whitespaces). My table 'TEST' has 3 columns: first, second and third.
Question is, how to first trim column data and then insert each row into the table?
<?php
// initial database stuff
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database';
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$file = file('/home/user/files/data.txt'); # read file into array
$count = count($file);
if($count > 0) # file is not empty
{
$query = "INSERT into TEST(first,second,third) values";
$i = 1;
foreach($file as $row)
{
$query .= "('TRIM(SUBSTR($row,1,30))','TRIM(SUBSTR($row,32,20))','TRIM(SUBSTR($row,34,49))')";
$query .= $i < $count ? ',':'';
$i++;
}
mysql_query($query) or die(mysql_error());
}
echo "File data successfully imported to database!!";
?>
And here is how it might look like:
<?php
// initial database stuff
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database';
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$file = file('/home/user/files/data.txt'); # read file into array
$count = count($file);
// Edited to add loop back in... Silly me.
if($count > 0) # file is not empty
{
foreach ($file as $row){
$first=trim(substr($row,0,30));
$second=trim(substr($row,31,20));
$third=trim(substr($row,33,49));
$query = "INSERT into TEST(first,second,third) values".
"($first,$second,$third)";
mysql_query($query) or die(mysql_error());
}
}
echo "File data successfully imported to database!!";
?>
Consider using PDO and prepared statement, to make it even cleaner ( and safer ).
Try this
<?php
// initial database stuff
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database';
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$file = file('/home/user/files/data.txt'); # read file into array
$count = count($file);
if($count > 0) # file is not empty
{
foreach($file as $key => $row)
{
if( $key == 0 ){
$col_1 = str_replace( " ", "" , trim(substr($row,1,30));
$col_2 = str_replace( " ", "" , trim(substr($row,32,20));
$col_3 = str_replace( " ", "" , trim(substr($row,34,49));
$query = "INSERT into TEST(col_1,col_2,col_3) values";
}
else {
$query .= "'TRIM(SUBSTR($row,1,30))','TRIM(SUBSTR($row,32,20))','TRIM(SUBSTR($row,34,49))')";
$query .= $key < $count ? ',':'';
}
}
mysql_query($query) or die(mysql_error());
}
echo "File data successfully imported to database!!";
?>
At the end I ended up using PDO as suggested.
It works fine with strings with commas in the middle, and it skips empty rows.
<?php
// configuration
$dbtype = 'sqlite';
$dbhost = 'localhost';
$dbuser = 'user_for_db';
$dbpass = 'pass_for_db';
$dbname = 'name_of_db';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8",$dbuser,$dbpass); //charset optional
// open data file
$handle = fopen('/home/user/data/file.txt', 'r');
if ($handle)
{
while (($buffer = fgets($handle, 4096)) !== false)
{
// new data
$first =trim(substr($buffer,0,8));
$second =trim(substr($buffer,9,10));
$third =trim(substr($buffer,20,6));
$fourth =trim(substr($buffer,27,100));
$fifth =str_replace(" , ", ", ", trim(substr($buffer,128,113)));
$sixth =trim(substr($buffer,240,30));
// query
$sql = "INSERT INTO table(column_1,column_2,column_3,column_4,column_5,column_6) VALUES (:first,:second,:third,:fourth,:fifth,:sixth)";
$q = $conn->prepare($sql);
$q->execute(array( ':first' =>$first,
':second' =>$second,
':third' =>$third,
':fourth' =>$fourth,
':fifth' =>$fifth,
':sixth' =>$sixth ));
}
if (!feof($handle))
{
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
echo "File data successfully imported to database!";
}
?>

Categories