How to fetch MySQLi data order by array values? - php

I have created an array, it is used to fetch data from MySQL server.
$ids = array(249853, 245549, 249851, 245552, 245551, 249854, 245550, 282445, 261747, 249852, 222398, 248072, 248390, 272473, 219212, 234140, 249815, 241089, 271940, 274940);
$sorted_ids = implode($ids, ",");
Fetched data using $sorted_ids which is ID to retrieve, but it is retrieved data by ID ascending order
$sql = "SELECT ID, number FROM table WHERE ID IN ({$sorted_ids})";
$result = mysqli_query($connection, $sql);
I have tried using == but it is showing only indexes matched records others not.
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
if( $ids[$i] == $row['ID'] ) {
echo $row['ID']."<br>";
$i++;
}
}
It is showing records if both indexes matched not other records.
How can I display records by $ids array list ?

Easiest way to do what you want is to the order it within your SQL
$sql = "SELECT ID, number FROM table WHERE ID IN ({$sorted_ids}) ORDER BY FIELD(id, {$sorted_ids})";
Should do the trick

Related

JSON object as array in array how to keep while loop going

My problem is:
I am joining tables together, and some tables have multiple data which I should fetch, but my JSON object only retrieves one. I think the reason for this is because the while loop loops through my main table aswell, fetches everything and stops looping, considering there is nothing left to loop through (I fetch my data based on my id in my database and these are auto_incremented etc).
So my question would be:
How can I loop through my main table (once), but keep on looping through the joined tables and insert these values in their 'own' array?
this is what I have right now:
$sqli = "SELECT event.*, typex.id, typex.type
FROM event
JOIN typex ON event.id = typex.id
WHERE event.id = ?";
mysqli_stmt_bind_param($stmt, 's', $editID); //fetch data based on ID
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data['all'] = array($row);
$data['type'] = array($row['type']);
}
//Echo data as JSON
echo json_encode($data);
So to give you an idea:
$data['all'] is the array which will hold all $row (this is so I can easily access columns from my main table)
$data['type'] however should only hold data from the table: typex (typex is a joined table).
an example:
You have a main table called: stack and a table you joined called: typex.
You want to insert all the rows with id number 5 from the table stack in the array $data['all'], considering the main table has an auto_increment on the id and unique, it will loop once... but now comes the part I fail at and need your help:
In your joined table: typex you have 2 rows with id number 5. these 2 rows should be fetched and inserted in the array $data['type']. How could this be achieved?
$data['all'] = array($row);
$data['type'] = array($row['type']);
This will always set the last $row's result, if you need all of the rows, you will need to do it like this:
$data[] = array('all'=>$row,'type'=>$row['type']);
Now each item of $data is an array with 2 keys, all and type
A few things to change here:
First in the query, as both the event and typex tables have an id column you will need an alias on one of them so you can distinguish between them, so I did that on typex.event also just in case.
$sqli = "SELECT event.*, typex.id as typex_id, typex.type as typex_type
FROM event
JOIN typex ON event.id = typex.id
WHERE event.id = ?";
Here I have amended the code to use the OO mysqli as its a whole lot easier to read
$stmt->bind_param('s', $editID);
$stmt->execute();
$result = $stmt->get_result();
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
$data = array();
$last_event = 0;
while ($row = $result->fetch_assoc()) {
if ( $last_event != $row['id'] ) {
$data['all'] = array($row);
$last_event = $row['id'];
}
$data['type'] = array('type' => $row['typex_type'], 'id' => $row['typex_id'] );
}
//Echo data as JSON
echo json_encode($data);
}

Selecting and displaying data from the last 5 entries in a table

So, after searching for a while here in stack overflow, I found a way of doing it:`
$sql = "SELECT username FROM (SELECT * FROM users ORDER BY id DESC LIMIT 5) sub ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
echo $row[0];`
However when I echo the $row[0] to get the first entry it doesn't display anything. I have checked my connection to the database and used the query on the phpmyAdmin and it worked fine, not sure why isn't it displaying the data (There is also a user in the table with the ID 1).
mysqli_fetch_assoc returns an associative array, not a numbered array. So the index of each column in the result is the column name, $row['username'].
If you want all 5 usernames, you need to call it in a loop. Each call just returns one row of the results, not all of them at once.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . '<br>';
}
To get a numbered array you use mysqli_fetch_row(). You still need the loop to get all of them.
while ($row = mysqli_fetch_row($result)) {
echo $row[0] . '<br>';
}

array in foreach loop

I'm taking data from mysql database table. The table have ID and "POST" columns. I've ordered posts by id's from bottom so i always have the newest post on the first place. But when i want to echo specific post (eg. with id 5) i can't echo it with $col = mysqli_fetch_array($result); echo $col;. I've tried with foreach loop but it echo's all posts. So I thought if i could put them into array with foreach loop it would do the job.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
}
I've tried a lot of things and spent a lot of time on research but still don't have idea how to do it.
Thanks for your ideas and help.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
if($col['id'] == 5) {
print_r($col);
}
}
mysqli_fetch_array fetchs a result row as an associative, a numeric array, or both.
You need to specify the name of the column you want to print out.
Because you may have more than one row in your result set, you should use a loop (while) like so:
while ($row = mysqli_fetch_array($result)) {
echo $row['POST']; // 'POST' here is the name of the column you want to print out
}
Hope this helps!
UPDATED:
If you want to get a specific post, you have to change your SQL to something like this:
$sql = "SELECT * FROM `post` WHERE `id` = $wanted_post_id";

Using a php function in a while loop to get the values and the counts of the values in same column

I am trying to perform a query inside a while loop that is getting values from a column. I am trying to query first to get all my values from a column in my DB and then get the count of how many times that value is in that column.
Examples of output trying to get
myValue is in the column 3 times
myOtherValue is in the column 10 times
myOtherOtherValue is in the column 22 times
Example of code
$sql = "SELECT DISTINCT id, columnName FROM tableName";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
function myCount($id)
{
$query = "SELECT COUNT(*) FROM tableName WHERE name = '$id'";
$result = mysql_query($query);
$count = mysql_fetch_array($result);
}
echo "$id is in the column $count[0] times";
}
You can't define a function inside the while loop.
Using COUNT(*) with a GROUP BY name clause, then you could solve the problem with only one query.

Returning each unique user from a MySQL table and also the count of the number of rows for each user

I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike

Categories