Here's my code:
$values = mysql_query("SELECT cult_desc FROM culture");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("d-m-Y_H-i",time());
#echo $filename;
echo $csv_output;
As far as I can tell, it should go through each piece of data, echo it with a ";" and then a newline. Instead, it gives me no output.
From the variable name ($csv_output) it seems you need CSV formatted output.
If you have FILE privilege why not invoke,
$values = mysql_query("SELECT cult_desc INTO OUTFILE '/tmp/result.txt'
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\n'
FROM culture");
readfile("/tmp/result.txt");
Otherwise following code will do it.
$values = mysql_query("SELECT cult_desc FROM culture");
$csv_output = "";
while ($rowr = mysql_fetch_row($values)) {
$csv_output .= implode(";", $rowr). "\n";
}
$filename = $file."_".date("d-m-Y_H-i",time());
#echo $filename;
echo $csv_output;
Try initializing $csv_output with an empty string so it has something to concatenate onto. Otherwise you may get a notice, and your code won't work. Additionally, check to make sure there are actually values in your results.
$csv_output = '' ought to do the trick, call that before your loop unless you initialize it elsewhere.
You also need to replace $i with $j unless you have $i declared elsewhere?
First of all mysql_fetch_row has in your case just one key its 0 (there the cult_desc field is stored).
You can use your code like this:
$csv_output = "";
$values = mysql_query("SELECT cult_desc FROM culture");
while ($rowr = mysql_fetch_assoc($values)) {
$csv_output .= $rowr['cult_desc']."; \n";
}
$filename = $file."_".date("d-m-Y_H-i",time());
#echo $filename;
echo $csv_output;
i replaced mysql_fetch_row with mysql_fetch_assoc so you get the field name as the key not a number. With that you can direct access with cult_desc
Related
I was recently tasked to update some older sites from MySQL to MySQLi.
Though slow and steady, the update has been ok until I ran into an issue when exporting some data to an excel document.
This code was written by a previous developer. There's a lot going on in the file, and I hope I'm grabbing the part that is supposed to be creating the excel document:
<?php
$export = mysqli_query ( $session->connDB(),$sql ) or die ( "Sql error : " . mysqli_error( ) );
$fields = mysqli_num_fields ( $export );
$num_rows = mysqli_num_rows( $export );
$pattern = '/[A-Z0-9][A-Z0-9._-]+#[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z.]{2,6}/i'; //email
$phonpat = '/(\(?([0-9]{3})+\)?[\-\s\.]?([0-9]{3})+[\-\s\.]?([0-9]{4})(( |-|\.)?[ext\.]+ ?\d+)|\(?([0-9]{3})+\)?[\-\s\.]?([0-9]{3})+[\-\s\.]?([0-9]{4}))/i'; //telephone
$phPat = '/([0-9]{3})([0-9]{3})([0-9]{4})/';
$vippatt = '/VIP/i';
for($f=0; $f<$fields; $f++){
$header.='"'.mysqli_fetch_fields($export, $f).'"'."\t";
}
for($i=0; $i<$num_rows; $i++){
for($x=0; $x<$fields; $x++){
$email = mysqli_fetch_assoc($export,$i,"EMAIL");
$phone = mysqli_fetch_assoc($export,$i,"PHONE");
$viprm = mysqli_fetch_assoc($export,$i,"VIP");
preg_match ($pattern, $email, $matches);
preg_match ($phonpat, $phone, $phoneno);
preg_match ($vippatt, $viprm, $vpmatch);
if(isset($matches[0])) {$emal=strtolower($matches[0]);} else {$emal="";}
if(isset($vpmatch[0])) {$vips=strtoupper($vpmatch[0]);} else {$vips="";}
if(isset($phoneno[0])) {$phne=preg_replace($phPat,'($1) $2-$3 ',formatPhone($phoneno[0],false,false));} else {$phne="";}
if(mysqli_fetch_fields($export, $x)=='EMAIL'){
$fld=$emal;
} else {
if(mysqli_fetch_fields($export, $x)=='PHONE'){
$fld=$phne;
} else {
if(mysqli_fetch_fields($export, $x)=='VIP'){
$fld=$vips;
} else {
if(mysqli_fetch_fields($export, $x)=='UNITS'){
$fld=1;
} else {
$fld = mysqli_fetch_assoc($export,$i,mysqli_fetch_fields($export, $x));
}
}
}
}
$data.= '"'.$fld.'"'."\t";
}
$data.="\n";
}
?>
Here is where the code checks if the data is blank or not, and then exports the spreadsheet:
<?php
if ($data == "") {
$data = "\nNo records found for your search parameters.\n\n".$sql;
} else {
echo "should show data";
}
global $time;
$time = time();
header("Content-Disposition: attachment; filename=CargoManagementCustomReport-$time.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>
When the spreadsheet gets exported, I see "should show data". This tells me the $data variable obviously has data. It's just not getting into the spreadsheet.
If you'll notice in the above, I'm using mysqli_fetch_fields. This was used to replace mysql_field_name (in my attempt to update to MySQLi).
I also tried mysqli_fetch_field, but got the same results.
I am getting no errors, but the spreadsheet is still blank.
I can echo $sql to get the query, and I can run the query in the database and it returns data.
What am I doing wrong and how can I fix it?
That whole code is gibberish, so I hope I understood what it is that it was meant to do.
Here are the main problems:
mysqli_fetch_fields() takes only 1 argument and returns an array of objects. You can't cast an array to a string. I assume you wanted to get the field name.
mysqli_fetch_assoc() takes only 1 argument and returns an array of data in an associative array as the name suggests. It also moves the internal pointer to the next row every time it is called. You are trying to use it as if it was mysql_result().
Your nested loops are very messy. I replaced them with simple foreach loops and replaced the nested if statements with a switch. While I would normally stay away from such constructs, this is the easiest way to migrate this code.
After removing all the mysqli nonsense, the code is now readable. It iterates over every field of every row, applying some transformations to some fields and concatenating the result into a string.
Fixed code:
$conn = $session->connDB();
$export = mysqli_query($conn, $sql);
$pattern = '/[A-Z0-9][A-Z0-9._-]+#[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z.]{2,6}/i'; //email
$phonpat = '/(\(?([0-9]{3})+\)?[\-\s\.]?([0-9]{3})+[\-\s\.]?([0-9]{4})(( |-|\.)?[ext\.]+ ?\d+)|\(?([0-9]{3})+\)?[\-\s\.]?([0-9]{3})+[\-\s\.]?([0-9]{4}))/i'; //telephone
$phPat = '/([0-9]{3})([0-9]{3})([0-9]{4})/';
$vippatt = '/VIP/i';
foreach (mysqli_fetch_fields($result) as $field) {
$header .= '"' . $field->name . '"' . "\t";
}
$data = '';
foreach ($export as $row) {
foreach ($rows as $fieldName => $value) {
switch ($fieldName) {
case 'EMAIL':
preg_match($pattern, $value, $matches);
$data .= '"' . (isset($matches[0]) ? strtolower($matches[0]) : '') . '"' . "\t";
break;
case 'PHONE':
preg_match($phonpat, $value, $phoneno);
$phne = "";
if (isset($phoneno[0])) {
$phne = preg_replace($phPat, '($1) $2-$3 ', formatPhone($phoneno[0], false, false));
}
$data .= '"' . $phne . '"' . "\t";
break;
case 'VIP':
preg_match($vippatt, $value, $vpmatch);
$data .= '"' . (isset($vpmatch[0]) ? strtolower($vpmatch[0]) : '') . '"' . "\t";
break;
case 'UNITS':
$data .= '"1"' . "\t";
break;
default:
$data .= '"' . $value . '"' . "\t";
break;
}
}
$data .= "\n";
}
Hi friends am trying to produce random words using order by rand but unable to produce.Here is my code
for($i=0;$i< 10;$i++) {
$result = mysqli_query($conn,"SELECT * FROM questions ORDER BY RAND() LIMIT 2");
if (!$result) {
/*die('Invalid query: ' . mysql_error());*/
die("Query failed".mysqli_error());
}
while ($row = mysqli_fetch_array($result)) {
$meta_descriptions = '{' $row['fact'] . ' ' . '|' $row['fact'] . '|' . $row['fact']}';
echo $meta_descriptions;
}
}
My questions table has one column that is column fact. i t has three values like
apple
ball
cat
Am getting output as
ball |ball| ball only
I want it to be random like
ball|cat|apple
How can I generate it
See this statement inside your while() loop,
$meta_descriptions = '{' $row['fact'] . ' ' . $row['fact'] . '}';
You're using same column value two times in each iteration of while() loop. Simply change your while() code section in the following way,
$meta_descriptions = '';
while ($row = mysqli_fetch_array($result)) {
$meta_descriptions .= $row['fact'] . '|';
}
$meta_descriptions = rtrim($meta_descriptions, '|');
echo $meta_descriptions;
Alternative method:
Create an empty array in the beginning. In each iteration of while() loop, push $row['fact'] value to this array. And finally apply implode() function on this array to get the desired result.
So your code should be like this:
$meta_descriptions = array();
while ($row = mysqli_fetch_array($result)) {
$meta_descriptions[] = $row['fact'];
}
$meta_descriptions = implode('|', $meta_descriptions);
echo $meta_descriptions;
change inside your while loop.
$meta_descriptions = '{';
$descriptions = array();
while ($row = mysqli_fetch_array($result)) {
$descriptions[] = $row['fact'];
}
$meta_descriptions .= implode(" | ",descriptions);
$meta_descriptions .= '}';
echo $meta_descriptions;
I got this code, which creates a table listing all the files of my directory $filedir. I also got a SQL database which lists the names and custom IDs of every file uploaded. For some reason, it only links me to the subpage with the cusom ID on the first file. The other ones link me to my xampp dashboard. I'd appreciate any kind of help/tips.
<?php
$myDirectory = opendir($filedir);
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
$dirArray2 = array_diff($dirArray, array('.', '..'));
array_splice($dirArray2, 1, 0);
closedir($myDirectory);
$indexCount= count($dirArray2);
echo("<TABLE id=myTable class=table-fill>\n");
echo("<thead><TR><th width=100px>---</th><th width=740px>Name</th><th width=160px>Last Modified</th></TR></thead>\n");
$j = 1;
echo "<tbody id=table class=fixed>";
if (count($dirArray2) == 0) {
echo("<TR>");
echo("<td> -- </td>");
echo("<td>No files uploaded yet</td>");
echo("<td> -- </td>");
echo("</TR>\n");
} else {
for ($i = 0; $i < $indexCount; $i++) {
echo("<TR>");
echo("<td><center><b>" . $j++ . "</b></center></td>");
$filename = $dirArray2[$i];
$owner = $user_data['username'];
$result = mysql_query("SELECT `url` FROM `uploads` WHERE `name` = '$filename' AND `owner` = '$owner'") or die(mysql_error());
$row = mysql_fetch_array($result);
echo("<td class=contextMenu>" . $dirArray2[$i] . "</td>");
echo("<td>" . date("m/d/Y h:ia", filemtime($filedir . $dirArray2[$i])) . "</td>");
echo "</tr>";
}
}
echo "</tbody>";
echo("</TABLE>\n");
?>
Note that I am quite new to PHP and SQL, so be kind please :)
I think there is something wrong with your query. Replace the "`" with "'". This sometimes happens if copy and pasting goes wrong. Also you need to put the variables in between the query, not in the string.
Like so:
"SELECT 'url' FROM 'uploads' WHERE 'name' = '".$filename."' AND 'owner' = '".$owner."'"
If that doesn't solve your problem see how many rows your query returns. You can just run it in your database program.
What I also recommend you do is run a 'select * from uploads', then looping the returned array with a foreach loop.
Something like this:
$content = "";
$result = mysql_query("SELECT * FROM 'uploads'");
$row = mysql_fetch_array($result);
$content.= "<table>";
$content.= "<th>Column1</th><th>Column2</th><th>Column3</th>";
foreach($row as $index => $value){
$content.= "<td>$value[$index][1]</td>";
$content.= "<td>$value[$index][2]</td>";
$content.= "<td>$value[$index][3]</td>";
}
$content.= "</table>";
print $content;
This should return a 3 column table with your data in. Not sure though, haven't tested it.
I'm generating dynamic content from a database like this:
$sql_select_items = $db->query("SELECT * FROM table WHERE ...);
Then it pulls the results, which may be one or multiple, like this:
while ($item_details = $db->fetch_array($sql_select_items))
{
$items_content =
'<table><tr> '.
'<td>RETRIEVED CONTENT HERE</td> '.
'</tr></table>';
}
Then, further down, I am outputting the generated content like this:
if ($section == 'summary_main')
{
$summary_page_content['content'] =
$summary_page_content['details'] .
$items_content .
$summary_page_content['messaging_received'] .
$summary_page_content['footer']
;
$template->set('members_area_page_content', $summary_page_content['content']);
}
Everything works except for the content generated by $items_content , which only displays 1 item no matter if there are 1 or 20. I tried to do a
$items_content . =
instead of
$items_content =
but that didn't seem to work either and just gave me an error.
What am I doing wrong?
It's not $db->fetch_array($sql_select_items) it's $sql_selected_items->fetch_array(). Here's how I would do it:
$table_rows = $db->query("SELECT * FROM table WHERE ...");
if($table_rows->num_rows > 0){
$table = '<table><tbody>';
while($row = $table_rows->fetch_object()){
$table .= "<tr><th>{$row->title_column_name}</th><td>{$row->other_column_name}</td></tr>";
}
$table .= '</tbody></table>';
}
else{
$table = '';
// no results
}
echo $table;
$table_rows->free(); $db->close();
Outside of (before) the while loop:
$items_content = '';
Inside the while loop:
$items_content .= '...';
This will make sure that your $items_content variable exists before your loop, and then the .= will concatenate your string to the end of $items_content.
"What am I doing wrong?"
As you didn't post the error, I can only assume you either got an undefined variable notice, which is solved by placing $items_content = ''; before the loop, or your got a syntax error because the operator you should be using is .= and not . = (note that the space is wrong).
I'm been hunting everywhere trying to find how to access data returned via a Zend db call. i want to append each columns value, comma delimited into a variable. I've always used associative calls in the past $row['fieldname'] etc.. but don't want to type out all the fields. I think I'm pretty close with the below but it's not working. Can someone point out my error? Thanks!
$data = $db->fetchAll($query);
$i=13; //number of columns
foreach($data as $row){
for($j=0;$j<$i;$j++) {
$csv_output .= $row[$j].", ";
}
$csv_output .= "\n";
}
Wow, you're over-complicating things! Try:
$csv_output = array();
foreach ($db->fetchAll($query) as $row)
{
$csv_output[] = implode(', ', $row);
}
$csv_output = implode("\n", $csv_output);
echo '<pre>';
print_r($csv_output);
echo '</pre>';