Formatting output from mysql (array of values) - php

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.

Related

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

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>';

Remove last comma from array after obtaining database results

I'm trying to list data from my database, and I need to use variables inside of my array, but when echoing it I want it to remove the last comma but it doesn't seem to work.
$forum_usersonline = $kunaiDB->query("SELECT * FROM users WHERE user_loggedin = '1'");
while($forum_usersonline_fetch = $forum_usersonline->fetch_array()) {
$usersonlineuname = $forum_usersonline_fetch["user_name"];
$onlinelist = array($usersonlineuname, ' ');
echo implode($onlinelist, ',');
}
It always returns with user1, user2, so how should I do it?
Your can do this job easily in sql. If your database is mysql try following
SELECT GROUP_CONCAT(user_name) as user_name FROM users WHERE user_loggedin = '1'
or if your database is postgres try following
SELECT string_agg(user_name, ',') as user_name FROM users WHERE user_loggedin = '1'
above query result return comma separated user_name.
You could use chop(); which removes characters from the right end of a string.
An example:
<?php
$str = "Random String Ending With,";
echo $str . "<br>";
echo chop($str,",");
?>
Or you could use rtrim(); like:
<?php
$str = "Random String Ending With,";
echo $str . "<br>";
echo rtrim($str,',');
?>
Or you could also use substr like:
<?php
$str = "Random String Ending With,";
echo substr($str,0,-1)."<br>";
?>
use rtrim(string,',')
For reference goto http://www.w3schools.com/php/func_string_rtrim.asp
The problem is you're doing the implode inside the while loop, it should be done outside after building your final array. This is what I would do:
$forum_usersonline = $kunaiDB->query("SELECT * FROM users WHERE user_loggedin = 1");
while ($row = $forum_usersonline->fetch_array()) {
$onlinelist[] = $row["user_name"];
}
echo implode($onlinelist, ",");
However, this should not be the case as you should be using CONCAT when doing your database query.

SQL Query not completing correctly - not sure why

Alright,
I've got a multiple select dropdown on a page called week-select, its selections get passed via ajax to my php page.
I can get the data just fine, but when the query runs it doesn't complete appropriately.
I've got this:
//Deal with Week Array
$weekFilter = $_GET['week']; /*This is fine, if it's 1 week the query works great (weeks are numbered 12-15), but if it is 2 weeks the result is formatted like this 12-13 or 13-14-15 or whichever weeks are selected*/
$weekFilter = str_replace("-",",",$weekFilter); /*This works to make it a comma separated list*/
.../*I deal with other variables here, they work fine*/
if ($weekFilter) {
$sql[] = " WK IN ( ? ) ";
$sqlarr[] = $weekFilter;
}
$query = "SELECT * FROM $tableName";
if (!empty($sql)) {
$query .= ' WHERE ' . implode(' AND ', $sql);
}
$stmt = $DBH->prepare($query);
$stmt->execute($sqlarr);
$finalarray = array();
$count = $stmt->rowCount();
$finalarray['count'] = $count;
if ($count > 0) { //Check to make sure there are results
while ($result = $stmt->fetchAll()) { //If there are results - go through each one and add it to the json
$finalarray['rowdata'] = $result;
} //end While
}else if ($count == 0) { //if there are no results - set the json object to null
$emptyResult = array();
$emptyResult = "null";
$finalarray['rowdata'] = $emptyResult;
} //end if no results
If I just select one week it works great and displays the appropriate data.
If I select multiple options (say weeks 12, 14 and 15) it runs the query but only displays week 12.
When I manually input the query in SQL, how I imagine this query is getting entered - it runs and displays the appropriate data. So if I put SELECT * FROM mytablename WHERE WK IN ( 12, 14, 15 ) it gets exactly what I want.
I can't figure out why my query isn't executing properly here.
Any ideas?
**EDIT: I make the array from the multiple selections a string using javascript on the front end before it is passed to the backend.
Your resulting query with values probably looks like this with a single value in IN:
… WK IN ("12,14,15") …
Either use one placeholder for each atomic value:
if ($weekFilter) {
$values = explode(",", $weekFilter);
$sql[] = " WK IN ( " . implode(",", array_fill(0, count($values), "?")) . " ) ";
$sqlarr = array_merge($sqlarr, $values);
}
Or use FIND_IN_SET instead of IN:
$sql[] = " FIND_IN_SET(WK, ?) ";
I don't think you can bind an array to a singular ? placeholder. Usually you have to put in as many ? values as there are elements in your array.
If your HTML is correct and your week select has name="week[]", then you will get an array back with $_GET['week'];, otherwise without the [] it will only give you 1 value. Then, you're doing a string replace, but it's not a string. Instead, try this:
$weekFilter = implode(',', $_GET['week']);

PHP Order in alphabetical order

I'm trying to make a simple alphabetical list to order items in my database. The thing I can't figure out is how to actually list it.
I would like it to be the same format as you have on miniclip.com
Here's an image
I looked around, but couldnt find an answer really.
(I would like it to finish even at the end of each vertical column, except the last one for sure)
Any help would be welcome!
In MySQL:
SELECT * FROM table ORDER BY name ASC
In PHP:
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
Assuming that your result set already is sorted by using the ORDER BY clause, to group the results by their first character you just need to remember the first character of the previous entry and print out the first character of the current entry if they are different. So:
$prevLabel = null;
while ($row = mysql_fetch_assoc($result)) {
$currLabel = strtoupper(substr($row['name'], 0, 1));
if ($currLabel !== $prevLabel) {
echo $currLabel;
$prevLabel = $currLabel;
}
echo $row['name'];
}
This will print the first character as a label for each group that’s members have the same first character.
He doesn't seem to have an issue with the storting, but doing the column format and headers for each new letter.
Suppose $arr contains your alphabetically sorted list with numeric keys. each element has indexes 'name' and 'link'. This should be pretty safe assumption for data from a SQL query.
$firstLetter = -1;
$desiredColumns = 4; //you can change this!
$columnCount = (count($arr)+27)/$desiredColumns+1;
echo "<table><tr><td>";
foreach($arr as $key => $cur)
{
if ($key != 0 && $key % desiredColumns == 0) echo "</td><td>";
if ($cur['name'][0] !== $firstLetter)
{
echo "<strong>$firstLetter</strong> <br />"; $firstLetter = $cur['name'][0];
}
echo "".$cur['name']."<br />";
}
echo "</td><tr></table>";
You'll have to treat numbers as a special case, but this is the idea. If you are using a template engine there are obviously better ways of doing this, but I figure you would have mentioned that. This is a rough sketch, making pretty HTML isn't my thing.
--Query-- get table into $arr. I can't see your tables obviously, Im making assumptions if names nad stuff so you'll need to verify or change them
$sql = "SELECT * FROM table T ORDER BY name";
$conn = //you should have this
$res = mysql_query($sql, $conn);
$arr = array();
while($row = mysql_fetch_assc($res)
$arr[] = $row;
// start above code here. This isn't safe for empty query responses or other error but it works
I presume you're using MySQL (or another SQL) database, in which case you should simply retrieve the data in the required order using a SORT BY clause on the lookup SELECT. (Sorting this PHP is trivial via the sort function, but it makes sense to get the database to do this - that's pretty much what it's for.)
In terms of balancing the output of each of the columns, you could get a COUNT of the required rows in your database (or simply use the count of the resulting PHP array of data) and use this to ensure that the output is balanced.
As a final thought, if this is going to be output on a per-page basis, I'd highly recommend generating it into a static file when the structure changes and simply including this static file as a part of the output - generating this on the fly is needlessly resource inefficient.
The mysql option mentioned above is definitely the best bet. If the data comes out of the DM in order, that's the simplest way to go.
Your next option might be to look at the
asort and ksort functions in PHP to find the exact one you're looking for.
http://www.php.net/manual/en/array.sorting.php
How are you pulling the data?
<?php
$result = mysql_query("SELECT titles FROM gamelist ORDER BY title ASC");
while ($row = mysql_fetch_assoc($result)) {
echo "{$result['title']}<br/>";
}
?>
There are two ways to do it.
You could use your database and use the 'order' clause to pull them by a specific field alphabetically.
You could also use either a key sort or value sort on a PHP array.
The PHP functions are sort($array) and ksort($array).
http://php.net/manual/en/function.sort.php
http://php.net/manual/en/function.ksort.php
<?php
$list = $your_list_array_from_database
//if you need info on how to do this, just let me know
sort($list);
foreach($list as $item) {
echo $item;
}
?>
I found this post and had the same problem. I used the code below to output a list by category name with a header equal to the first letter. In my database table (category) I have name and category_letter. So, name = football and category_list = 'F'.
<section>
<?php
try {
$cats_sql = $dbo->prepare("SELECT name, category_list, FROM category WHERE category_list REGEXP '^[A-Z#]' GROUP BY category_list ASC");
$cats_sql->execute();
$results_cats = $cats_sql->fetchAll();
} catch(PDOException $e) {
include('basehttp/error');
}
$array_cats = $results_cats;
if(is_array($array_cats)) {
foreach($array_cats as $row_cats) {
$cat_var = $row_cats[category_list]; // Each Category list title
?>
<aside>
<h1><a name=""><? echo $cat_var ?></a></h1>
<?php
try {
$search_sql = $dbo->prepare("SELECT name, category_list FROM category WHERE category_list=:cat_var ORDER BY name ASC"); // Pulling a list of names for the category list
$search_sql->bindParam(":cat_var",$cat_var,PDO::PARAM_STR);
$search_sql->execute();
$results_search = $search_sql->fetchAll();
} catch(PDOException $e) {
include('basehttp/error');
}
$array_search = $results_search;
if(is_array($array_search)) { // Output list of names which match category
foreach($array_search as $row_search) {
?>
<h2><?php echo $row_search[name]; ?></h2>
<br class="clear">
<?php
}
}
?>
</aside>
<br class="clear">
<?php
}
}
?>
</section>
Its actually Simple....I did similar thing for my project once. I had to pull out all music albums name and categorize them in alphabetical order.
In my table, "album_name" is the column where names are stored.
$sql= "select * from album_table order by album_name ASC";
$temp_char= ""; // temporary variable, initially blank;
using while loop, iterate through records;
while($row= $rs->fetch_assoc())
{
$album_name= $row['album_name'];
$first_char_of_albm= $album_name[0]; // this will store first alphabet;
$first_char_of_albm= strtoupper($first_char_of_albm); // make uppercase or lower as per your needs
if($temp_char!=$first_char_of_albm)
{
echo $first_char_of_albm;
$temp_char= $first_char_of_albm; // update $temp_char variable
}
}
That's it....
I am posting my answer to this old question for 3 reasons:
You don't always get to write your queries to MySQL or another DBMS, as with a web service / API. None of the other answers address PHP sorting without query manipulation, while also addressing the vertical alphabetical sort
Sometimes you have to deal with associative arrays, and only a couple other answers deal with assoc. arrays. BTW, my answer will work for both associative and indexed arrays.
I didn't want an overly complex solution.
Actually, the solution I came up with was pretty simple--use multiple tags with style="float:left", inside of a giant table. While I was sceptical that having multiple tbody tags in a single table would pass HTML validation, it in fact did pass without errors.
Some things to note:
$numCols is your desired number of columns.
Since we are floating items, you may need to set the width and min-width of parent elements and/or add some <br style="clear: both" />, based on your situation.
for alternative sorting methods, see http://php.net/manual/en/array.sorting.php
Here's my full answer:
function sortVertically( $data = array() )
{
/* PREPARE data for printing */
ksort( $data ); // Sort array by key.
$numCols = 4; // Desired number of columns
$numCells = is_array($data) ? count($data) : 1 ;
$numRows = ceil($numCells / $numCols);
$extraCells = $numCells % $numCols; // Store num of tbody's with extra cell
$i = 0; // iterator
$cCell = 0; // num of Cells printed
$output = NULL; // initialize
/* START table printing */
$output .= '<div>';
$output .= '<table>';
foreach( $data as $key => $value )
{
if( $i % $numRows === 0 ) // Start a new tbody
{
if( $i !== 0 ) // Close prev tbody
{
$extraCells--;
if ($extraCells === 0 )
{
$numRows--; // No more tbody's with an extra cell
$extraCells--; // Avoid re-reducing numRows
}
$output .= '</tbody>';
}
$output .= '<tbody style="float: left;">';
$i = 0; // Reset iterator to 0
}
$output .= '<tr>';
$output .= '<th>'.$key.'</th>';
$output .= '<td>'.$value.'</td>';
$output .= '</tr>';
$cCell++; // increase cells printed count
if($cCell == $numCells){ // last cell, close tbody
$output .= '</tbody>';
}
$i++;
}
$output .= '</table>';
$output .= '</div>';
return $output;
}
I hope that this code will be useful to you all.

Displaying multidimensional array in php

I have an array like this:
$tset = "MAIN_TEST_SET";
$gettc = "101";
$getbid = "b12";
$getresultsid = "4587879";
$users["$tset"] = array(
"testcase"=>"$gettc",
"buildid"=>"$getbid",
"resultsid"=>"$getresultsid"
);
Arrays in PHP is confusing me.
I want to display some like this:
MAIN_TEST_SET
101 b12 4587879
102 b13 4546464
103 b14 5545465
MAIN_TEST_SET3
201 n12 45454464
MAIN_TEST_SET4
302 k32 36545445
How to display this?
Thanks.
print_r($users)
That will print your array out recursively in an intuitive way. See the manual: http://us2.php.net/manual/en/function.print-r.php
If you want to print it in the specific way you formatted it above you're going to have to write a custom function that uses foreach looping syntax like this:
<?php
echo "<table>";
foreach($users as $testSetName=>$arrayOfTestCases){
echo "<tr><td>".$testSetName."</td></tr>";
foreach($arrayOfTestCases as $k=>$arrayOfTestCaseFields){
//$arrayOfTestCaseFields should be an array of test case data associated with $testSetName
$i = 0;
foreach($arrayOfTestCaseFields as $fieldName => $fieldValue){
//$fieldValue is a field of a testcase $arrayOfTestCaseFields
if($i == 0){
//inject a blank table cell at the beginning of each test case row.
echo "<tr><td> </td>";
$i++;
}
echo "<td>".$fieldValue."</td>";
}
echo "</tr>";
}
}
echo "</table>";
?>
Your data should be composed as follows:
$tset = "MAIN_TEST_SET";
$gettc = "101";
$getbid = "b12";
$getresultsid = "4587879";
$users[$tset] = array();
$users[$tset][] = array( "testcase"=>"$gettc",
"buildid"=>"$getbid",
"resultsid"=>"$getresultsid"
);
$users[$tset][] = ... and so forth ...
To fix the data structure you present (as Victor Nicollet mentions in his comment) you need something like this:
$users = array(); // Create an empty array for the users? (Maybe testsets is a better name?)
$testset = array(); // Create an empty array for the first testset
// Add the test details to the testset (array_push adds an item (an array containing the results in this case) to the end of the array)
array_push($testset, array("testcase"=>"101", "buildid"=>"b12", "resultsid" => "4587879"));
array_push($testset, array("testcase"=>"102", "buildid"=>"b13", "resultsid" => "4546464"));
// etc
// Add the testset array to the users array with a named key
$users['MAIN_TEST_SET'] = $testset;
// Repeat for the other testsets
$testset = array(); // Create an empty array for the second testset
// etc
Of course there are much more methods of creating your data structure, but this one seems/looks the most clear I can think of.
Use something like this to create a HTML table using the data structure described above.
echo "<table>\n";
foreach($users as $tsetname => $tset)
{
echo '<tr><td colspan="3">'.$tsetname.'</td></tr>\n';
foreach($tset as $test)
echo "<tr><td>".$test['testcase']."</td><td>".$test['buildid']."</td><td>".$test['resultsid']."</td></tr>\n";
}
echo "</table>\n";
The first foreach iterates over your test sets and the second one iterates over the tests in a test set.
For a short uncustomisable output, you can use:
print_r($users)
alternatively, you can use nested loops.
foreach($users as $key => $user) {
echo $key . "<br />"
echo $user["testcase"] . " " . $user["buildid"] . " " . $user["resultsid"];
}
If you are not outputting to html, replace the <br /> with "\n"

Categories