PHP to CSV not outputting fields correctly - php

I am trying to output my PHP code to a downloadable CSV file and so far i am able to do this however at the moment, the output does not place the field data into separate columns. Instead it puts everything into one column and in addition to that, it displays the postcodes in its neighbouring columns. Does anyone know why this is?
<?php
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="filename.csv"');
$outstream = fopen("php://output",'w');
if ($db_found) {
// Select all fields from bodyshops_master_network table
$SQL = "SELECT * FROM bodyshops_master_network";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
// Splits the arrays
$row = explode(",", $db_field['postcodes_covered']);
$dealer_code = $db_field['dealer_code'];
$dealer_name = $db_field['dealer_name'];
$bodyshop_id = $db_field['bodyshop_id'];
$bodyshop_name = $db_field['bodyshop_name'];
$address1 = $db_field['address1'];
$address2 = $db_field['address2'];
$address3 = $db_field['address3'];
$address4= $db_field['address4'];
$address5 = $db_field['address5'];
$postcode = $db_field['postcode'];
$bo_tel = $db_field['BO_tel'];
$bo_email = $db_field['BO_email'];
$bc_name = $db_field['BC_name'];
$equity_contract = $db_field['equity_contract'];
echo "<pre>";
foreach ($row as $value) {
echo $dealer_code . " ";
echo $dealer_name . " ";
echo $bodyshop_id . " ";
echo $bodyshop_name . " ";
echo $address1 . " ";
echo $address2 . " ";
echo $address3 . " ";
echo $address4 . " ";
echo $address5 . " ";
echo $postcode . " ";
echo $bo_tel . " ";
echo $bo_email . " ";
echo $bc_name . " ";
echo $equity_contract . " ";
echo $value. "<BR>";
fputcsv($outstream, $row, ',', '"');
}
echo "</pre>";
}
mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
fclose($outstream);
}
?>

OK, you're doing something really weird here. You're outputting content in two ways.
First, you output content in the normal way using echo. Fair enough!
Second, you output content using fputcsv where the file handler leads to php://output. Also fair enough!
But you shouldn't do both and expect it to work seamlessly. You want a CSV file, so the best way is to output all your data using fputcsv. At the moment, some of your data is encapsulated as a CSV file, and some of it isn't. This leads to output that you don't really want.
I think you want something like this:
foreach ($row as $value) {
$output = array(
$dealer_code,
$dealer_name,
$bodyshop_id,
$bodyshop_name,
$address1,
$address2,
$address3,
$address4,
$address5,
$postcode,
$bo_tel,
$bo_email,
$bc_name.
$equity_contract,
$value
);
fputcsv($outstream, $output, ',', '"');
}
fputcsv expects the data to be an array, so that's what we give it. The separate array fields will be separate columns in the CSV output. We don't echo any data: we store it in an array and then supply it to fputcsv.
The second mistake you made was to send $row rather than $value to fputcsv. This meant that you were sending all the postcodes as received from the database row.
Finally, you don't need <pre>.
On a separate note, you really should have a better database structure. If you had a table of postcodes and a separate table of bodyshops and a foreign key linking them, the code to retrieve data would be a lot simpler, as would searching and updating it in future.

Related

no data gets print where the query returns too many results

I have a query which is supposed to retrieve data from mysql and print it on the browser. It is working with a few rows of data but when the data gets bigger it just stops working and doesn't give any errors.
$result = mysql_query($query);
$json_array = array();
while($row = mysql_fetch_assoc($result)){
$json_array[] = $row;
}
print mysql_error();
print json_encode($json_array);
I have tried everything but nothing seems to work.
I'm very surprised it works at all.
This would work if $row was formatted.
Use foreach()
I doubt this would work either:
foreach($json_array as $row){
echo "$row<br>\n"
}
This should work (replace colx with the name of the table columns):
foreach($json_array as $row){
echo $row['col1'] . ', ' . $row['col2'] . ', ' . $row['col2'] . "<br>\n"
}
foreach($json_array as $row){
echo $row['name'] . ', ' . $row['address'] . ', ' . $row['phone'] . "<br>\n"
}
#Lessmore has right, maybe the PHP process has reached the memory limits in the server, try with less columns or registers, but I understand your need, then you need to write your self json_encode code to write row by row. Some like this:
$first = null;
header('Content-Type: application/json');
echo '[';
while ($row = mysql_fetch_assoc($result)) {
if ($first) {
echo ',';
}
echo json_encode($row);
!$first && $first = true;
}
echo ']';
exit;

save mysql table as csv modifying file some of the cell data in php

I need to download a mysql table as a csv file. Okay, Now thats no big thing.
But I need to modify the cell contents when I download it. For eg. In the table male, female and others are denoted as 1 2 and 3 respectively. But the downloaded excel csv file should contain "Male" "female" and "others" in the gender field.
I tried calling some php functions within the code. But it didnt work.
Is it possible?
Can you help guys?
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("bus",$conn);
$query = "SELECT * FROM booking";
$result = mysql_query($query);
$num_column = mysql_num_fields($result);
$csv_header = '';
for($i=0;$i<$num_column;$i++) {
$csv_header .= '"' . mysql_field_name($result,$i) . '",';
}
$csv_header .= "\n";
$csv_row ='';
while($row = mysql_fetch_row($result)) {
for($i=0;$i<$num_column;$i++) {
//echo $i; this and the next line doesnt execute
//echo '<script>myFunction()</script>';
$csv_row .= '"' . $row[$i] . '",';
}
$csv_row .= "\n";
}
/* Download as CSV File */
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=toy_csv.csv');
echo $csv_header . $csv_row;
exit;
?>
Add the other fields that you expect for,
but this is how you will get the gender.
SELECT
IF (
`booking`.gender = 1,
"Male",
IF (
`booking`.gender = 2,
"Female",
"Other"
)
) as gender
FROM
`booking`;

How Can I Retrieve A MySQL Table Into An Array Then Use The Array Contents In A Function

I'm trying to work something out but I just can't get it to work. I need to do the following:
Pull data from a MySQL Table
Store that data in an array
Use that data from the array in a Function.
Current code looks like this (currently pulls data from MySQL Table and iterates over it, putting it in a table (purely to check it worked).
mysql_connect("localhost", "*****", "*****") or die(mysql_error());
mysql_select_db("*****") or die(mysql_error());
$data = mysql_query("SELECT batch FROM widgetBatches") or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data )) { Print "<tr>";
Print "<th>Batch:</th> <td>".$info['batch'] . "</td> ";
Print "" . " </td></tr>";
} Print "</table>";
Here's the function, $widgetBatches needs to take the array from the previous code however nothing i've tried works. (there is more to the Widget() however it's not relevant to this issue. Thanks in advance!
$uI = 550;
Widget($uI);
function Widget($input) {
$currentValue = $input;
$i = 0;
$widgetBatches = [250, 500, 1000, 2000];
while ($currentValue > 0) {
$i++;
echo "Batch Number " . $i . "<br/>";
echo "Widgets Left To Fulfill Order: " . $currentValue . "<br/>";
$closest = ClosestBatch($widgetBatches, $currentValue);
echo "Closest Batch Available: " . $closest . "<br/>";
$currentValue = $currentValue - $closest;
echo "Remaining Widgets: " . abs($currentValue) . "<hr/>";
}
echo "<br />";
}

Query does not insert into database

I've made this code but for some reason when i submit the form the data is not inserted to the table name posts. here's my code, i might have a typo or something, it'd be great if someone could have a look.
$fnames = Array("","","","","");
$fcnt = 0;
if (isset($_POST['submit']))
{
$allowedExts = array("gif", "jpeg", "jpg", "pjpeg", "x=png","png",);
// do all 5 files!
for ( $fnum = 1; $fnum <= 5; ++$fnum )
{
$curfile = $_FILES["uploaded_file" . $fnum];
if ($curfile["error"] > 0) {
echo "Return Code: " . $curfile["error"] . "<br>\n";
} else {
$ftype = explode( "/", $curfile["type"])[1]; // get the part after the /
$fsize = $curfile["size"];
if ( in_array($ftype, $allowedExts) && $fsize < 20000000 )
{
echo "Upload: " . $curfile["name"] . "<br>\n";
echo "Type: " . $ftype . "<br>\n";
echo "Size: " . ($fsize/1024) . " KB<br>\n";
echo "Temp file: " . $curfile["tmp_name"] . "<br>\n";
$fname = $_SESSION["userid"] . "_" . $curfile["name"];
if (file_exists("uploads/$fname"))
{
echo "$fname already exists.<br>\n";
} else {
move_uploaded_file($curfile["tmp_name"], "uploads/$fname");
$fnames[$fnum-1] = $fname;
++$fcnt;
}
}
else
{
echo "No valid file in slot $fnum<br>\n";
}
}
}
if ( $fcnt > 1 )
{
$sql = "INSERT INTO posts (picture1, picture2, picture3, picture4, picture5) VALUES( ". "'" . implode("','", $fnames) . "')";
echo "DEBUG SQL: $sql <hr>\n";
mysqli_query($sql);
}
}
With a quick glance:
A) error in your mysqli_query($sql);.
The mysqli_ extensin needs the connection pointer, something like: mysqli_query($dbConn, $sql);
B) Also, modify your query to look like mysqli_query($dbConn, $sql) or die(mysqli_error($dbConn));. It will show you the sql errors, if any.
EDIT 1
If no errors appear after you put the mysqli_error(), then i think your script never gets to the sql part. Something stops it before that if.
Put on top of your script:
error_reporting(E_ALL);
ini_set('display_errors', '1');
and check if any php errors appear on the page.
Most of the time is a string/integer mismatch. Double check all your string escape characters. Copy your final query string and use some external tool to submit the query. You could start hardcoding all your data in the query and then proceed by adding one parameter at a time. Eventually you'll find the field (or fields) that causes the problem.
However, read carefully the error message first instead of guessing blindly what's causing the problem :-)
Make sure your fields count and values count are the same. Also correct this as well:
"'".implode("','", $fnames)."'"
in values passed.

php mysqli select resultset is not showing anything

Ive been trying to crack this for 2 hours, but something is wrong. I am very much used to doing things without mysqli but read that there is a recommended shift towards it from regular mysql commands. Hence am stuck with following:
<?php
$mysqli = new mysqli('localhost', 'admin', 'test123', 'kadmindb');
if ($result = $mysqli->query("SELECT * FROM records WHERE '$queryType' = '$keyword'")) {
while ($row = $result->fetch_object()) {
echo "<h2>Result:</h2><br>";
echo "ID: " . $row->id . "<br>";
echo "Name: " . $row->cust_name . "<br>";
echo "Invoice No: " . $row->invoice_num . "<br>";
echo "Date: " . $row->date_recorded . "<br>";
}
}
?>
This code is shown in the page where the result of the query should be displayed but nothing is displayed. I checked that both keyword and queryType variables are set and they contain the correct values. Any help would be greatly appreciated. All am trying to do is: select statement to retrieve all the details based on invoice_num submitted.
EDIT: from help I received, I was able to get this working:
$query = "SELECT * FROM records WHERE ".$queryType. " LIKE '%$keyword%' ";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_object()) {
echo "<h2>Result:</h2><br><hr/> ";
echo "ID: " . $row->id . "<br>";
echo "Name: " . $row->cust_name . "<br>";
echo "Invoice No: " . $row->invoice_num . "<br>";
echo "Date: " . $row->date_recorded . "<br>";
echo "<hr/>";
}
}
Are you sure there's data to select? This code will only output data if there actually is.
Make sure that $queryType and $keyword are set and have sane values that will yield a result.
Use var_dump($queryType) and var_dump($keyword) immediately before the query. Now check your output. Are they both strings? Run this query directly in PHPMyAdmin and check how many rows you get.
If you can't do that try echo'ing the number of rows returned along with the query values:
if ($result = $mysqli->query("SELECT * FROM records WHERE $queryType = '$keyword'"))
{
while ($row = $result->fetch_object())
{
echo "<h1>Query WHERE '$queryType' = '$keyword' yielded {$result->num_rows} rows!</h1>";
echo "<h2>Result:</h2><br>";
...
Note, you should not have single quotes around the column ($queryType), if you insist you should use backtick quotes (`) but it's unnecessary really - if you're that pedantic you should be using prepared statements.
Also be sure to filter them for any potentially dangerous values that could allow for sql injections. See: mysqli::real_escape_string
Assuming that $queryType is the name of a column in your records table, then I believe the problem is your WHERE clause.
Rather than:
$mysqli->query("SELECT * FROM records WHERE '$queryType' = '$keyword'")
You should have:
$mysqli->query("SELECT * FROM records WHERE {$queryType} = '{$keyword}'")
Note that I've removed the single quotes around $queryType and have used complex (curly) syntax
Also, in the future you might want to try using an else block to trap errors:
$mysqli = new mysqli('localhost', 'admin', 'test123', 'kadmindb');
if ($result = $mysqli->query("SELECT * FROM records WHERE {$queryType} = '{$keyword}'")) {
while ($row = $result->fetch_object()) {
echo "<h2>Result:</h2><br>";
echo "ID: " . $row->id . "<br>";
echo "Name: " . $row->cust_name . "<br>";
echo "Invoice No: " . $row->invoice_num . "<br>";
echo "Date: " . $row->date_recorded . "<br>";
}
}
else
{
echo "Error: " . $mysqli->error;
}

Categories