Not getting expected results from SELECT query [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to grab 10 results from a table that has 16k rows.
With in this table is a row called views that gets a +1 each time an artist is viewed.
But I'm getting unexpected results only the top artist.
I have the views row indexed for speed.
I know I have to loop it, but I'm unsure how to get all 10 rows
I haven't dealt with looping or getting more than one row at a time and need help formatting it with the new mysqli
example here with printout of array returned
// Get Top Viewed Artist
$TopViewedArtist = mysql_query("SELECT * FROM `artists` ORDER BY `artists`.`views` DESC LIMIT 10");
$TopViewedArtistInfo = mysql_fetch_assoc($TopViewedArtist);
$TopViewedArtist_TotalRows = mysql_num_rows($TopViewedArtist);
print_r($TopViewedArtistInfo); // the data returned from the query
This is the solution to display the results of the artist name in a readable format.
$TopViewedArtists = mysql_query('SELECT * FROM `artists` ORDER BY `artists`.`views` DESC LIMIT 10');
while (($TopArtist = mysql_fetch_assoc($TopViewedArtists)) !== FALSE) {
//print_r($TopArtist);
echo $TopArtist['artist']; echo "<br>";
}
This code can be change for others. but needs to be updated to mysqli

mysql_query returns a result resource object. Think of it as an array. The only way to read the contents of that array is to iterate through it. Think of mysql_fetch_assoc as the same as each for arrays: it returns the next row and increments the internal pointer. I think this is what you want to do:
<?php
// Get Top Viewed Artist
$TopViewedArtists = mysql_query('SELECT * FROM `artists` ORDER BY `artists`.`views` DESC LIMIT 10');
while (($artist = mysql_fetch_assoc($TopViewedArtists)) !== FALSE) {
print_r($artist);
}
?>
Keep in mind also that mysql_fetch_assoc returns an array with multiple values. The array is supposed to contain everything you see; access the values with $artist['artist'] (outputs Gwen Stefani).
May I suggest that you look into mysqli or PDO instead of the basic mysql functions? The only reason to use mysql_ functions is if you're stuck with PHP 4 (no longer supported so nobody should still be using it) or old applications. This looks like neither, and as it also seems you have no existing experience with the interface you really ought to look into the better options.

Basically, you want something like this:
$q=mysql_query("SELECT * FROM `artists` ORDER BY `artists`.`views` DESC LIMIT 10");
while($r=mysql_fetch_array($q)){//this will loop 10 times presuming there are at least 10 entries in your table
//use $r here, it represents a single row
print_r($r);
}
As other people have said, you should use mysqli or pdo and not the mysql_ functions

Related

Select Specific Rows in a Specific Order [duplicate]

This question already has an answer here:
MySQL sort by some list
(1 answer)
Closed 2 years ago.
I have a script (in PHP) that goes through a bunch of different comparisons to generate an ordered array of entries in a table by the row id. Then I'm imploding the array into a string and using WHERE to select those specific rows, however I don't know how to order them in the same order as they were in the array.
$order_array = [50,49,42,52,53,54,51,48,47]
$order_string = implode(',', $order_array);
// echo $order_string returns '50,49,42,52,53,54,51,48,47'
$sql_todo = "SELECT * FROM todo_list WHERE id IN ({$order_string})";
if ($result_todo = mysqli_query($link, $sql_todo)) {
while ($row_todo = mysqli_fetch_assoc($result_todo)) {
This successfully selects the desired rows, but they are not in the same order as the array. I know that I haven't told it to order them that way (so it didn't), but I don't know how to make it happen.
Thanks for your time,
Seth
You could use the field() function:
"SELECT * FROM todo_list WHERE id IN ({$order_string}) ORDER BY FIELD(id, {$order_string})"
field() returns the index of its first argument in the list, which you can directly use for ordering.
Side note: you should probably use a prepared statement rather than concatenating values in the query string (if your values come from outside your code, this is a must-have).

How to order two tables with no relationship and different columns, by a single column that they share (date) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I've got two tables in a MYSQL database. One Is a for blog posts and one is for videos. All the columns in each of them are different except for one which is the date they were created.
On the main page of my website I want to show most recent posts, whether that be a video or a blog post. So I want to order them based on their shared date column. Is this something I can do in MYSQL or would I have to pull all the data into php and then order it using my own function.
I've looked up other answers but they all seem to be cases where the tables have no relationship but share the same columns.
For table to be used in the same result set as you are suggesting, you would need a UNION; but UNIONs require all union-ed queries to have the same columns in their results. If the only field in common you have is "date"; the best you could probably do is something like.
SELECT `date` AS postDate, 'Video' AS postType
, someVideoField, null as someBlogField
FROM video_table
UNION
SELECT `date` AS postDate, 'Blog' AS postType
, null as someVideoField, someBlogField
FROM blog_table
ORDER BY postDate
;
Note: The latter aliases are not actually needed, I just tend to do that for clarity as to which field is expected to map to which. Also, the null as someBlogField portion may need tweaked to insure the result field is a type that can accept the real values from the latter half of the union; the first half determines field types.
If you end up using two queries it's easy enough to put them together in your script.
while ($row = $blogQuery->fetch()) {
$results[$row['date']]['blog'] = $row;
}
while ($row = $videoQuery->fetch()) {
$results[$row['date']]['video'] = $row;
}
If you ordered by date in your select queries, this will already be mostly in the right order, except for dates where only the video query has rows (or whichever one you fetched second). You can ksort($results) to fix the order for any of those.

How can I order html table with data from database? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've got a question regarding a html table and data from a database.
I managed to create a html table, which fetches data from a mysql database. So far it works fine. I am using auto increment within the database.
Unfortunately the html table is going from up to down. So the first entry has ID 1, while the last entry has a higher number. I want to change that so that the entry with the higher ID is displayed on top.
Is there any possibility to do that without Javascript or buttons? I didn't found a solution yet.
You can use ORDER BY change the list to start from higher number to the lower.
The ORDER BY keyword is used to sort the result-set by one or more columns, it sorts the result-set in ascending by default if you want it in descending (your case) you can use the DESC keyword.
So update your SQL query as follow.
SELECT *
FROM table_name
ORDER BY COLUMN_NAME_TO_SORT DESC
http://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html
You can also use PHP's usort() function to sort the result-set fetched from database.
Sample code to sort the array by specific column using usort()
usort($finalarray, function($a, $b) {
return $finalarray['COLUMN_NAME_TO_SORT'] - $finalarray['COLUMN_NAME_TO_SORT'];
});
// Assuming $finalarray is a result-set from database and it's an array.
Reference: http://php.net/manual/en/function.usort.php
ORDER BY in SQL directly is preferred and better option to sort the result by higher
ID to lower.
Yes you can do that in a MySQL statement:
SELECT *
FROM table
ORDER BY ID DESC
It's the last line you need to add. With ORDER BY you can set the order in which the SELECT results are presented. The order can be DESC (descending), or ASC (ascending). You can order on multiple columns, seperated by comma's, it will then first sort on the first column, then on the second, etc.

How to store a random SQL query by its ID? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
$randWord = mysql_query("SELECT * FROM words ORDER BY RAND() LIMIT 1");
After I call a random row from my table (which includes a word, its definition, and an id column) I want to store that word and definition so I can edit it if another button is pressed. From what I've seen online the common solution is to store it by its id. How do I store a random SQL query by its id?
Here's an example of where the pro tip
Never use SELECT * in software, instead give the names of the
columns you want.
would have helped you. If your words table has an id column, store that value.
RAND() and fetching by * is strongly not recommended because of it's bad performance.
Suggested example:
$total = mysql_result(mysql_query('SELECT COUNT(*) FROM words'), 0);
$randWord = mysql_fetch_array(mysql_query('SELECT wid, word, definition FROM words LIMIT '.rand(0, $total - 1).', 1'), 0);
Where mysql_result obtains the total number of records, mysql_fetch_array turns the result into an array. rand(0, $total - 1) generates a random number between available records, and then satisfy the [LIMIT start, limit] statement in the query.
You may build up your own DB class to reduce the code redundancy.
For your question, you should create a field as a primary key (or unique identifier). Like the 'wid' field I suggested above. Then you can output it as the value of a button and so on.

SELECT 'random' results with set parameters

I am developing a system which selects questions from a database to generate a test/exam.
Each question has a set 'question type' ('q_type'). I have a database of questions and need to select 4 questions, each with a different 'q_type'.
The basic query to select 4 random questions at the moment is:
SELECT * FROM questions ORDER BY RAND() LIMIT 0,4
This obviously does not take into account the fact that each question should have a different 'q_type'.
I would like to be able to do something that follows this logic (i need something to fill in the square brackets):
SELECT * FROM questions WHERE ['q_type' is DISTINCT] ORDER BY RAND() LIMIT 0,4
I have tried using GROUP BY 'q_type', but that simply gives the first question for each 'q_type', not a different question of that type each time.
Any help would be great, as I am completely stumped at the moment (I am working with a overblown PHP loop which simply queries the DB 4 times, with an updated WHERE 'q_type'!=XX each time).
Thanks for any help!
I don't think there's an easy way to do this with simple queries. You could probably do it with a mysql stored procedure, or to save some development time do it in php.
If the pool of questions isn't something extremely large, and this isn't something that happens too frequently, you should be ok with the 4 separate queries (one for each q_type), or even with getting the entire question set into php and then playing around with it to get 4 random questions, one in each q_type.
With the following (untested) code you'll be getting all questions ordered randomly and loop through them to get the first question for each q_type, then stop. It's not the most elegant solution but, again, for small enough data sets and frequency it should be ok.
$questions = array() ;
$res = mysql_query('SELECT * FROM questions ORDER BY RAND()') ;
while ($row = mysql_fetch_assoc($res)) {
//if we have all 4, stop
if (count($questions) == 4) {
break ;
}
$currType = $row['q_type'] ;
$currQuestion = $row['questionTitle'] ;
if (isset($questions[$currType])) {
//already have it, continue to the next
continue ;
}
$questions[$currType] = $currQuestion ;
}
i'm by no means an SQL expert but does this work?
SELECT DISTINCT `q_type`, * FROM questions ORDER BY RAND() LIMIT 0, 4

Categories