Filtering an array in PHP - php

i have a script which takes data from a database and displays it on a page.
It sorts the rows by an id number, and displays them in that order
heres the script
// get the info from the db
$sql = "SELECT showtime, html FROM showfeed ORDER BY showtime ASC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result))
{
// echo data
echo $list['html'] . "<hr />";
} // end while
what I want to do is filter that data so that if the ID number of a row is less than a given number than it won't be displayed. And if it is greater than a certain number it will be displayed normally.

Do it in the database query.
SELECT ... WHERE id > $certainNumber ...
If, for whatever reason, you want to do it in PHP:
while ($list = mysql_fetch_assoc($result)) {
if ($list['id'] < $certainNumber) {
continue;
}
...
}

Assuming ID is a field in your table:
$sql = "SELECT id, showtime, html FROM showfeed ORDER BY showtime ASC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
$targetID = 120;
while ($list = mysql_fetch_assoc($result))
{
// echo data
if ($list['id'] < $targetID) continue;
echo $list['html'] . "<hr />";
} // end while
However, if this would work for you, then probably better to change your query to
$sql = "SELECT showtime, html FROM showfeed WHERE id > 120 ORDER BY showtime ASC LIMIT $offset, $rowsperpage";

Filter sql query (the word "array" is not right here).
you have to filter the query using sql instead of your application
Something like that
SELECT showtime, html FROM showfeed WHERE ID > ?? AND ID < ?? ORDER BY showtime ASC

Related

How to echo result from query

Maybe I am overthinking this, but I have narrowed my query to find a row down to 1 result that I need, and it will not display. Wondering if someone could tell me what I am doing wrong.
$result = mysqli_query($link, "SELECT pageid FROM article ORDER BY id DESC LIMIT 1");
$row = mysqli_use_result($result);
echo $row;
I have it selecting the last row and supplying me with the stored data from the pageid of the last row.
I had to adapt my code. I believe it was because I use mysql. However, this code will work if you use mysqli
$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);
if ($resultpageid->num_rows > 0) {
while ($row = $resultpageid->fetch_assoc()) {
$pagenumber = $row["pageid"];
}
} else {
echo "0 results";
}
mysqli doesn't have any function to get a single column from a single row. You need to use one of the fetch methods e.g. fetch_array(). You don't need any loop if you use LIMIT 1.
Just fetch a single row and get the column from the returned array:
$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);
$row = $resultpageid->fetch_assoc();
// or
$row = $resultpageid->fetch_array();
if ($row) {
echo $row["pageid"];
} else {
echo "No record found!";
}

shuffle : Display only one row at the same time

How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.

MYSQL Order BY "entry" DESC Not showing the highest

i'm having a slight problem with this mysql query.
$sql = "SELECT name FROM videos ORDER BY counter DESC LIMIT 5";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$list = mysql_fetch_assoc($result);
while($list = mysql_fetch_assoc($result)){
echo $list['counter'];
echo "<br>";
}
mysql_free_result($result);
Want i'm wanting to achieve is it listing 5 entrys by order "Counter" But when listing it? it only shows 4 entrys like so :-
5648
4575
1595
35
So where is my 5th entry? and why isn't it posting it? NOTE that the 5th entry is also the highest with a value of
305355
Thanks in advance
You fetch before the loop which pops one record off the result set (i.e. 305355).
$list = mysql_fetch_assoc($result); // REMOVE THIS LINE
while($list = mysql_fetch_assoc($result)) {
// output code
}
Try to reduce the code and use mysqli_ functions
$sql = "SELECT name FROM videos ORDER BY counter DESC LIMIT 5";
$result = mysql_query($sql, $conn);
while($list = mysql_fetch_assoc($result)){
echo $list['counter']."<br>";
}
try out this code..
$sql = "SELECT name FROM videos ORDER BY counter DESC LIMIT 5";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while($list = mysql_fetch_assoc($result)){
echo $list['counter'];
echo "<br>";
}
mysql_free_result($result);
you are calling mysql_fetch_assoc two time that is why your first row get by first time you called the mysql_fetch_assoc and remaining show in second calls

Can I randomly select a row from one table and use a static identifier to select corresponding data in another table?

The following script was initially intended to select a row at random, which it could do fine, however, I an unable to figure out how to amend it to select data from a second table using a column ID called "nid" which is the same in both tables:
$conn = mysqli_connect($host,$username,$password, $database) or die(mysql_error ());
$total_rows = 5;
$selected_row = mt_rand(0, $total_rows);
$query="SELECT * FROM `node` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
$node=$row["nid"];
echo $row["title"];
$query2="SELECT * FROM `field_data_body` LIMIT $node, 1;";
$result2=$conn->query($query2);
while($row = $result->fetch_assoc()) {
echo $row["body_value"];
}
Admittedly, the above is not really close to working, but I was hardpressed to find an example of what I was after.
These tables are in the database for a Drupal site, so the title field and the body_value fields are in two different tables; ultimately, I would like to echo a result that is a matching set of title and body_value for a randomly selected node.
Speaking of this script specifically, I want to use the nid to find the corresponding row for the second table.
Is this possible?
The bit that works, selecting the data I want from a single table is in the following format:
$total_rows = 5;
$selected_row = mt_rand(0, $total_rows);
$query="SELECT * FROM `field_data_body` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["body_value"];
}
?>
UPDATE:
At the suggestion of a commenter, I used a join, and ended up with:
$conn = mysqli_connect($host,$username,$password, $database) or die(mysql_error ());
$total_rows = 5;
$selected_row = mt_rand(0, $total_rows);
//Use the result in your limit.
$query="SELECT a.nid, a.title, b.entity_id, b.body_value
FROM node a, field_data_body b
WHERE a.nid = b.entity_id LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["title"];
echo " | ";
echo $row["body_value"];
}
which worked perfectly.
for future reference since you have solved your problem, you need to close the previous connection before starting a new one, or free the results
$conn = mysqli_connect($host,$username,$password, $database) or die(mysql_error ());
$total_rows = 5;
$selected_row = mt_rand(0, $total_rows);
$query="SELECT * FROM `node` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
$node=$row["nid"];
echo $row["title"];
$result->close(); // close $result
$query2="SELECT * FROM `field_data_body` LIMIT $node, 1;";
$result2=$conn->query($query2);
while($row = $result->fetch_assoc()) {
echo $row["body_value"];
}
$result2->close(); // close $result2
i also notice you haven't closed the connection on the UPDATE you posted either which will lead you to run into the same problem again later on.
If this is just about to select a single record, you do not have to define the LIMIT, instead you can use the randomly generated value to select the row by using it in WHERE!
You can just join the two tables. Beside that, your code has a potential problem. It relies on the existence of at least 5 records. You can avoid that by putting the randomization into the query. The code will then be
$conn = mysqli_connect($host,$username,$password, $database) or die(mysql_error());
$query = "SELECT n.*, b.* FROM `node` AS n LEFT JOIN `field_data_body` AS b ON n.nid=b.nid ORDER BY REVERSE(RAND()) LIMIT 0, 1;";
$result = $conn->query($query);
$row = $result->fetch_assoc();
$result->close();
echo $row["title"];
echo $row["body_value"];
The REVERSE() function makes the result from RAND() more random. You may omit it, if you want.

php, mySQL return last x rows

I'm working on a php/mySQL/ajax shoutbox and have run into a small snag.
On the page I want the content to be loaded from oldest to newest, with the newest on the bottom. I also want to limit the output to reduce load times once the database starts to get a lot of data in it.
Here is the current code;
<?php
include_once("../includes/db.php");
include_once("../includes/functions.php");
$q="SELECT tM.*, tC.char_name as username, tC.char_id as char_id
FROM shoutbox tM JOIN characters tC
ON tC.char_id=tM.char_id
ORDER BY shout_id DESC LIMIT 25";
db_Connect();
$result=mysql_query($q);
while($row=mysql_fetch_array($result))
{
$classColor = getClassColor($row['char_id']);
echo "<span class='".$classColor."'>".$row['username']."</span>: ",nl2br($row['shout_message'])."<br />";
}
mysql_Close();
?>
I have tried using while($row=array_reverse(mysql_fetch_array($result))) as well as $result = array_reverse(mysql_query($q)) but both return an error that array_reverse needs to be fed an array.
So far anything I have found on the web from the SQL side have all been answered "just use DESC or ASC accordingly."
$res = mysql_query($q);
$shouts = array();
while($row = mysql_fetch_assoc($res))
$shouts[] = $row;
$shouts = array_reverse($shouts);
foreach($shouts as $shout) {
// show them...
}
If you want oldest to newest, and shout_id is auto increment just use
ORDER BY shout_id ASC LIMIT 25
You have DESC/ASC mixed up
$result=mysql_query($q);
unset($temp_array);
while($row = mysql_fetch_array($result))
$temp_array []= $row;
$temp_array = array_reverse($temp_array);
foreach ($temp_array as $row)
{
$classColor = getClassColor($row['char_id']);
echo "<span class='".$classColor."'>".$row['username']."</span>: ",nl2br($row['shout_message'])."<br />";
}
Seems like a lit of work. I just used this:
$result = mysql_query($strQuery) or die(mysql_error());
while ($row = array_reverse(mysql_fetch_array($result))) {
$row['something'];
}

Categories