I'm trying to save into file a mysql SELECT query as follows:
$result = mysqli_query($db,$sql);
$out = fopen('tmp/csv.csv', 'w');
while ($row = $result -> fetch_row()) {
fputcsv($out,$row);
}
fclose($out);
after save I need to publish on a page as follows :
while ($row = mysqli_fetch_assoc($result)) {
//embed html code
}
The problem is that anytime I run $result->fetch_row(), a record of data is lost. I need to be able to run fetch_object at least 2 times within my code and preserve the data. I thought cloning would be a good solution for this, but it isn't.
Any hints, other that doing 2 query on the sql database ?
I believe another solution that could work is to use mysqli_data_seek.
The mysqli_result object is a pointer that moves through the data with each call of fetch_row(), but you can move the pointer back to the beginning by calling
mysqli_data_seek($result, 0);
And now the result is "reset", as it were, and you can use it again.
Learn more here:
https://www.php.net/manual/en/mysqli-result.data-seek.php
If you need to re-use the data, load it into an array - or do all the logic in the same loop.
So for example,
$data = []:
$result = $mysqli->query("...");
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
$out = fopen('tmp/csv.csv', 'w');
foreach ($data as $row) {
fputcsv($out, $row);
}
fclose($out);
// ...
foreach ($data as $row) {
//embed html code
}
Or do it all in the same loop (this may not always be possible, so if it isn't, go with the option above).
$result = mysqli_query($db, $sql);
$out = fopen('tmp/csv.csv', 'w');
while ($row = $result->fetch_row()) {
fputcsv($out,$row);
// embed HTML
}
fclose($out);
If you have mysqlind installed as part of your PHP MySQL infrastructure, Use a fetch_all() to get all the results into an array. You can then use that array as many times as you like.
$result = mysqli_query($db,$sql);
$all_results = $result->fetch_all();
$out = fopen('tmp/csv.csv', 'w');
foreach ( $all_results as $row){
fputcsv($out,$row);
}
fclose($out);
// now to reuse the array for your HTML output
foreach ($all_results as $row) {
//embed html code
}
Then you can reuse $all_results
If you dont have mysqlind then write a simple loop to load an array manually with all the results from the resultset
$result = mysqli_query($db,$sql);
$all_results = [];
while ($row = $result -> fetch_assoc()) {
$all_results[] = $row;
}
$out = fopen('tmp/csv.csv', 'w');
foreach ( $all_results as $row){
fputcsv($out,$row);
}
fclose($out);
// now to reuse the array for your HTML output
foreach ($all_results as $row) {
//embed html code
}
Related
I have database connection. I want to make an array but something is problem i think. Here is my array code:
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
foreach ($result as $row) {$data[] = $row;}
print_r($data);
$no=1;$total_deger=count($data);
echo $total_deger;
for($i=0;$i<$total_deger);$i++){
$xxx[i]="[Date.UTC(".$data[i]['year'].",".$data[i]['month'].",".$data[i]['day'].",".$data[i]['saat'].",".$data[i]['dakika'].",00),".$data[i]['Guc']."]";if($no < $total_deger){echo ",";}
echo $xxx[i];
}
When I run this code, nothing happens in page. When I write to for example 0 for i. I can see my array value. Where do I mistake?
Code with correction and suggestion (both are commented):-
<?php
error_reporting(E_ALL); // check all errors
ini_set('display_errors',1);// display those errors
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
if ($result->num_rows > 0) { // check you got results or not
while($row = $result->fetch_assoc()) {
$data[] = $row; // assign them
}
}
//foreach ($result as $row) {$data[] = $row;} // not needed
print_r($data);
$no=1;
$total_deger= count($data);
echo $total_deger;
for($i=0;$i<$total_deger;$i++){ // remove )
$xxx[$i]="[Date.UTC(".$data[$i]['year'].",".$data[$i]['month'].",".$data[$i]['day'].",".$data[$i]['saat'].",".$data[$i]['dakika'].",00),".$data[$i]['Guc']."]"; // use $i instead of i
if($no < $total_deger)
{
echo ",";
}
echo $xxx[$i];
}
Note:- Always add some error reporting code. So that all errors will populated and you can rectify those
Also better would be to use foreach() instead of for loop (as it will take care of indexes itself):-
//use foreach
foreach ($data as $dat){
echo "[Date.UTC(".$data['year'].",".$data['month'].",".$data['day'].",".$data['saat'].",".$data['dakika'].",00),".$data['Guc']."]";
}
Firstly you want to check your SQL query returns rows. Then I think you need to modify your foreach to a while as below. Also checking that rows are returned before looping.
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
As per example given here: http://www.w3schools.com/php/php_mysql_select.asp
I am doing my project in codeigniter. My issues is i will store value for 'game_aspect_details' in json format like
"{"game_aspect_details":[{"aspect_id":"1"},{"aspect_id":"4"}]}"
for this select query i will decode the json format and check that value in foreach.
$this->db->select('game_aspect_details');
$this->db->from('share_reviews');
$this->db->where('review_id',6);
$query = $this->db->get();
$result = $query->result();
$test = $result[0]->game_aspect_details;
$res = json_decode($test);
$result_array = array();
foreach ($res as $row)
{
$this->db->select('comments');
$this->db->from('review_ratings');
$this->db->where('game_aspect_id',$row->game_aspect_details); //here i need
$query1 = $this->db->get(); to check 1 and 4
$resultReviews['comments'] = $query1->result();
$result_array[] = $resultReviews;
}
print_r($res);
exit;
First this do see what you are getting in the $row within the foreach by using the print_r().
And I hope that you need to replace the below line
$this->db->where('game_aspect_id',$row->game_aspect_details);
With following line:
$this->db->where('game_aspect_id',$row['aspect_id']);
as $row is an array not an object.
EDITED:
foreach ($res as $rows)
{
foreach ($rows as $row)
{
........
$this->db->where('game_aspect_id',$row['aspect_id']); //here make change
.....
}
}
You are doing some things wrong, see the comments in this code:
...
//$test = $result[0]->game_aspect_details; // This does not work since $result is not decoded yet
$res = json_decode($result); // Changed to `$result` instead of `$test`
$res = $res->game_aspect_details; // Instead pick the `game_aspect_details` here, after the decode
$result_array = array();
foreach ($res as $row)
{
$this->db->select('comments');
$this->db->from('review_ratings');
$this->db->where('game_aspect_id',$row['aspect_id']); // Changed to `aspect_id`
$query1 = $this->db->get();
$resultReviews['comments'] = $query1->result();
$result_array[] = $resultReviews;
}
...
I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}
If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it
I am pulling data from my database and trying to encode into JSON data using json_encode. But to make it easier to read in my android app. I was hopping to format it differently then I am currently doing. Please see bottom encode string example. Any help would be great. Thanks in Advance.
$result = $db->query($query);
while($info = mysql_fetch_array($result))
{
$content[] = $info;
}
$count = count($content);
$result=array();
for($i=0;$i<$count;$i++)
{
$result[id][] = $content[$i]['imageID'];
$result[name][] = $content[$i]['Name'];
$result[thumb][] = $content[$i]['Thumb'];
$result[path][] = $content[$i]['Path'];
}
echo json_encode($result);
{"id":["1","2","3"],"name":["Dragon","fly","bug"],"thumb":["thm_polaroid.jpg","thm_default.jpg","thm_enhanced-buzz-9667-1270841394-4.jpg"],"path":["polaroid.jpg","default.jpg","enhanced-buzz-9667-1270841394-4.jpg"]}
But I am trying to format my array like so when it is encoded by json_encode.
[{"id":"1","name":"Dragon","thumb":"thm_polaroid.jpg","path":"polaroid.jpg"},{"id":"2","name":"Fly","thumb":"thm_default.jpg","path":"default.jpg"},{"id":"3","name":"Bug","thumb":"thm_enhanced-buzz-9667-1270841394-4.jpg","path":"enhanced-buzz-9667-1270841394-4.jpg"}]
Well, there is a problem. This is not valid JSON:
{"image":["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
"image":["2","fly","thm_default.jpg","default.jpg"]}
A JSON object can only have one value per unique key. This means that your latter image key would clobber the value of the former.
If you are content with this, however:
[["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
["2","fly","thm_default.jpg","default.jpg"]]
Then you can simply use mysql_fetch_row:
$result = $db->query($query);
while($info = mysql_fetch_row($result))
{
$content[] = $info;
}
echo json_encode($content);
Side Note:
Generally, in PHP, it is best to use foreach( $arr as $val ) (or $arr as $key => $val). for loops should be limited to when they are strictly necessary.
You need to add the iterator $i to the setting array
for($i=0;$i<$count;$i++)
{
$result[$i][id] = $content[$i]['imageID'];
$result[$i][name] = $content[$i]['Name'];
$result[$i][thumb] = $content[$i]['Thumb'];
$result[$i][path] = $content[$i]['Path'];
}
<?
$result = $db->query($query);
while($info = mysql_fetch_array($result))
$content[] = $info;
$result=array();
$count = count($content);
for ($x=0;$x<$count;++$x)
{
$result[$x][] = $content[$x]['imageID'];
$result[$x][] = $content[$x]['Name'];
$result[$x][] = $content[$x]['Thumb'];
$result[$x][] = $content[$x]['Path'];
}
echo json_encode($result);
?>