How to display results from a database from newest to oldest - php

I have a page that displays entered data from a database in a table. I am wondering how I can reverse the order displayed from newest to oldest.
Here is the code for the fetch page that displays my results in the table, html has been removed as it is irrelevant to the question.
<?php
// Create connection in mysqli
$connection = new mysqli($server, $user, $pass, $dbname);
//Check connection in mysqli
if($connection->connect_error) {
die("Error on connection:" .$connection->connect_error);
}
//Display the informaion
$sql = "SELECT * FROM logs";
$res = $connection->query($sql);
if($res->num_rows > 0) {
// echo table row code
while($row = $res->fetch_assoc()) {
// echo table row code
}
}
else {
echo "No Record Found!";
}
$connection->close();
?>

Simply modify your query like this :
$sql = "SELECT * FROM logs ORDER BY `column` DESC";
Where column is your column with the primary key. Normaly it is ID or id...

Related

not able to retrieve the last inserted id from sql in html

i am trying to display some values from database to my html calling the last inserted id
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from registers where id= LAST_INSERT_ID()";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " $row[firstname] ";
}
} else {
echo "0 results";
}
But when I am using this, the result is not being displayed, is there any problem with my code, how do I retrieve the last inserted id from sql?
try this query
$sql = "SELECT * from registers ORDER BY ID DESC limit 1 ";
it will give you only one result and this result will be the last inserted ID.
But ID needs to be auto increment.
To retrieve the last id in the table you need:
SELECT id FROM registers ORDER BY ID DESC LIMIT 1

Use PHP loop to fetch tables data from the table which contain names of database tables

I have table named category which contain names of other tables in the same database. I want to fetch table names from category table and then fetch data from each table from db. So far I have this code below:
$db = new mysqli('localhost', 'root', '', 'db_cat');
if($db){
// $q = "SELECT TABLE";
// $echo = $db->query($q);
// echo $echo;
// $result = $db->query("SHOW TABLES");
$qCat="SELECT * FROM product_category";
$cat_query= $db->query($qCat) or die(mysql_error());
while ($fetch= $cat_query->fetch_object())
{
$cat_id=$fetch->id;
$category=$fetch->category;
$p_cat=str_replace(" ","_",strtolower($category).'_categories');
//if(strlen($category)>22){$fine_product_name= substr($service, 0,19).'...';}else{ $fine_product_name=$category;}
$result = $db->query("SHOW TABLES");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
}
The second query must be different.
$result = $db->query("SELECT * FROM $category");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
print_r($tables);
First of all your design to connect to a database is not that good, Please check the below code for a proper way of connecting to it.
<?php
$con=mysqli_connect("localhost","root","","db_cat");
//servername,username,password,dbname
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: ".mysqli_connect_error();
}
?>
Here is a sample code of getting data from a table ( where this table name is in another table).
$get_table_name ="SELECT TableName FROM table_name";
$get_name=mysqli_query($con,$get_table_name);
$count=0;
while($row_name=mysqli_fetch_array($get_name)){
$count++;
$tbName=$row_name['TableName'];
$_SESSION['table_name'][count]=$tbName;
}
This will show you how to fetch data from one table. You can use a For loop to get all the tables
$table=$_SESSION['table_name'][1];
$get_table ="SELECT * FROM $table";
.... // Normal way of fetching data
You can try to adjust your code according to this and improve it.
For further reference please refer http://php.net/manual/en/book.mysqli.php

Limit No. Of MYSQL Data

I'm using MySQL to show data on my website: http://www.onlinedealsindia.in. You can see the deals (deal boxes) there but I want to limit them. I want only 50 deals (deal boxes) to show up per page. Clicking the more button would show the next 50 deals.
Below is my code to get data from MySQL:
<?php
$host="localhost";
$username="username";
$password="pass";
$dbname="DB NAme";
$conn=new mysqli($host, $username, $password, $dbname);
if($conn->connect_error)
{
die("error".$conn->connect_error);
}
else { echo "";}
$sql= "SELECT * FROM table ORDER BY p_id DESC";
$results=$conn->query($sql);
if($results->num_rows > 0)
{ while($row=$results->fetch_assoc())
{ $pid=$row["p_id"];
?>
The mechanic you are looking for is called skip and take.
In mySQL you can use the LIMIT to accomplish this. With one parameter it returns that many rows. With two parameters, it will skip the first number in rows and return the number of rows for the second number.
This SQL would return 20 rows:
$sql= "SELECT * FROM table LIMIT 10 ORDER BY p_id DESC";
This SQL would return the ten rows skipping the first 10
$sql= "SELECT * FROM table LIMIT 20,10 ORDER BY p_id DESC";
Documentation and examples of LIMIT can be found here
To make this work for your website just pass a parameter that tells what page you are on and how many rows per page. You can then calculate the two numbers you need for your select statement.
$mysqli = new mysqli($host, $username, $password, $dbname);
if($mysqli->connect_error)
{
die("error".$mysqli->connect_error);
}
else {
echo "";
}
$datas = $mysqli->prepare('SELECT id FROM table LIMIT 50 ');
if($datas)
{
$datas->execute();
$datas->bind_result($id);
while($datas->fetch)
{
$store['id']= $id;
$results[] = $store;
}
return $results;
}
foreach($results as $result)
{
echo $result['id'];
}

mysqli display rows based on row value - (if row value=1 display, else hide)

I want to display 30 rows from an data base,on an TABLE, but just the approved entries.
This "approved entries" are defined for an row with values "1 for approved" and "0 for NOT approved"
This is the code wath I need to change:
<?php
$servername = "localhost";
$username = "username ";
$password = "password";
$dbname = "name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, label, title_id, season, episode, approved FROM links order by id desc LIMIT 30 OFFSET 1";
$result = $last_id = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table><tr><th>ID</th><th>Audio</th><th>URL</th><th>Temporada</th><th>Episodio</th><th>Aprobado</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["label"]."</td>";
echo "<td><a href=";
if (empty($row['episode'])) {
echo '/peliculas-online/'.$row["title_id"];
}
else {
echo '/series-online/'.$row['title_id'].'/seasons/'.$row['season'].'/episodes/'.$row["episode"];
}
echo ">".$row["title_id"]."</a></td>";
echo "<td>".$row["season"]."</td><td>".$row["episode"]."</td><td>".$row["approved"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Like you can see, this code list all (approved or not)... how to get something like this:
if row approved=1 display rows, else hide (hide all not just the approved row)
Need to HIDE all entries from this table row if entry is not approved -> id-label-title_id-season-episode-approved
Thanks
You should know about the MySQL WHERE clause in SELECT.
Something like:
"SELECT id, label, title_id, season, episode, approved
FROM links
WHERE approved = 1
ORDER BY id desc
LIMIT 30 OFFSET 1";
Reference:
https://dev.mysql.com/doc/refman/5.0/en/select.html

returing one value from the database using php

How do I fetch only one value from a database using PHP?
I tried searching almost everywhere but don't seem to find solution for these
e.g., for what I am trying to do is
"SELECT name FROM TABLE
WHERE UNIQUE_ID=Some unique ID"
how about following php code:
$strSQL = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = mysql_query($strSQL) or die('SQL Error :: '.mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['name'];
I hope it give ur desired name.
Steps:
1.) Prepare SQL Statement.
2.) Query db and store the resultset in a variable
3.) fetch the first row of resultset in next variable
4.) print the desire column
Here's the basic idea from start to finish:
<?php
$db = mysql_connect("mysql.mysite.com", "username", "password");
mysql_select_db("database", $db);
$result = mysql_query("SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID");
$data = mysql_fetch_row($result);
echo $data["name"];
?>
You can fetch one value from the table using this query :
"SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID limit 1"
Notice the use of limit 1 in the query. I hope it helps!!
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();

Categories