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).
Related
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
In my database, there is a table named CAT with a column named cat_id.
I need to fetch the cat_id field from the CAT table row by row without using a while loop.
This is what I have so far...
$catid = mysqli_query($con,"select * from cat");
$fetchcat = mysqli_fetch_assoc($catid);
Now I need data one by one like below...
<li>Men</li>
<li>Men</li>
Can someone suggest the next step? Thanks
One way or another, you have to loop... The most efficient option is usually to run the query, then to fetch rows one by one.
Here is a code sample to achieve that. Please note that since the only column you need to output is cat_id, it’s more efficient to select only that column in you sql statement rather than all available columns with select *.
$result = mysqli_query($con,"select cat_id from cat");
while ($row = mysql_fetch_assoc($result)) {
?><li>Men</li><?php
}
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
echo $row['cat_id'];
This question already has answers here:
Get last insert id after a prepared insert with PDO
(3 answers)
Closed 7 years ago.
I'm looking to be able to retrieve the last inserted id based on username. I know within PDO I am able to use to use lastInsertId() but from what I can tell that only gets the last one inserted with no other parameters. Is this possible in a short and simple?
The only way I thought I could do this was using something like
SELECT id FROM table_name WHERE username=:username ORDER BY enteredTimenDate ASC
Would this be the easiest way I could do this?
EDIT to address duplicate issue. The "Original" question this question is considered a duplicate of just asks how to retrieve the last inserted ID, my question was retrieving the last inserted ID based on another parameter.
Use following query to get the last inserted id:
SELECT id FROM table_name WHERE username=:username ORDER BY enteredTimenDate desc limit 1;
Data is sorted based on the enteredTimenDate in descending order and then picking up the first row by limiting the query result.
Let's say that I want to perform 2 MySQL operations:
Operation 1:
SELECT * From Comments ORDER BY ID DESC
Operation 2:
SELECT * From Comments WHERE Date >'2012-05-01', ORDER BY ID ASC
Clearly, the second table is contained within the first; the specifics are just hypothetical. My question: Rather than perform 2 separate MySQL queries as done above, is it possible to obtain just the first, use it, then LATER manipulate it using php to obtain the second? In the example above, the php function would need to alter the order of the table and remove inapplicable rows, but again, it's just an example.
Why do I care?
Well, I'm trying to limit the number of MySQL connections to my server. Rather than have 5 separate queries that reference the same one master table, I'd prefer to have just 1, and use php to manipulate it 4 times so as to get the same final product.
Thanks!
No, you cannot "alter the table". When you query the database from PHP, you're not getting "the table" back as a result, you're just getting a result set back. What you can perfectly do is store this result in a PHP variable and use PHP code to further filter or sort that data:
$result = $pdo->query('SELECT * From Comments ORDER BY ID DESC')->fetchAll();
$result2 = array_filter($result, function (array $row) {
return strtotime($row['Date']) > strtotime('2012-05-01');
});
usort($result2, function (array $a, array $b) {
return $a['ID'] - $b['ID'];
});
It seems that can be done like this:
Launch first query
iterate backwords through results (you will programatically have ASC order instead of DESC)
2a. for each record check if "Date" meets your criteria
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
This question already has answers here:
How to resolve ambiguous column names when retrieving results?
(11 answers)
Closed 2 years ago.
select * from A left join B on A.columnc=B.columnd
results returned by above SQL will include both columns of A and B.
And what if A and B have some columns with the same name?
How to retrieve the value from PHP?
You probably want to be more explicit in your query. That way you can provide aliases for your columns:
SELECT
A.foo as a_foo,
B.foo as b_foo
FROM A
LEFT JOIN B ON A.columnc = B.columnd
The answer is actualy in the PHP documentation:
"If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases. "
Especialy mysql_fetch_array() seems to be the best candidate when you insist on using star in the select statement:
$row = mysql_fetch_array($result, MYSQL_BOTH)
Then you can refer to the unambigous fields by $row[name] and to the ambigous one by $row[col_number], but that limits portability of your code (maybe next version of MySQL is going to return columns in a different order?). Recommended solution is to rewrite your query and list all the required fields instead of using star and for the ambigous ones - use aliases.
You should use column aliases in the select statement.
In Java+MySQL from the ResultSet object, you can use for example getString("a.id") and also getString("b.id"), if your query was like "SELECT a.id, b.id FROM a,b"
I dunno if there is something like this in PHP.
Regards
This may be useful to somebody: Because I was using some templating, I couldn't easily use aliases each time, and I wanted the associative array for ease of use.
CREDIT PILCROW for his answer on how to mysql_fetch_array on joined tables, but columns have same name, but in MySQLi:
$qualified_names = array();
for ($i = 0; $i < mysqli_num_fields($result); ++$i) {
$fieldinfo=mysqli_fetch_field_direct($result,$i);
$table = $fieldinfo->table;
$field = $fieldinfo->name;
$qualified_names["$table.$field"]="$table.$field";
}
$newrow = array_combine($qualified_names, mysqli_fetch_array($result,MYSQLI_NUM));