I have a query which gets all records ordered by last_name. Now I would like to create a loop that groups these results by the first letter of the last name and display the letter above the group i.e.
A
-----------
Albert
Alfred
C
-----------
Charles
D
-----------
Delta etc...
Thanks!
Order the results by lastname on MySQL side and track the change of the first letter on PHP side:
<?php
$rs = mysql_query("SELECT * FROM mytable ORDER BY lastname");
while ($rec = mysql_fetch_assoc($rs)) {
if ($initial !== strtoupper(substr($rec['lastname'], 0, 1)) {
$initial = strtoupper(substr($rec['lastname'], 0, 1));
print "$initial\n";
}
print $rec['lastname'] . "\n";
}
?>
$letter = null;
foreach ($array as $word) {
if ($letter != $word[0]) {
$letter = $word[0];
echo '<b>'.strtoupper($word[0]) . '</b><br/>';
}
echo strtoupper($word) . '<br/>';
}
and to tour query add line :
order by `your_field` asc
Allready tried something like this?
$last = '';
foreach($data as $key=>$row){
if(substr($row['last_name'],0,1)!=$last) echo '<br /><br />'.substr($row['last_name'],0,1).'<br />----------------<br />';
$last = substr($row['last_name'],0,1);
echo $row['last_name'];
}
In your view you could then loop the records and split them up:
$current = '';
foreach ($rows as $r) {
if (!$current || strtolower($r['name'][0]) != $current) {
$current = strtolower($r['name'][0]);
echo strtoupper($current).'<br />---------------';
}
echo $row['name'].'<br />';
}
in your query, try adding something like:
group by substr(last_name,1,1)
i.e.
select substr(last_name,1,1) as alpha, *
from tableName
group by substr(last_name,1,1)
Yes you can achive this using MySql itself
In my case brand_name going to be list out as you expected.
Example :
SELECT id, upper(SUBSTR(brand_name, 1, 1)) AS alpha FROM products WHERE brand_name != '' group by alpha
UNION
SELECT id, upper(SUBSTR(brand_name, 1, 1)) AS alpha FROM products WHERE brand_name != '' order by brand_name COLLATE NOCASE
Result :
A
A Card
A Cef
A Cef O
B
Bacticef Tab
Bacticin
Bactidrox
Bactidrox Kid
........
Hope it will help someone.
Related
I built a poll system. In this system, the values selected by the user are saved as 0,1,2. Now I want each user's choices to be counted.
For example:
Option one: 10 votes
Option two: 5 votes
Option three: 12 votes
...
foreach ($choices as $choice) {
echo $wpdb->get_var("SELECT COUNT(*) FROM mytable WHERE (id = {$_GET['id']} AND user_choice = {$choice}))");
}
try this:
user_choice: Column containing user votes
$sql=mysqli_query($con,"SELECT user_choice FROM mytable WHERE (id = {$_GET['id']} AND user_choice = {$choice}) ");
$arr = array();
while ($all = mysqli_fetch_array($sql, MYSQLI_NUM)) {
foreach($all as $val) {
$arr[] = $val;
}
}
$vote_choice = array_count_values($arr);
foreach($vote_choice as $name=>$qty) {
echo "Who Choice(".$name.'):->'.$qty.'<br />';
}
Hi i'm quite newbie in php language and i need to find same values in DESCRIPTION column in my database table.
id-------DESCRIPTION
1-------Final
2-------Exam
3-------Test
4-------Test
5-------Mid
6-------Quiz
7-------Quiz
As output it needs to be like:
Final
Exam
Test
Test
Mid
Quiz
Quiz
If a value repating just change them style is enough but i'm really don't know how to do it.
<?php
$check = mysqli_query($connection,"SELECT * FROM EXAMS");
while($test=mysqli_fetch_array($check))
{
echo $test["DESCRIPTION"];
}
?>
Use an EXISTS subquery to look if the same value exists for another id:
$result = $connection->query("
SELECT e.id, e.DESCRIPTION, EXISTS(
SELECT *
FROM EXAMS e2
WHERE e2.DESCRIPTION = e.DESCRIPTION
AND e2.id <> e.id
) as is_duplicate
FROM EXAMS e
ORDER BY e.id
");
Then check in PHP if it is a duplicate (if ($row['is_duplicate'] == 1)) and mark it bold:
while($row = $result->fetch_assoc())
{
if ($row['is_duplicate'] == 1) {
echo "<strong>$row['DESCRIPTION']</strong><br>";
} else {
echo "$row['DESCRIPTION']<br>";
}
}
PHP solution
$result = $connection->query("SELECT * FROM EXAMS");
$data = $result->fetch_all(MYSQLI_ASSOC);
$counts = array_count_values(array_column($data, 'DESCRIPTION'));
foreach($data as $row)
{
if ($counts[$row['DESCRIPTION']] > 1) {
echo "<strong>$row['DESCRIPTION']</strong><br>";
} else {
echo "$row['DESCRIPTION']<br>";
}
}
I am displaying a list of items based on a database. The order of the items is by ProductID.
When I add an item to the database, it is automatically assigned a ProductID.
However, I would like to be able to either
a) sort the list alphabetically by name, without changing the ProductID in the database or
b) add another column to the database called, for example: Rank, and have this list display the list by Rank, rather than by ProductID.
Here is my code. Any help in re-writing this section of the code to accomplish either a) or b) would be very helpful!
PS: I'm a little familiar with PHP and databases, but I am by no means an experienced coder.
$category = array_search(strtolower('upright'), $CFG["Category"]);
$product2 = new ProductData();
$where2 = sprintf(" WHERE CategoryID=%d ORDER BY ProductID DESC", $category);
$rows2 = $product2->GetRows($where2);
$count2 = count($rows2);
$line_count2 = 4;
$total_lines2 = ceil($count2/$line_count2);
// Photo
$photo5 = new PhotoData();
$thumb_array5 = array();
$count3 = count($rows2);
for ( $i = 0; $i < $count3; $i++ )
{
$ret = $photo5->Query($rows2[$i]["ProductID"]);
if ( $ret != 0 )
{
continue;
}
$thumb_array5[$photo5->Get("ProductID")] = $photo5->Get("Photo1");
}
Your SELECT query is not shown which I assume is coming from your ProductData() class. If you could change the source of your ProductData() that includes ranking, you could use a variable for ranking, like:
SELECT
#Ranking := #Ranking + 1 AS Rank,
productID,
product_name
FROM yourTable t, (SELECT #Ranking := 0) r
ORDER BY product_name;
Otherwise you could do it in your Php instead:
First change the ORRDER BY to your product name instead of product id:
$category = array_search(strtolower('upright'), $CFG["Category"]);
$product2 = new ProductData();
$where2 = sprintf(" WHERE CategoryID=%d ORDER BY Product_Name", $category);
Then in your php use a variable to do the ranking:
$count3 = count($rows2);
echo "<table><tr><th>Ranking</th><th>Product Name</th><th>Product Name</th></tr>";
for ( $rank = 0; $rank < $count3; $rank++ )
{
echo "<tr>";
echo "<td>$rank+1</td><td>".$rows2[$rank]["Product_name"]."</td><td><img src='".$photo5->Get("Photo1")."'></td>"
echo "</tr>";
}
echo "</table>";
I have a problem realizing some output to echo a list of results that comes from an Array.
I would like to create a Live search engine that runs a query by the help of keyup-function by using AJAX.
Everything works fine when the output will be echoed for every match that is listed in the table.
Now I would like to to combine all entries that are duplicates.
The code is like:
$search_term = $_POST['search_term'];
$where = "";
$search_term = preg_split('/[\s]+/', $search_term, -1, PREG_SPLIT_NO_EMPTY);
$total_search_terms = count($search_term);
$total_search_term = 0;
foreach ($search_term as $key=>$value) {
$total_search_term = $total_search_term + 1;
if ($total_search_term === 1){
if (is_numeric($value) ){
$where .= "(`a` LIKE '%$value%')";
} else {
$where .= "(`b` LIKE '%$value%')";
}
}else if ($total_search_term > 1){
$where .= " AND ";
if (is_numeric($value) ){
$where .= "(`a` LIKE '%$value%')";
} else {
$where .= "(`b` LIKE '%$value%')";
}
}
}
$duplicate = $db->query("SELECT a, b, COUNT(*) counter
FROM `table`
GROUP BY a, b
HAVING COUNT(*) > 1
");
$check = $duplicate->fetch_assoc();
$query = $db->query("SELECT a, b FROM table WHERE $where");
$result = $query->num_rows;
if ($result !== 0 ){
echo '<li id="hit">There are $result results!</li>';
while ($row = $query->fetch_assoc() ) {
echo '<li>',
$row["a"],
' ',
$row["b"],
'</li>';
}
} else {
echo '<li id="hit">no result!</li>';
}
To give an example of the output:
There are 3 results!
12345 New
12345 New
56789 Chicago
And thats how it should be:
There are 3 results!
12345 New (2x)
56789 Chicago
So the table is:
a | b
12345 New
12345 New
56789 Chicago
Thanks alot.
I thought of something like this:
$query = $db->query("SELECT a, b, COUNT(*) counter FROM `table` WHERE ".$where." GROUP BY a, b");
$result = $query->num_rows;
if ($result !== 0 ){
$resultSizeQuery = $db->query("SELECT COUNT(*) counter FROM `table` WHERE ".$where);
$resultSize = $resultSizeQuery->fetch_assoc();
echo '<li id="hit">There are '.$resultSize["counter"].' results!</li>';
while ($row = $query->fetch_assoc() ) {
echo '<li>'.$row["a"].' '.$row["b"];
echo ($row["counter"] > 1 ? " (".$row["counter"]."x)" : "");
echo '</li>';
}
} else {
echo '<li id="hit">no result!</li>';
}
Replacing all lines from "$duplicates = ..." to the end it should do it's work. Just give it a try because sometimes the step before the problem should be thought over.
Regards
parascus
first of all, your statement will return just 1 line with New York and the column counter will have 2. Chicago is missing because counter is just 1.
So I think your result looks like:
Ther are 1 results!
12345 New York
If you want to have "3 results" jsut do 2 queries, one for the number of rows (just leave out the group and having clause, also don't ask for a and b).
So you get the output:
There are 3 results!
Next you have to omit the having clause for getting all rows (also those without duplicates). You could write something like:
echo ($row["a"].' '.$row["b"].($row["counter"] > 1 ? " (".$row["counter"]."x)" : "")
I hope this helps.
Regards
Parascus
I have a query that I want to sort alphabetically, but the trick is that I want the sorting to treat two columns equally. For instance, if the first row of first_col equals apple and the second row of second_col equals aardvark I want the value in the second row of second_col to be listed before the value in the first row of first_col. A value (not NULL or '') will always exist in every row of second_col, but the value in first_col can be ''. Hopefully I have explained this good enough. I don't care if I have to use MySQL or PHP for this, but once sorted, the array is read through and echoed into an HTML table. Any thoughts?
EDIT
This is what I have for code right now. In my MySQL query I need b_name and l_name to be equal. The column b_name does not always have a value. When I put the values into the table it is based on the existence of b_name. If b_name does not exist the f_name and l_name are combined to replace b_name.
$query = "SELECT * FROM customers ORDER BY b_name, l_name";
$result = mysql_query($query);
mysql_close($link);
$num = mysql_num_rows($result);
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$class = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";
if($row[b_name]!=''){
echo "<tr class=".$class.">";
echo "<td>".$row[c_id]."</td>";
echo "<td>".$row[b_name]."</td>";
echo "<td>".$row[phone]."</td>";
echo "</tr>";
}
else{
echo "<tr class=".$class.">";
echo "<td>".$row[c_id]."</td>";
echo "<td>".$row[f_name]." ".$row[l_name]."</td>";
echo "<td>".$row[phone]."</td>";
echo "</tr>";
}
}
?>
</table>
If your tables are very similar you can do this
In my case I have a table test_a with 2 columns id and name
(SELECT * FROM test_a a1)
UNION ALL
(SELECT * FROM test_a a2)
ORDER BY name DESC
Your question isn't completely clear but you could try using this as your ORDER BY clause:
ORDER BY LEAST(first_col, second_col)
Demonstration:
CREATE TABLE table1 (first_col VARCHAR(100) NOT NULL, second_col VARCHAR(100) NOT NULL);
INSERT INTO table1 (first_col, second_col) VALUES
('a', 'b'),
('d', 'e'),
('f', 'c');
SELECT first_col, second_col
FROM table1
ORDER BY first_col, second_col;
a b
d e
f c
SELECT first_col, second_col
FROM table1
ORDER BY LEAST(first_col, second_col);
a b
f c
d e
Try
ORDER BY CONCAT(b_name, l_name)
or (if your fields are NULL when EMPTY)
ORDER BY COALESCE(b_name, l_name)
As they say above, UNION ALL is your friend, and, of course, if you have only one table, you can always do this:
(SELECT field1 AS name FROM TABLE1)
UNION ALL
(SELECT field2 AS name FROM TABLE1)
ORDER BY name DESC
So, you are asking for two diferent rows in the same table, and ordering it as it was one.
Thanks for all your help guys, but none of your answers allowed me to sort the data AND echo it into the HTML table correctly once sorted. A UNION might have worked, but I think my solution was faster as far as figuring it all out goes.
$query = "SELECT c_id, b_name, l_name, f_name, phone FROM customers";
$result = mysql_query($query);
mysql_close($link);
$num = mysql_num_rows($result);
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
if($row[b_name]!=''){
$new_result[$i]['c_id'] = $row[c_id];
$new_result[$i]['c_name'] = $row[b_name];
$new_result[$i]['phone'] = $row[phone];
}
else{
$new_result[$i]['c_id'] = $row[c_id];
$new_result[$i]['c_name'] = $row[l_name].", ".$row[f_name];
$new_result[$i]['phone'] = $row[phone];
}
}
foreach ($new_result as $key => $row) {
$c_id[$key] = $row['c_id'];
$c_name[$key] = $row['c_name'];
$phone[$key] = $row['phone'];
}
array_multisort($c_name, SORT_ASC, $c_id, SORT_ASC, $new_result);
for ($i = 0; $i < $num; $i++){
$class = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";
echo "<tr class=".$class.">";
echo "<td>".$new_result[$i]['c_id']."</td>";
echo "<td>".$new_result[$i]['c_name']."</td>";
echo "<td>".$new_result[$i]['phone']."</td>";
echo "</tr>";
}
?>
</table>