Here is how the database looks like
So I would like to display it like
Champion name
name of the column e.g. Q name of the spell - Surging Tides
the rest of spells for that champion
Next Champion etc.,
This is the way I display Champion names right now
$champions = $conn->prepare("SELECT *
FROM champions
Where Patch_No = ?");
$champions->bind_param('s', $Patch_No);
$champions->execute();
$champions_result = $champions->get_result();
while($row = $champions_result->fetch_assoc()){
echo $row['Champion'].' '.$row['NumNotNull'].'<br>';
}
I can't really think of an easy way to do this with the least amount of queries possible.
Here is another example how it should look like
$row is an associative array, so you can loop through it with foreach and test whether the column is empty.
while($row = $champions_result->fetch_assoc()){
echo $row['Champion'].' '.$row['NumNotNull'].'<br>';
foreach ($row as $column_name => $column) {
if ($column_name == 'Champion' || $column_name == 'NumNotNull') {
continue; // These fields were already displayed above
}
if (!empty($column)) {
echo "$column_name $column<br>";
}
}
}
Related
I have a query which selects userid,messageid,statusid from tableA like following.
$qry = mssql_query('select userid,messageid,statusid from tableA');
if(mssql_num_rows($qry))
{
$data = mssql_fetch_array($qry)
{
//if(current_status_id column value != next_status_id column value)
$status = $data['statusid'];
}
}
I need to compare the value of current statusid column with the immediate next row statusid column like this if(current_status_id column value != next_status_id column value).Is this possible.Pls help me
$qry = mssql_query('select userid,messageid,statusid from tableA order by statusid');
while (($row=mssql_fetch_array($qry) !== FALSE) {
if (isset($previous) && $previous['statusid'] !== $row['statusid']) {
// do what you gotta do here
}
$previous = $row;
}
I added order by statusid to your SQL so that you do get an order set of data. And rather than trying to "look ahead" to the next row, the code above "looks back" to the previous row ... which is effectively the same. You've got the data of the two rows in $previous and $row so you should be able to do what you wanna do with $previous.
I have created an array and assigned the results into it.Then I used while loop and checked if the current element is not equal to next element.
$i=1;
while (($row = mssql_fetch_array($qry, MYSQL_ASSOC)) !== false)
{
$data_array[] = $row; // add the row in to the results (data) array
}
mssql_data_seek( $qry, 0 );
while($msgDetailChilds = mssql_fetch_array($qry)){
if($data_array[$i]['groupid']!=$data_array[$i-1]['groupid'])
{
//do stuff
}
}
I have a mysql table called foods with columns "id, name, addinfo, picname, mg1cup, mg100g". I have a form where the user can submit between 1-20 food names. The php file takes the submitted food names in an array called $terms[]. I need to search the sql table for all terms and return results for all columns for each of the terms.
However, the results are only showing the first term submitted, repeated as many times as there are inputs (for example, if two words were inputted, the first term gets outputted in the results twice - instead of first word results, then second word results).
I don't know what I'm doing wrong. Here's my code (I haven't added the function to sanitize the strings yet):
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//connect to the wordpress (bluehost)DB
require_once '../../../wp-config.php';
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to mysql');
$Db = mysql_select_db(DB_NAME, $link) or die('Could not select database.');
//check to see if the search term has a value, matches "name" column in DB, and if so, put it into an array called terms
if (isset($_POST['terms'])) {
$terms = ($_POST['terms']);
if (count($terms) > 0 ) {
$results=array();
foreach($terms as $term) {
$sql = 'SELECT * from `wpqr_foods` WHERE `name` like "%'. $term .'%" ORDER BY name ASC';
$Q1 = mysql_query($sql);
if(mysql_num_rows($Q1)) {
while ($Res = mysql_fetch_assoc($Q1)) {
$results[] = $Res;
}
}
//$results = mysql_query($sql);
$sql = 'SELECT * from wpqr_foods WHERE name LIKE "%'. $term .'%" ORDER BY name ASC';
$Q2 = mysql_query($sql);
//get results
if(mysql_num_rows($Q2)) {
while ($Res = mysql_fetch_assoc($Q2)) {
$results[] = $Res;
}
}
}
if (count($results) > 0 ) {
foreach ($results as $CurRes ) {
echo $CurRes['name']. "<br/>";
echo $CurRes['addinfo']. "<hr/>";
/*
[id] => 5
[name] => Apples
[value] => Yes
[addinfo] => They can eat apples. They can also eat the skin of the apple and the leaves of the apple tree, but the tree leaves are high in calcium, so limit their intake. They can also chew on the apple tree branches.
[picname] => apple
[mgc1cup] => 5.8
[mgc100g] => 4.6
*/
}
}
else {
echo "(nothing entered)";//MEANS $TERM IS EMPTY
}
}
else {
echo "(nothing entered)";//means $_POST IS NOT SET (end of if(isset($_POST['term'])) { )
}
}
//function to sanitize array values from form
function sanitizeString($var) {
if (is_array($val))
{
foreach ($val as $k => $v)
{
$val[$k] = htmlentities(strip_tags($v),ENT_QUOTES);
}
}
else
{
$val = htmlentities(strip_tags($terms),ENT_QUOTES);
}
return $val;
}
?>
The HTML is
<div class="my-form">
<form role="form" id="step1" method="post" action="/wp-content/themes/mia/vitcdata.php">
<p class="text-box"><label for="box1">Food <span class="box-number">1 </span></label><input type="text" name="terms[]" value="" placeholder="apples" id="box1" /> <a class="add-box" href="#">Add More</a></p>
<p><input type="submit" value="Submit" /></p>
</form>
The form has dynamic form fields which users can add via javascript, and they can add up to 20 text inputs, in which all inputted terms get added to the $terms[] array.
So, if I test it, use two fields, and input "apples" and "bananas", the results show all the data for "apples" repeated twice.
Check this, you can check a related question here:
Using OR in LIKE Query in MySQL to compare multiple fields
You might have to do something like this in your query.
$sql = 'SELECT * from wpqr_foods WHERE name LIKE "%'. $term .'%" OR addinfo LIKE "%'. $term .'%" ORDER BY name ASC';
OR,
$sql = 'SELECT * FROM `wpqr_foods` WHERE CONCAT(name, addinfo ) LIKE "%'. $term .'%" ORDER BY name ASC';
I would recommend the following two ways forward:
It looks like the code block that queries the database and pushes results into $results is duplicated. You probably want to get rid of the duped block as that will create 2x results for each distinct term.
I suspect what's actually getting passed to the server through the form is a string containing whitespace-separated (or commas, or whichever separator the user chose to enter) terms. Even though you've chosen to pass it (and receive it server-side) as an array, it is actually a string and you will have to explode it (or some other method) yourself into an array. To check if that's the case (and if you haven't do so already), somewhere inside the foreach ($terms as $term) loop you should inspect $term to see if it is what you expect it to be.
I almost managed to split the different arrays and to prepare them in the table in the MySQL database, I'll explain the situation:
On the main page, the user has the ability to add and remove rows in a table. The table for each line carries with it these inputs:
input1.name = "product[]";
input2.name = "seller[]";
input3.name = "description[]";
input4.name = "quantity[]";
input5.name = "priece[]";
so if the user inserts two rows in each array will be included descriptions of two products, for example:
product: "PS3", "PS4";
seller: "AMAZON", "SONY";
description: "100Gb", "200Gb";
quantity: "1", "2";
price: "100", "200";
This is the layout table:
http://www.mediafire.com/view/ux0su8ssdixfmgc/Cattura2.JPG
The problem arises. I capture the data entered via a post, but I can't distribute these data on several lines. I want you to PS3 both into the first row of MySQL table, and PS4 in the second row of the table. Until now arrays are instantiated only on the first line, in this way, however, there is only one product. It is therefore necessary to prepare each box in the appropriate row of the array. I do not know if I was clear, but I would like to achieve something like this:
http://www.mediafire.com/view/d6f6ahy834jv0p2/Cattura.JPG
Obviously, the data in table I've entered manually and not through code. Was it right for you to understand.
This is the code that I currently use to send multiple arrays on different lines, but it doesn't work.
if(isset($_POST['sending']))
{
if($_POST['sending'] == "save")
{
$row_data = array();
foreach($_POST['sending'] as $key => $value)
{
$product=mysqli_real_escape_string($con,($_POST['product'][$row]));
$seller=mysqli_real_escape_string($con,($_POST['seller'][$row]));
$description=mysqli_real_escape_string($con,($_POST['description'][$row]));
$quantity=mysqli_real_escape_string($con,($_POST['quantity'][$row]));
$priece=mysqli_real_escape_string($con,($_POST['priece'][$row]));
$user=mysqli_real_escape_string($con,($_POST['user'][$row]));
$row_data[] = "('$product', '$seller', '$description','$quantity', '$priece', '$user')";
}
if (!empty($row_data))
{
$sql = 'INSERT INTO test(product,seller,description,quantity,priece,user) VALUES '.implode(',', $row_data);
$result = mysqli_query($con, $sql );
if ($result)
echo 'ADD COMPLETE!: ' . mysqli_affected_rows($con);
else
echo 'ERROR' ;
}
} // if ($_POST['sending'] == "save")
} // if (isset($_POST['sending']))
}//close method
if I understood it well this is how it should work
if(isset($_POST['sending']))
{
if($_POST['sending'] == "save")
{
$row_data = array();
foreach($_POST['sending'] as $key => $value)
{
$product=mysqli_real_escape_string($con,($_POST['product'][$row]));
$seller=mysqli_real_escape_string($con,($_POST['seller'][$row]));
$description=mysqli_real_escape_string($con,($_POST['description'][$row]));
$quantity=mysqli_real_escape_string($con,($_POST['quantity'][$row]));
$priece=mysqli_real_escape_string($con,($_POST['priece'][$row]));
$user=mysqli_real_escape_string($con,($_POST['user'][$row]));
array_push($row_data, "('$product', '$seller', '$description','$quantity', '$priece', '$user')");
}
foreach($row_data as $value){
if (!empty($value))
{
$sql = 'INSERT INTO test(product,seller,description,quantity,priece,user) VALUES '.$value;
$result = mysqli_query($con, $sql );
if ($result)
echo 'ADD COMPLETE!: ' . mysqli_affected_rows($con);
else
echo 'ERROR' ;
}
} // if ($_POST['sending'] == "save")
} // if (isset($_POST['sending']))
}//close method
I am using PHP 5.4 with a MySQL database.
This database represents a media library. The table I'm dealing with has one column, "Title", with obvious contents, and then a series of boolean columns, representing the availability of that title on a given platform. So a row looks like
TITLE: "Curb Your Enthusiasm: The Game"
PS4: 0
Atari 2600: 1
Dreamcast: 0
And so on.
The PHP code I would like to write be, in pseudocode,
Echo row[0] (title)
Cycle through other cells in the row
If the cell is '0' or NULL, do nothing
But if the cell is '1', echo the name of that column
So the result would be the echoing of
Curb Your Enthusiasm: The Game (Atari 2600, WonderSwan, Saturn)
It's the fourth statement that I can't quite work out. It seems to require the function mysqli_fetch_field, but I'm not sure of the syntax, and nothing I try after googling quite works.
I'd really appreciate any advice or examples someone could offer!
$database = mysqli_connect(SERVER,USERNAME,PASSWORD,'games');
$query = mysqli_query($database,"SELECT * FROM games` WHERE NAME LIKE '%ZELDA%'");
while ($row = mysqli_fetch_row($query)) {
echo $row[0]; // Echo title
for ($i=0;$i<sizeof($row);$i++) {
if ($row[$i] === '1') {
// ???????
}
}
}
Here is some rough untested code that should hopefully get you going.
while ($row = mysqli_fetch_assoc($query)) {
$columns = array(); // this will track the additional columns we need to display
foreach($row AS $column => $value) {
if($column == "title") {
echo $value; // this is the title, just spit it out
continue;
}
if($value == 1) {
// We have a column to display!
$columns[] = $column;
}
}
if(count($columns)) {
// We have one or more column names to display
echo " (" . implode(", ",$columns) . ")";
}
}
Some things to point out:
Using mysqli_fetch_assoc will allow you access to column names along with the values, which is useful here.
Keep track of the columns you want to display in an array first, this makes it easier at the end of each loop to format the output.
Sounds like you can do something like this:
// Simulates DB fetch
$titles = array(
array(
'TITLE'=>'Curb Your Enthusiasm: The Game',
'PS4'=>0,
'Atari 2600'=>1,
'Dreamcast'=>0
),
array(
'TITLE'=>'Curb Your Enthusiasm: The Book',
'PS4'=>1,
'Atari 2600'=>1,
'Dreamcast'=>0
)
);
foreach($titles as $title){
// get supported platforms
$supportedPlatforms = array();
foreach($title as $titleAttribute=>$titleValue){
if($titleAttribute != 'TITLE' && $titleValue == 1)
$supportedPlatforms[] = $titleAttribute;
}
echo $title['TITLE'] . ' (' . implode(', ', $supportedPlatforms) . ')' . "<br>";
}
Try running it here: http://phpfiddle.org/lite/code/pr6-fwt
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.