Opening Text File in PHP update Database - php

Okay this will be my last post here for today, have asked you guys enougth questions about why my terrible code dosnt work :)
I am trying to run a query to update all values of a column with a text documents contents. My database looks like follows:
Attribute_id | value
64 | Data.txt
109 | other data
64 | Data2.txt
109 | other data
If you look at my script you can see what I am trying to do, for now I am echoing the query the end result is here: http://dev.central-pet-supplies.co.uk/test.php
it is returning
UPDATE mage_catalog_product_entity_text SET value= 'Array' WHERE value = '13685.txt'
however array should be the text files contents
Here is the script:
<?php
mysql_connect ("localhost","cpsdev_mage1","********");
mysql_select_db ("cpsdev_mage1");
$sql = "select value from mage_catalog_product_entity_text WHERE Attribute_id = 64";
$result = mysql_query ($sql) or die($myQuery."<br/><br/>".mysql_error());
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$lines = file('http://dev.central-pet-supplies.co.uk/media/import/' . $row['value']);
$query3 = "UPDATE mage_catalog_product_entity_text " . " SET value= '" . $lines . "' WHERE value = '" . $row['value'] . "'";
echo $query3 ."<br>";
}
?>
Edit: changed file to file_get_contents and now working.

file() reads in the entire file with each line as a new entry in an array. Since you don't want that, you can either join the lines together using implode() by putting
$lines = implode( "\n", $lines);
After:
$lines = file('http://dev.central-pet-supplies.co.uk/media/import/' . $row['value']);
Or, by using file_get_contents() instead of file(), which will return the entire file's contents as a string, instead of an array:
$lines = file_get_contents( 'http://dev.central-pet-supplies.co.uk/media/import/' . $row['value']);

You dont show where $lines comes from but its an array i assume of lines in the text file. Use something like file_get_contents to get the contents of the text file as a single string instead.

Related

PHP read from file line by line, declare as variable, then use in MySQL query as WHERE column_name equals variable

Good day,
My aim with the script (overview) is to let PHP read from text file line by line then declare the line as variable that will be used in a MySQL statement as a where clause into an array, then ultimately writing to another text file.
CODE:
$lines = file('/root/prcode');
foreach($lines as $line) {
$query = "select * from $db_table where code=$line";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$out = "$row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],
$row[8],$row[9],$row[10],$row[11],$row[12],\n";
//file_put_contents($outfile, $out);
//$fp = fopen($outfile, 'w');
//fwrite($fp, $out);
//fclose($fp);
echo $out;
//echo $line;
//echo $query;
//echo $result;
//echo $row;
};
}
File prcode's first 10 lines:
60025909170
*
.05005140160
0000000000000000
0000000000000001
0000000000000004
0000000000000005
0000000000000007
0000000000000010
0000000000000011
OUTPUT when script is run from Linux shell:
0010,0000,60025909170,01,,,,,,,,,,
0010,0000,60025909170,02,,,,,,,,,,
0010,0000,60025909170,03,,,,,,,,,,
0010,0000,60025909170,04,,,,,,,,,,
0010,0000,60025909170,05,,,,,,,,,,
0010,0000,60025909170,06,,,,,,,,,,
0010,0000,60025909170,07,4.000,36.960,-4.000,-36.960,,,,,,
0010,0000,60025909170,08,4.000,36.960,,,,,,,,
0010,0000,60025909170,09,4.000,36.960,,,,,,,,
0010,0000,60025909170,10,4.000,36.960,,,,,,,,
0010,0000,60025909170,11,4.000,36.960,,,,,,,,
0010,0000,0000060025909170,01,,,,,,,,,,
0010,0000,0000060025909170,02,,,,,,,,,,
0010,0000,0000060025909170,03,,,,,,,,,,
0010,0000,0000060025909170,04,,,,,,,,,,
0010,0000,0000060025909170,05,,,,,,,,,,
0010,0000,0000060025909170,06,,,,,,,,,,
0010,0000,0000060025909170,07,,,,,,,,,,
0010,0000,0000060025909170,08,,,,,,,,,,
0010,0000,0000060025909170,09,,,,,,,,,,
0010,0000,0000060025909170,10,-4.000,-.040,4.000,.040,,,,,,
0010,0000,0000060025909170,11,-4.000,-.040,,,,,,,,
0010,0000,60025909170,12,4.000,36.960,,,,,,,,
0010,0000,0000060025909170,12,-4.000,-.040,,,,,,,,
From the output, it can be established that the order of the text file is not being followed as 60025909170 and 0000060025909170 are 2 different products and 0000060025909170 is at about line 32000 <- my first problem. To try to rectify this and cater for following the order, the special characters and spaces I tried:
$query = "select * from $db_table where code='$line'"; \\causes empty output
$query = "select * from $db_table where code=\"$line\""; \\causes empty output
$query = "select * from $db_table where code=\'$line\'"; \\empty output
The echos below were just to test to see which variables are set or not to try to further troubleshoot:
echo $out;
//echo $line;
//echo $query;
//echo $result;
//echo $row;
The second problem is, none of the attempts to write to file worked, it would either write just a single line and nothing more or would not write at all.
Any advise or guidance on how to possibly fix my 2 issues?
1st issue: Likely, your file is being read in order, but your query is finding all of those rows. You can see if this is happening by adding the line number to your output. Try changing your foreach to foreach($lines as $lineNum => $line) { and your output to $out = $lineNum.implode(',', $row)."\n"; If you have the same lineNum for 60025909170 and 0000060025909170, then you know that the query is matching both.
2nd issue: You just need to add a flag of FILE_APPEND to the file_put_contents. Like this: file_put_contents($outfile, $out, FILE_APPEND);

How to export data from MySQL to CSV?

I am trying to export data from MySQL to CSV using PHP from a website. When a user clicks generate the report it will automatically create and this will be downloaded as a file on their computer. The code below I have been following an online tutorial but I have run into some issues. Currently, it will download but will only show one row with one date value from the MySQL data.
I was wondering what I need to do to show all the data in the csv file and how do I ensure that the names of the Rows are printed as well.
#header("Content-Disposition: attachment; filename=record.csv");
$select = "SELECT * FROM DBtable WHERE user_id=$id";
$result2 = $conn->query($select);
while ($row = $result2->fetch_assoc()) {
$data = $row['pain']."\n";
$data = $row['sleep']."\n";
$data = $row['mood']."\n";
$data = $row['heartrate']."\n";
$data = $row['time_of_entry']."\n";
}
echo $data;
exit();
Instead of setting the $row values to $data, you should echo instead
#header("Content-Disposition: attachment; filename=record.csv");
$select = "SELECT * FROM DBtable WHERE user_id=$id";
$result2=$conn->query($select);
while($row=$result2->fetch_assoc()){
echo $row['pain']."\n";
echo $row['sleep']."\n";
echo $row['mood']."\n";
echo $row['heartrate']."\n";
echo $row['time_of_entry']."\n";
}
exit();
Your code just keeps setting $data to a rows value, without actually doing anything with it. Each line overwrites the previous, so when you do echo $data, you are echoing the last value it was set to which in your case was the last loops "time of entry" value.
As for adding "names of the Rows", currently the code puts in a value then a new line. You probably want to replace "\n" with ",", so one loops data is one one line, then before the closing while loop, echo a "\n" to insert a new line character. You can then put the titles in the same way, using an echo, and comma seperated titles, followed by a new line character.
For example
echo $row['pain'].",";
echo $row['sleep'].",";
echo $row['mood'].",";
echo $row['heartrate'].",";
echo $row['time_of_entry'].",";
echo "\n";

Formatting output from mysql (array of values)

I am running a sql query to output value of field, which has array of values. How can I format those value using php/css/html.
This is the output I get from following code:
$rb = $wpdb->get_results("select value
from wp_rg_lead_detail
where field_number = 33
and lead_id =
(select distinct lead_id
from wp_rg_lead_detail
where value = '".$uname."')
");
foreach( $rb as $r){
echo $r->value . "<br/> ";
}
MySQL Output Value:
a:2:{
i:0;a:2:{s:10:"First Name";s:6:"testb1";s:9:"Last Name";s:5:"test1";}
i:1;a:2:{s:10:"First Name";s:6:"testb2";s:9:"Last Name";s:5:"test2";}
}
Desired Output:
FirstName LastName
testb1 test1
testb2 test2
Can someone help me with this?
To start, you'll need to remove the new lines and tabs from your serialized data before it will unserialize() correctly:
$data = unserialize('a:2:{i:0;a:2:{s:10:"First Name";s:6:"testb1";s:9:"Last Name";s:5:"test1";}i:1;a:2:{s:10:"First Name";s:6:"testb2";s:9:"Last Name";s:5:"test2";}}');
You can output the results you want with a simple loop like this:
// Keep track of whether the headers have been output yet
$headersOutput = false;
foreach ($data as $row) {
// If the headers haven't been output yet
if (!$headersOutput) {
// Output the headers only
echo implode("\t", array_keys($row)), PHP_EOL;
// Update variable so it won't happen again
$headersOutput = true;
}
// Output the values
echo implode("\t", array_values($row)), PHP_EOL;
}
Example:
First Name Last Name
testb1 test1
testb2 test2
You can swap the "\t" tab characters for whatever you want to delimit columns with, and swap PHP_EOL for what should delimit new lines.
If you want to add this data to an array (e.g. to write to a CSV instead) then just use $output[] = implode... instead of echo and use $output at the end.

PHP ODBC return all records

I started using PHP with Oracle using ODBC commands. I used odbc_exec to get to query the database, which seems to work.
I am trying to print the dataset to a text file. I am able to write to the text file, but for some reason, I am only able to get back 1 record/row from the table.
One query in particular returns over 100 records. I would like to be able to print all 100 records in the text file.
I have researched all over the web, and I have come close to getting this work. In fact, I can print all the records to the web page. I just can't get all of the records into the text file.
Please see my code below and advise what I am missing.
<?php
$voyage = $_POST['voyage'];
$query = "SELECT * FROM voyageTable WHERE voyage = '".$voyage."'";
$result = odbc_exec($connect, $query);
while($row = odbc_fetch_array($result)) // have tried odbc_fetch_row already
{
$fullName = odbc_result($result, 1);
}
$dateFile = "CMDU-".$voyage."-".date('dmY').".txt";
$dataString = $fullName . "\n";
$fWrite = fopen($dateFile, "a");
$wrote = fwrite($fWrite, $dataString);
fclose($fWrite);
?>
I know I am close to getting this.
I have altered the while loop numerous times. I tried to do this as well:
<?php
while(odbc_fetch_array($result))
// ...
?>
Please help.
That was unsuccessful as well.
Instead of
$fullName = odbc_result($result, 1);
You need to either echo out like this:
echo odbc_result($result, 1);
Or store the result in an array like this:
$fullName[] = odbc_result($result, 1);
Just storing the value of each row in $fullname as a variable will overwrite the value and give you the last value from the last row in the result set.
Expanding on ಠ_ಠ's comment.

Modifying many rows of mySQL data from PHP

I have some php script that I would like to run on EVERY row within a mySQL table. The php script:
function replacespaces($text) {
return preg_replace_callback('/[\<]pre(.*)[\>](.*)[\<]\/pre[\>]/i',
create_function(
'$matches',
'return "<pre".$matches[1].">".str_replace(" ", " ", $matches[2])."</pre>\n";'
), $text);
}
I need to cycle through the mySQL database in the table "jos_picmicro_content" passing the content of the field "fulltext" to the above function, and inserting the result back into the field "fulltext". Sounds easy enough to do, although I am not experienced in the area! The table is about 500 rows long.
$result = mysql_query("SELECT * FROM jos_posmicro_content");
while ($row = mysql_fetch_array($result)) {
$text = replacespaces($row['fulltext']);
$sql = "UPDATE jos_posmicro_content SET fulltext = '" . mysql_real_escape_string($text) . "' WHERE ????";
mysql_query($sql);
}
You just ned to change the ???? part to identify which row to update (eg, where id = $row['id'] or whatever your primary key is).

Categories