How to print list in opposite direction? - php

My question is by default list print in top to bottom direction but I want to print in bottom to top direction which means first value should be at bottom and last value on top.
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
$hh = '';
while ($row = $q->fetch_assoc())
{
$hh .= '<li>' . $row['name'] . '</li>';
}
?>
<ul id="myUL">
<?php echo $hh; ?>
</ul>
By default it will print:-
Mango
Apple
Grape
But I want:-
Grape
Apple
Mango

If you want to customize the order of results by select query you must create an additional field on the table where you define the order of the single element, after that you can use the select statement and order them by new field.
For example, you have theese columns on the table:
id, name, order_column, created_at
and you have 3 records on this table:
1, pippo, 1, 2019-02-10
2, pluto, 5, 2019-02-10
3, topolino, 3, 2019-02-10
where the third column is the order of element on the column, if you want to order by its you should use a query like this
select name from table_name order by order_column ASC
or
select name from table_name order by order_column DESC
that's it!

You should handle sorting with SQL query but you can also achieve this in PHP. Save the result into an array and reverse the order of rendering.
<?php
$plants = array();
while( $row = $q->fetch_assoc() ) {
$plants = $row['name'];
}
$index = count( $plants );
?>
<ul id="myUL">
<?php while( $index ) { ?>
<li><?php echo $plants[--$index]; ?></li>
<?php } ?>
</ul>
You can also try array_reverse.

This is quite simple. Sort your query results in descending order:
select name from plant order by name desc

Related

php code to update sort order according to category

I have the following table:
news(id,cat_id,headline,sub_top_priority)
I create drag and drop sortable list.
It change the sub_top_priority column order in database.
But i need this to change order of sub_top_priority column according to category.
for example.
Database has 6 rows
id cat_id headline sub_top_priority
1 15 good 1
2 15 Bad 2
3 15 Nice 3
4 15 Fine 1
5 16 Test1 2
6 16 Test2 3
if I Drag the second row and drop on first row then it only change order of category = 15 not of category = 16. category 16 sub_top_priority column remains as it is.
plz help me to make update and plz suggest what should i change in code...to update sub_top_priority column order according to cat_id.
I Try to change id with cat_id but this change all category in same sequence.
<?php
while ($sub_top = mysql_fetch_array($sub_top_select))
{
?>
<li id="recordsArray1_<?php echo $sub_top['id']; ?>"> <?php echo $sub_top['category_name']; ?> : <?php echo $sub_top['headline']; ?></li>
<?php } ?>
<?php
if(isset($_POST['change']))
{
$change = mysql_real_escape_string($_POST['change']);
$updateRecordsArray1 = $_POST['recordsArray1'];
if ($change == "updatesubtop")
{
$listingCounter1 = 1;
foreach ($updateRecordsArray1 as $recordIDValue1)
{
$query1 = "UPDATE news SET sub_top_priority = " . $listingCounter1 . " WHERE id = " . $recordIDValue1;
mysql_query($query1) or die($query1."<br/><br/>".mysql_error());
$listingCounter1 = $listingCounter1 + 1;
}
}
}
?>

php How to sort and brake while loop based on variable

I have a problem ... I can not solve it for two days. I am a beginner in php.
i don't understand why while loop returns me as much selects fields as every select field has options, for example field "choose color" has 3 options, red green and yellow and i get instead one select field 3 of them... see this http://5dstudio.eu/select.jpg
structure of my data base looks like this:
http://5dstudio.eu/data.jpg
my php code:
<?php
$sql = mysql_query("SELECT qty FROM attributes ORDER BY qty ");
while($row = mysql_fetch_array($sql)){
$name_attribute = $row["qty"];
$num = (int)$name_attribute;
echo "<select>";
$sql2 = mysql_query("SELECT name FROM attributes WHERE qty='$name_attribute' ORDER BY qty");
while($row2 = mysql_fetch_array($sql2)){
$value_attribute = $row2["name"];
echo '<option>' ."$value_attribute". '</option>';
}
echo "</select>";
}
?>
Thanks for any tips and help!
Change your first query to this:
SELECT qty FROM attributes GROUP BY qty
or
SELECT DISTINCT qty FROM attributes

Array Results in PHP

Is it possible to limit the results shown from a MYSQL database?
At the moment the results are shown in a html table, how do I only show the newest entries?
<?php
$con = mysql_connect("localhost","cl49-XXX","XXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cl49-XXX", $con)or die("Unable to select database");
$result=mysql_query("SELECT * FROM products") or die('You need enter a category');
echo "<tr>"; // first row beginning
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
$row = mysql_fetch_array($result);
$prodname = $row['prodname'];
$prodID = $row['prodID'];
$catagory = $row['catagory'];
echo "
<td>$prodID</td>
<td>$prodname</td>
<td>$catagory</td>
<td>
<a href=deleteproduct.php?q=$prodID' class='btn mini red'>
<i class='icon-trash'></i> Delete Item</a>
</td>";
echo "</tr><tr>"; // it's time no move to next row
}
echo "</tr>"; // last row ending
?>
Just switch your query to something like this!
$result=mysql_query("SELECT * FROM products LIMIT 0,10")or die('You need enter a catagory' );
LIMIT 0,10 will show the first 10 results from your DB.
You could even order it by a specific element in your DB.
$result=mysql_query("SELECT * FROM products ORDER BY objectName LIMIT 0,10")or die('You need enter a catagory' );
For further SQL basic help: http://www.sqlcommands.net/
Good luck!
Your question Consists of two parts.
First part: Is it possible to limit the results shown from a MYSQL database?
you can do that by using limitword inside the query.
Example:
mysql_query("SELECT * FROM products limit 1, 5");
The previous code say select all products and start from the product one and show me 5 products only.
Second part: how do I only show the newest entries ?
You can do that by, must first create column called date to your products table, then when add new product, store the time by using time() function into date column.
Then when you want to show the products order by newest products, you can use order by sentence.
Example:
mysql_query("SELECT * FROM products order by date ASC limit 1, 5");
To apply these words on your code, only need to
Add new column in your products table and call it date.
Then change the query that adds the products to products table to add also
the time to the date column by using time() function.
INSERT INTO tableName(date) VALUES('".time()."');
Show the products sorted order by newest by modify the query to
$result=mysql_query("SELECT * FROM products ORDER BY date ASC LIMIT 0, 15") or die('You need enter a category');
First of all, while you're still new, you should look into PDO/Prepared statements instead of mysql_ functions.
Also, you can do this for your SQL:
$result=mysql_query("SELECT * FROM products ORDER BY name DESC LIMIT 0,10")or die('You need enter a catagory ' );
'name' being the name of your products/row name you wish to sort it by
just add a counter and when the counter hits a number use:
break;
to jump out the loop.
for example
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
if ($i==3) break;
}
Of course you could better limit the loop itself:
use:
for ($i = 1; $i <= 4; $i++)
or use the LIMIT option in the SQL-query

PHP Mysql Left Join

<?php
$q = mysql_query("SELECT sub_cat.*, links.*
FROM links
LEFT JOIN sub_cat
ON links.p_id = sub_cat.id
WHERE sub_cat.p_id = '$id'
ORDER BY name ASC") or die (mysql_error());
while ($r = mysql_fetch_assoc($q))
{
$links_name = $r['name'];
$link_h3 = $links_name != '' ? '<h3>' . $links_name . '</h3>' : '';
//print $link_h3;
print '<pre>';
print_r ($r);
}
?>
I have two tables with rows like:
sub_cat
id
name
p_id
links
id
links
p_id
In sub cat i have movie categories, like foreign language movies, national movies, uncategorised movies and so on. In links table i have concrete movie links and depending on sub category.
The only thing is that i do not want dublicate titles (sub_cat.name).
result is:
Without Category www.moviesite.com
Without Category www.moviesite2.com
Without Category www.moviesite3.com
Foreign Movies www.moviesite1.bla
Foreign Movies www.moviesite2.bla
I want to be
Without Category www.moviesite.com
www.moviesite2.com
www.moviesite3.com
Foreign Movies www.moviesite1.bla
www.moviesite2.bla
and do not have any idea how to do this :(
any help appreciated.
To do the job, you have 2 solutions:
The first solution is to process your data before showing it, in order to group all movies by category.
You can do for example:
$moviesByCategory = array();
while ($r = mysql_fetch_assoc($q))
{
// Create the new sub array for the new category if necessary
if (!isset($moviesByCategory[$r['name']]))
$moviesByCategory[$r['name']] = array();
// Add the movie in the category
$moviesByCategory[$r['name']][] = $r['links'];
}
And then, you can now iterate on this new array like
foreach($moviesByCategory as $category => $movies)
{
// Print the category name
echo '<h1>' . $category . '</h1>';
// Print all movies of the category
foreach($movies as $movie)
echo '<h3>' . $movie . '</h3>';
}
The second solution is to modify the SQL query to group directly all movies that have the same category. You just have to use a GROUP BY clause on sub_cat.id and then apply an agregate function on all other fields in the select.
For performance aspect, the best solution is the SQL solution, but doing it with PHP will give you more flexibility for the presentation.
Try something like:
$lastSubcatName = "";
while ($r = mysql_fetch_assoc($q))
{
$links_name = $r['name'];
if($lastSubcatName != $links_name)
{
echo "<h1>".$links_name."</h1>";
$lastSubcatName = $links_name;
}
echo '<h3>' . $r['links'] . '</h3>';
}

PHP/SQL/Wordpress: Group a user list by alphabet

I want to create a (fairly big) Wordpress user index with the users categorized alphabetically, like this:
A
Amy
Adam
B
Bernard
Bianca
and so on.
I've created a custom Wordpress query which works fine for this, except for one problem: It also displays "empty" letters, letters where there aren't any users whose name begins with that letter. I'd be glad if you could help me fix this code so that it only displays the letter if there's actually a user with a name of that letter :) I've tried my luck by checking how many results there are for that letter, but somehow that's not working.
(FYI, I use the user photo plugin and only want to show users in the list who have an approved picture, hence the stuff in the SQL query).
<?php
$alphabet = range('A', 'Z');
foreach ($alphabet as $letter) {
$user_count = $wpdb->get_results("SELECT COUNT(*) FROM wp_users WHERE display_name LIKE '".$letter."%' ORDER BY display_name ASC");
if ($user_count > 0) {
$user_row = $wpdb->get_results("SELECT wp_users.user_login, wp_users.display_name
FROM wp_users, wp_usermeta
WHERE wp_users.display_name LIKE '".$letter."%'
AND wp_usermeta.meta_key = 'userphoto_approvalstatus'
AND wp_usermeta.meta_value = '2'
AND wp_usermeta.user_id = wp_users.ID
ORDER BY wp_users.display_name ASC");
echo '<li class="letter">'.$letter.'';
echo '<ul>';
foreach ($user_row as $user) {
echo '<li>'.$user->display_name.'</li>';
}
echo '</ul></li>';
}
}
?>
Thanks in advance!
Update:
I edited the SQL into this, but now I have the problem that it spits out an </ul> before the first li, which screws up the layout, like this:
</ul>
</li>
<li class="letter">
<div class="letter_head">A</div>
<ul>
<li>Abigail</li>
</ul>
</li>
<li class="letter">
<div class="letter_head">B</div>
<ul>
<li>Bernard</li>
<li>Bianca</li>
</li>
</ul>
It's in general pretty wonky about the ul and li nesting. How can I fix it?
<?php
$qry = "SELECT DISTINCT wp_users.user_login, wp_users.display_name,
LEFT(UPPER(wp_users.display_name), 1) AS first_char
FROM wp_users, wp_usermeta
WHERE UPPER(wp_users.display_name) BETWEEN 'A' AND 'Z'
OR wp_users.display_name BETWEEN '0' AND '9'
AND wp_usermeta.meta_key = 'userphoto_approvalstatus'
AND wp_usermeta.meta_value = '2'
AND wp_usermeta.user_id = wp_users.ID
ORDER BY wp_users.display_name ASC";
$result = mysql_query($qry);
$current_char = '';
while ($row = mysql_fetch_assoc($result)) {
if (!isset($current_char)) {
echo '<li class="letter"><div class="letter_head">'.$current_char.'</div>';
echo '<ul>';
} elseif ($row['first_char'] != $current_char) {
echo '</ul>';
$current_char = $row['first_char'];
echo '<li class="letter"><div class="letter_head">'.$current_char.'</div>';
echo '<ul>';
}
echo '<li>'.$row['display_name'].'</li>';
}
?>
A better solution would be to loop through all users in alphabetical order and for every record check if the first letter differs from that of the last record. If different, you echo out the new letter.
You are doing 52 database calls. Is the user table too big to grab all of them in one query? Also, I believe the order by on the count is unnecessary. I do not know if MySQL ignores it or not.
Your problem is get_results returns an single element array every time for the count query. So $user_count > 0 is always returning true. (I don't understand PHP logic most of the time. Is an array greater than zero?). You need to do something like $user_count[0] to get at the actual number.

Categories