How to print an entire PHP array in a single HTML cell? - php

I have a HTML table where there are some columns. Each column is showing its own value. But in one cell of the table, I want to display an entire array of item-names separated by commas. I want the table cell to display like this:
User ID
Item Name
1
name1, name2, name3,....
$allitemnames holds the array values like name1, name2, name3 etc
This is my current code for fetching the array of items:
$itemnames="SELECT item_name FROM orderhistory WHERE uid='$userid' AND payment_mode = 'Cash'";
$itemnamescon=$con->query($itemnames);
$allitemnames=array();
while($x = mysqli_fetch_assoc($itemnamescon))
{
$allitemnames[]=array('item_name'=> $x['item_name']);
}
$itemsarrayresult = implode(", ", $allitemnames);
It's fetching the array properly because when I try to Echo out the $allitemnames outside the HTML table then it prints the whole array. But the main problem arises when i try to print it in a HTML table cell. I used the following code to print it:
echo"<tr style='color:white; background-color:#262626'>
<td><center>".$userid."</center></td>
<td><center>".$itemsarrayresult."</center></td>
</tr>";
This code does print multiple names in a single cell but the output is not at all what I want. It prints only "Array, Array, Array...."
Firstly it shows this warning message many times and it says-
Warning: Array to string conversion in C:\xampp\htdocs\Project\pendingpayments.php on line 62
and secondly the table looks like this:
User ID
Item Name
1
Array, Array, Array,....
I've had a look online but every forum I've come across has been people trying to loop through and print 1 value per td, not all values in one td

A couple of different approaches to this:
In php:
while($x = mysqli_fetch_assoc($itemnamescon))
{
$allitemnames[]=$x['item_name'];
}
$itemsarrayresult = implode(", ", $allitemnames);
In MySQL:
SELECT GROUP_CONCAT(item_name) FROM orderhistory WHERE uid='$userid' AND payment_mode = 'Cash'"

There is an multidimension array. You don't need her.
Do like this:
$allitemnames[] = $x['item_name'];

can you change your code as following and retry?
$itemsarrayresult = ''; //initialization
while($x = mysqli_fetch_assoc($itemnamescon))
{
$itemsarrayresult .= $x['item_name'].","; //concatenation
}
//now you need to display but variable will have an addirional ',' at the end so we will trim it using rtrim
echo '<tr style="color:white; background-color:#262626">
<td><center>'.$userid.'</center></td>
<td><center>'.rtrim($itemsarrayresult,',').'</center></td>
</tr>';

Related

How can I store large chunks into json file without memory crash?

I have an array $table and it contains 6000 items.
When I want to convert this array to json and store it into a file, my memory crashes.
So I had the idea to break the array into chunks of parts with 500 items:
$table = array_chunk($table, 500);
$table_json = $serializer->serialize($table[0], 'json', $context);
$myfile = fopen($_SERVER['DOCUMENT_ROOT']."/files/myfile.json", "w") or die("Unable to open file!");
file_put_contents($_SERVER['DOCUMENT_ROOT']."/files/myfile.json", $table_json);
This runs fast now, but of course now only 500 items are stored. Is there a way to add the other parts of the $table array without memory crash?
You could do something like this as you mentioned you know how to use array_chunk();
Let's look into simplifying the process with a built-in PHP function called array_chunk();
We'll be using HTML tables for design which isn't recommended. The task is better accomplished with CSS, you can follow same way without HTML and CSS.
Our table :
id datePosted firstName lastName pictureName anotherColumn
1 2013-07-01 John Smith SmithJohn.jpg anotherValue
2 2013-05-06 Elroy Johnson JohnsonElroy.jpg anotherValue
3 2013-06-18 Jake Bible BibleJake.jpg anotherValue
4 2013-07-17 Steve Stevenson StevensonSteve.jpg anotherValue
5 2013-04-08 Bill Smith SmithBill2.jpg anotherValue
Building HTML Tables
PDO query is used to grab the database information with prepared statements, Note that the loop only generates the code to display the columns.
The tests to detect where the rows begin and end are unnecessary.
//INITIALIZE VARIABLES
$colsToDisplay = 3;
$htmlOutput = array();
//GET PICTURE LIST
$sql = "SELECT datePosted, firstName, lastName, pictureName FROM pictureList ORDER BY datePosted DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$htmlOutput[] = "<td><img src='images/{$row['pictureName']}' alt='' /><br />{$row['firstName']} {$row['lastName']}</td>";
}
Once the loop is done, the array containing the column information can be broken into groups of three... or whatever value was assigned to $colsToDisplay, What we did here ? we tooks 3 columns from table, So divide table in two parts.
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//...
}
//BREAK THE COLUMNS INTO GROUPS
$htmlOutput = array_chunk($htmlOutput, $colsToDisplay);
All that's left is to display the table information. Note that array_chunk() creates a multi-dimensional array. The foreach loop is used to process the groups of columns. Each group is assigned to $currRow which contains an array of columns for the current row. The implode() function is used to quickly display the columns as a string.
Lets continue :
//BREAK THE COLUMNS INTO GROUPS
$htmlOutput = array_chunk($htmlOutput, $colsToDisplay);
//DISPLAY TABLE
print '<table>';
foreach($htmlOutput as $currRow) {
print '<tr>' . implode('', $currRow) . '</tr>';
}
print '</table>';
Checking For Missing Column Tags
One thing you may have noticed is the code to add missing columns was left out.
In other words, this example results in an HTML table where the last row only has two columns.
Apparently, the missing columns aren't needed according to the W3C Markup Validation Serviceā€¦ so they weren't included. However, they can be added by running the following code right before array_chunk() is called.
$colsDifference = count($htmlOutput) % $colsToDisplay;
if($colsDifference) {
while($colsDifference < $colsToDisplay) {
$htmlOutput[] = '<td></td>';
$colsDifference++;
}
}
Final Code :
//INITIALIZE VARIABLES
$colsToDisplay = 3;
$htmlOutput = array();
//GET PICTURE LIST
$sql = "SELECT datePosted, firstName, lastName, pictureName FROM pictureList ORDER BY datePosted DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$htmlOutput[] = "<td><img src='images/{$row['pictureName']}' alt='' /><br />{$row['firstName']} {$row['lastName']}</td>";
}
//OPTIONAL CODE
//IF NEEDED, ADD MISSING COLUMNS
$colsDifference = count($htmlOutput) % $colsToDisplay;
if($colsDifference) {
while($colsDifference < $colsToDisplay) {
$htmlOutput[] = '<td></td>';
$colsDifference++;
}
}
//END: OPTIONAL CODE
//BREAK THE COLUMNS INTO GROUPS
$htmlOutput = array_chunk($htmlOutput, $colsToDisplay);
//DISPLAY TABLE print '<table>';
foreach($htmlOutput as $currRow) {
print '<tr>' . implode('', $currRow) . '</tr>';
}
print '</table>';
Idea Behind This Tutorial :
You dont need to create a file and write arrays into that file to display in datatable.
If you still wants that you can (divide table in two parts) to create two arrays and than write into file, and than use array_push(); or array_merge(); to get both arrays into one.
I might have bad explanition please forgive for mistakes, Hope this help you in your coding life :)
Sticking to your solution, you can append the other chunks to your exisiting file. This works by setting the flag FILE_APPEND, e.g.:
$table_json = $serializer->serialize($table[1], 'json', $context);
$myfile = fopen($_SERVER['DOCUMENT_ROOT']."/files/myfile.json", "w") or die("Unable to
open file!");
file_put_contents($_SERVER['DOCUMENT_ROOT']."/files/myfile.json", $table_json, FILE_APPEND | LOCK_EX);
(LOCK_EX flag to prevent anyone else writing to the file at the same time)

PHP displays only the first value in a for() loop insinde another foreach() loop

I have small issue with a for() loop that displays values inside another foreach() loop in a dynamic way.
A small background of the code:
The output table is created dynamically based on the values obtain from one mysql query SELECT (which is the 1st select) from 1 column (that has name "coloane") in a table called "categories";
The values stored in the column "coloane" are actually the name of some columns from another table called "articles"
The first mysql select is to obtain the values from the column "coloane" so I can create the second.
After the second table returns rows (num_rows() > 0) I start to create the table.
The table has 2 static columns that are always present, and the rest of the columns are added dynamically based on different criteria.
The plot:
I explode the values obtained from the first select - from the column "coloane" - to make the [th]'s for the table header;
this explode I store it under the variable "$rows_th";
to make the [th]'s for the table header, i use a foreach() loop (and here I also remove any underscores);
after that I proceed to create the [tbody] and the [td]'s using another foreach(), only that this foreach is done for the values of the second select;
inside this foreach() I create another loop, using the for() function on the variable "$rows_th" so the table has the same length;
here the values are combined like this:
'<td id="'.$i.'">'.$values_td[$rows_th[$i]].'</td>';
The main issue is that, using the format listed above, it will only display the first value!
When I tried to verify the "$values_td[$rows_th[$i]]" using the is_string() function, I discovered that the first value is a string, and after that, every other value is not a string...
The test performed:
if (is_string($values_td[$rows_th[$i]]))
print '<td id="'.$i.'">Value found!!!</td>';
} else {
print '<td id="'.$i.'">No luck...</td>';
}
Any ideas on what might be going wrong ?
I know I'm missing something, but I just can't seem to figure it out :-/
The entire code is listed here: http://pastebin.com/4MFifh92
In the mean time, with the help from a friend, I finally found what was going wrong.
The variable turns from string to number because in the table called "categories", the column named "coloane" has the values inside devided by a "," (comma) and a " " (space), like so
------------------------------------------
| coloane |
------------------------------------------
make, model, location, comments, status
------------------------------------------
To fix this, I found out that I can try to do a str_replace in a simple foreach() loop :)
Something like this:
$i=0;
foreach($rows_th as $values_th) {
$i++;
$cols_td = str_replace(' ', '', $values_th);
$actual_value = $values_td->$cols_td;
print '<td id="'.$i.'">'.$actual_value.'</td>';
}
And this did the trick :)
Hope this will help others that came across with issues similar to this :)
Best regards,
Mike
Can't you just do something like:
SELECT * FROM results_query_header_by_cat WHERE `id` = 3;
Then:
SELECT * FROM results_query_content_by_cat WHERE `id_category` = 3;
Then with the results:
echo '[thead]';
foreach ( $results as $result ){
foreach( $result['coloane'] as $header ){
echo '[th]'.$header.'[/th]';
}
}
echo '[/thead][tbody]';
foreach ( $records as $record ){
echo '[tr][td]' .
$result['producator'] . '[/td][td]' .
$result['model'] . '[/td][td]' .
$result['imei'] . '[/td][td]' .
$result['locatie'] . '[/td][/tr]';
}
echo '[/tbody]';
Is that what you're looking for?
e: I haven't tried this but I'd imagine it's something like that. Just:
get the headers by category ID
get the records by category ID.
Echo the first result set as headers with a loop,
echo the second result set as table rows with columns in a loop.

Take data between a comma from a SQL row PHP

I'm about to write this code which stores numbers in a database, for example it's 1,2,3,4. I know how to store it in the database, etc, but I need to know to get those numbers out of the database, everyone on it's own where it can be used as a variable.
Example:
Database has a column called IDs, IDs contains the following:
1,2,3,4,5
In PHP I want to take every number in the column IDs, so there's a variable for every number.
$variable = 1;
$variable = 2;
etc
explode() can parse the string into an array of variables with one element of the array per number.
$str = '1,2,3,4,5';
$arr = explode(',', $str);
echo $arr[0]; // 1
echo $arr[1]; // 2
echo $arr[2]; // 3
echo $arr[3]; // 4
echo $arr[4]; // 5
However, storing strings of IDs in a database is generally undesirable. Usually there is a better database structure that can be used.
For example by using an additional table to associate rows from two other tables:
customers ( id, name, date_of_birth )
customer_addresses ( id, line1, line2, town, city )
customer_address_assoc ( customer_id, customer_address_id )
Using the explode method, you may have stored a field on the customer table such as address_ids. But by using an association table, this is a much better structure. It's easier to query, faster and generally more optimized. The association table would store a row for every address associated to the customer.
Best way to to this is using a foreach cycle but it depends on what you need.
This examples echoes all your numbers:
<?php
foreach($querynumberas $number){
$id = $number['id'];
echo $id;
}
?>
But this doesn't store all variables as you need, so to do this you should use this construct:
<?php
for ($i = 1; $i <= array.lenght(); ++$i) {
${'number'.$i} = $number['number'.$i]; // it stores: number1 = 1; number2 = 7; ecc
}
php?>

How to group the table rows and add summary row above the group?

I have an sql query that outputs a lot of information. What I need to do is group and summarize the information in the output table. Here is an example of what i'm trying to do:
name val1 val2 val3 total Run
some name 18 4 1 23
some name 5 4 1 23 2
some name 13 8 2 23 1
other name 2 2 0 4 1
and name 2 42 1 45 1
The name that is coming in from the database can appear more then once. If it does I group those items together and add the Summary row above which would have the same name but also compute the totals:
Val1 has to be added together
Val2, Val3 has to be the same as the row with the largest value in RUN cell
total value always stays the same.
There would be multiple occurrences of such grouping in the output table.
I tried to google my question but the closest that I got to what I was looking for was this this: How to add rows in middle of a table with jQuery?
which is not really what I am doing.
I'm not sure if there is an sql command that I could use to do that, or if it can be done in php or with use of jquery. Any suggestions will be appreciated.
Thank you!
Update:
I have tried using GROUP BY in sql, but it gives me syntax error:
SELECT name, val1, val2, val2, run
FROM tableName
WHERE ... ORDER BY name DESC GROUP BY name
(don't mind the WHERE ... I actually have statements there).
The only time it actually grouped the query when I have two or three results in the query and all of the three have the same name. So I though the GROUP BY is not the option.
In the php I am storing the name into a variable and checking if the name the same or not. if it's not the same i add master class to the row, if not the class is child, which helps me group it. However I didn't figure out a way to add a summary row above.
I was thinking for every time the name changes add a blank row and use jquery to populate it after page is loaded, however, for one time occurances of a name I do not need the summary.
As for, Val3 in the summary row I have made changes above. Val3 will be the same as the val3 in the row with the largest run value. I think I was confused by my own example.
I hope this information is more helpful.
Whenever I have to do something like this, I use multi-dimensional associative array with the top level keys being the highest level of grouping that I want to do. In your case, that would be "name".
In each element of that array, there is another assoc array with a key for each value that I want to keep track of. There is also a numbered sub-array that will contain each individual row that belongs in that grouping.
After I finish going through all the rows, I go through the resulting associative array and print the results.
For example:
<?php
/** Simulate of the results of your SQL query **/
$sql_result = array(
array("name"=>"some name ", "val1"=>5, "val2"=>4, "val3"=>1, "run" =>2),
array("name"=>"some name ", "val1"=>13, "val2"=>8, "val3"=>2, "run" =>1),
array("name"=>"other name", "val1"=>2, "val2"=>2, "val3"=>0, "run" =>1),
array("name"=>"and name", "val1"=>2, "val2"=>42, "val3"=>1, "run" =>1)
);
/** Add each result to your assoc array **/
$names = array();
foreach($sql_result as $row) {
$name = $row["name"];
// Create a new assoc array for each different name
if( !$names[$name] ) {
$names[ $name ] = array(
"name" => $row["name"],
"max_run" => $row["run"],
"val1" => $row["val1"],
"val2" => $row["val2"],
"val3" => $row["val3"],
"runs" => array( $row )
);
continue;
}
// Update the necessary values for the highest "run" number
if ($row["run"] > $names[ $name ]["max_run"]) {
$names[ $name ]["max_run"] = $row["run"];
$names[ $name ]["val2"] = $row["val2"];
$names[ $name ]["val3"] = $row["val3"];
}
// Update the reset of the values
$names[ $name ]["val1"] += $row["val1"];
$names[ $name ]["total"] = $names[ $name ]["val1"] + $names[ $name ]["val2"] + $names[ $name ]["val3"];
$names[ $name ]["runs"][] = $row;
}
/** Print your results **/
foreach ($names as $name) {
// Print your totals here like $name["total"], $name["val1"]
echo $name["name"]." ";
echo $name["val1"]." ";
echo $name["val2"]." ";
echo $name["val3"]." ";
echo $name["total"]."<br>";
if ( count($name["runs"]) > 1 ) {
foreach( $name["runs"] as $run ) {
echo print_r($run)."<br>";
}
}
echo "<hr>";
}
?>
This code is tested

Database data in PHP array

I have a table in phpmyadmin that stores an 'id' (auto inc), 'title' and a 'date'.
I have a webpage where I display the 10 latest items (I simply order by ID).
On that page I print the title and the date. My wish is to also display the number of the posted item, so the first posted item is 1, the second is 2, etc. I cannot simply print the ID from the database because if I delete a row, the numbers aren't straight anymore.
My idea was to put all the data in an array but I have no clue what the best way to do this is and how I could print that item number. So for example when I want to display the 54th item I can easily print $items[54][id] or something and it will show me the number 54 and to display the title I print $items[54][title].
I don't know if there are simpler methods, plus arrays always start at 0, but my items must start at 1.
Besides this page that shows the 10 latest items, there is another page where it gets the title of the item out of the URL. How will I be able to search the title in the array and display the data the same way but only for that requested title?
Thanks in advance!
"SELECT COUNT(id) as cnt FROM mytable";
you can select the count of all database entries.
and then assign it to your iterator
$i = $row['cnt']; // this will hold the ammount of records e.g. 21
// other query
while($row = mysql_fetch_assoc($result)) {
echo $i;
$i--; // this will decrement on every iteration 21, 20 , 19, and so on.
}
First off. I would add a timestamp field to the database and order by that instead as it feels overall more reliable and gives you additional details which may prove handy later.
To create the multidimensional array I would do something like:
$result = mysql_query(...);
$items = array();
while($item = mysql_fetch_assoc($result)) {
$items[] = $item;
}
Now $items[12] for example would give you item number 13 (since it's 0-indexed).
Lastly, to select only the item with a specific title I would use a query which included a WHERE clause, like
"SELECT ... FROM ... WHERE title = '".$title."'"
It's very important to sanitize this variable before using it in the query though.
You can read more about MySQL on a lot of places. A quick googling gave me this: http://www.tutorialspoint.com/mysql/index.htm
You should learn PHP before starting to program in PHP ;) Read and work through the PHP manual and some tutorials!
As to your question it is a simple loop you want to do. One way of doing it as an example.
Fetch the 10 last items from the database in any way you like, following some code, partly pseudo-code.
$markup = '';
for ($i=1; $i<=count($items); $i++)
{
$markup .= 'Item ' . $i . ': ' . $items['date'] . ' - ' . $items['title'];
$markup .= 'read more';
$markup .= PHP_EOL;
}
echo $markup;
I don't know how you print out your data exactly, but I assume there is a loop in there. Simply set a counter that increments by one at every row and print its value.
As for the title search, you'll have to run another query with a WHERE title = '$title' condition, but beware of SQL injection.

Categories