I need to display the latest 3 articles individually from the database (title, description, content and image).
$title_query = "SELECT title, description, content, image FROM articles ORDER BY id DESC LIMIT 10";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));
while($row = mysqli_fetch_array($title_result))
{
$title = $row['title'];
$description = $row['description'];
$content = $row['content'];
$image = $row['image'];
}
echo $title;
Currently this only gets the latest one. How can I set variables for the second and third latest one? So I can have:
$title1
$title2
$title3
etc.
Thanks
the way you construct the code, it is supposed to echo out the 3rd item's tittle. so what you should do is go through loop and keep adding them to array like below:
and since you want latest 3 items, so wht not you limit it to only 3 items like below:
$title = array();
$title_query = "SELECT title, description, content, image FROM articles ORDER BY id DESC LIMIT 3";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));
while($row = mysqli_fetch_array($title_result)) {
$title[] = $row['title'];
}
print_r($title);
The request what you have made to display the latest articles individually based on the id published into the DB. You need to modify the loop what you have provide over to the question.
If you want to display multiple products outside of any looping statement you have to make it store the values in an array() and after that you can use anywhere else outside the loop.
In order to make the variable as an array you can initialize an array() either in any of the two methods as you prefer.
Method: 1 - You can initialize the array() when the query returns the TRUE value.
Method: 2 - You can initialize the array() at the top of the page too.
Initializing is based on the convenience of the developer who is developing the code.
The basic Strategy for the MYSQL Limit Statement.
MySQL: SELECT LIMIT Statement
Description: The MySQL SELECT LIMIT statement is used to retrieve records from one or more tables in MySQL and limit the number of records returned based on a limit value.
Syntax:
The syntax for the SELECT LIMIT statement in MySQL is:
SELECT expressions
FROM tables
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]]
LIMIT row_count
And hence you need to modify the query like follows so that you can display the latest three articles as per your requirement.
<?php
$title_query = "SELECT `title`, `description`, `content`, `image` FROM `articles` ORDER BY `id` DESC LIMIT 0,3";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));
$counting = $title_result->num_rows;
if($counting==0)
{
echo 'No Datas found';
}
else
{
// This part will execute if the count is greater than 0
$row=[];
while($fetch = $title_result->fetch_assoc()) {
$row[] = $fetch;
}
}
// here you can loop through to display the data.
foreach ($row as $key => $single_data) {
?>
Title: <?php echo $single_data['title']; ?>
Description: <?php echo $single_data['description']; ?>
Content: <?php echo $single_data['content']; ?>
Image: <img src="PATH to FOLDER WHERE YOU HAVE SAVED THE IMAGE ALONG WITH <?php echo $single_data['image']; ?>" />
<?php
}
?>
Related
In my DB I have some "documents" which contain more items, I'm inserting that from my dashboard.
The thing is ; when displaying, the method requires a value in my case it's $id.
Right now I am using rand() with hardcoded range to show different "documents".
This is how it looks :
<?php
$num = rand(1,10);
$post->showSmallPost($num);
?>
Let's say i want to have three of these on HTML page. But instead of this rand() I want to show the last three ID imported to table. So that is my question, how to do it?
This is a method showSmallPost():
public function showSmallPost($id){
$connection = new Db();
$conn = $connection->connect();
$image = new Image();
$imgC = $image->showSmallImg($id);
$query = $conn->prepare("SELECT * FROM post WHERE id = ?");
$query->bind_param('i', $id);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
if ($row = $result->fetch_assoc()) {
$this->id = $row['id'];
$this->title = $row['title'];
$this->description = $row['description'];
echo "<div class=\"col-md-4 text-center\" style=\"margin-top: 5px;\">";
echo <<<EOT
<a href="news.php?post=$id">
$imgC
</a>
<h4 class="news-title">$this->title</h4>
<p class="news-para">$this->description</p>
EOT;
echo "</div>";
}
}
}
And yes, this showSmallImg() is just doing his job.
You can just add Sort to the Query.
You don't need to pass a random $id to the function.
You can change the SQL statement to:
$query = $conn->prepare("SELECT * FROM post ORDER BY id DESC LIMIT 0,1");
Also you can get 3 Documents in a Single Query With,
$query = $conn->prepare("SELECT * FROM post ORDER BY id DESC LIMIT 0,3");
You can even optimize the query to run faster,
$query = $conn->prepare("SELECT id, title, description FROM post ORDER BY id DESC LIMIT 0,3");
Also, rather than using HTML inside echo, you can create a multidimensional array of your preferred structure or use the one that the sql query returns.
And make use of foreach method and only print the Values inside the array with PHP and leave HTML as it is.
It will generate more cleaner code.
For Example:
<div class=col-md-4 text-center" style="margin-top: 5px;">
<?php echo $imgC; ?>
<h4 class="news-title"><?php echo $this->title; ?></h4>
<p class="news-para"><?php echo $this->description ?></p>
</div>
You can select the last id from the database, and create a for loop decrementing it.
$query = $conn->prepare("SELECT MAX(id) AS last_id FROM post");
$query->execute();
$result = $query->get_result();
$row = $result->fetch_assoc();
$lastId = $row['last_id'];
for ($i = $lastId; $i > $lastId - 3; $i--)
{
$post->showSmallPost($i);
}
Alternatively, you can use the ORDER BY and LIMIT statements to get what you want.
$query = $conn->prepare("SELECT id FROM post ORDER BY id DESC LIMIT 3");
$query->execute();
$result = $query->get_result();
$row = $result->fetch_assoc();
while ($row = $result->fetch_assoc())
{
$post->showSmallPost($row['id']);
}
If I'm understanding it right then you want to fetch the latest n records from a table and to do that you need to have a field like createdAt. Then you can write a query which will fetch the n records and order result by this createdAt field in descending order.
Your query then will look something like this
select * from posts order by createdAt desc limit 5;
This will give you the latest 5 records inserted into the table.
I'm developing one API in php to display data on android app from my database using JSON.
In my app I want to display 20 records first, after display again 20 records once user scroll to top.
I'm requesting the last id of the record from app to show next 20 records from last id.
Here is my code
<?php
$last_movie = 0;
$genre = $_REQUEST['genre'];
$last_movie = $_REQUEST['lastid'];
require_once("connect.php");
$myArray = array();
if($last_movie == 0)
{
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year DESC LIMIT 20");
}
else
{
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year LIMIT ".$last_movie.",20");
}
if ($result) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
$result->close();
$conn->close();
?>
I'm getting values in some genres, but sometimes it show empty JSON.
I tried with this url
http://freemodedapk.com/bobmovies/by_genre.php?genre=Action
its working , whenever I try from last id
http://freemodedapk.com/bobmovies/by_genre.php?genre=Action&lastid=4714
It returns empty JSON. I have values in database.
But some genres working fine
http://freemodedapk.com/bobmovies/by_genre.php?genre=Drama
http://freemodedapk.com/bobmovies/by_genre.php?genre=Drama&lastid=865
I have total 4858 records in the database with all genres.
Anybody can help me to fix empty JSON problems in some of genres ?
Your main issue is in the wrong LIMIT usage: when you utilize 2 parameters for LIMIT keyword, the first one is for OFFSET value (not for IDs), the second one is to limit your result.
In short words: you should use LIMIT 0,20 to get the first 20 results, LIMIT 20,20 to show next 20 results and so on.
Also, your code is insecure - you have SQL injection. Try to not post direct urls on your sites with the source code which includes injection because some bad guys may drop your database or do some other harmful things.
Sample code is listed below (minor changes may be required):
<?php
require_once('connect.php');
$response = [];
$items_per_page = 20;
$page = (int) (($_REQUEST['page'] - 1) * $items_per_page);
$genre = $conn->escape_string($genre); # replace escape_string with proper method if necessary
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year DESC LIMIT $page,$items_per_page");
if ($result)
{
$response = $conn->fetch_all($result, MYSQLI_ASSOC); # replace fetch_all with proper method if necessary
}
echo json_encode($response);
$result->close();
$conn->close();
if you want to get last ID to ASC then use to
SELECT * FROM my_movies WHERE genre = '$genre' id<".$last_movie." ORDER BY year LIMIT 0,20
or if you want to get for pagination then your OFFSET value wrong,
you should be use LIMIT 0,20 to get the first 20 results, LIMIT 20,20 to next 20 , LIMIT 40,20
please check your SQL injection
look like Code
require_once('connect.php');
$result = [];
$limit = 20;
$pageNumber = (int) (($_REQUEST['pageNumber'] - 1) * $limit);
$genre = $conn->escape_string($genre);
$getDta = $conn->query("SELECT id,title,stream,trailer,directors,actors,quality,year,genre,length,translation,rating,description,poster FROM my_movies WHERE genre = '".$genre."' ORDER BY year DESC LIMIT $pageNumber,$limit");
if ($result)
$result =$conn->fetch_all($result, MYSQLI_ASSOC);
echo json_encode($result);
$result->close();
$conn->close();
I want to fetch first five rows and display same five rows at different places on single page, using single query
$cel_bir1=$db->query("SELECT * FROM tbl_birthday WHERE MONTH(Birthday_Date)=$month AND DAY(Birthday_Date)=$day LIMIT 4");
$get_bir=$cel_bir1->fetch(); $count=0;
while($get_bir1=$cel_bir1->fetch())
{
if($count++) echo ',';
echo $get_bir1['Name'];
}
So to get the first 5 rows, you can use Mysql Limit eg: Select * FROM mytable LIMIT 5.
Ok, typically what happens is, When using a PDO,your result-set is stored in an array.
$query = "Select * FROM mytable";
$statement = $db->prepare($query);
$statement->execute();
$productsinfo = $statement->fetchAll();//$productsinfo is the array in question
$statement->closeCursor();
Now to get the values in the array, you can loop through the array using a foreach loop like:
foreach($productsinfo as $productsinfomation):
$productid=$productsinfomation['productid'];
//you can echo $productid or anything you want to do with it here
endforeach;
There is no harm in repeating the foreach loop at different positions on your page.
Le'me know how it works for you.
Have fun coding.
$sql ="SELECT * FROM table_name LIMIT 0,5";
// $conn = your connection to database
$result = $conn->query($sql) or die($conn->error);
$html = '';
while($row = $result->fetch_assoc()){
$html.= $row['colum1'].'<br>'.$row['colum2'];
}
echo $html;
?>
// some more html code
<?php echo $html?>
// some more html code
<?php echo $html?>
// some more html code
<?php echo $html?>
I wanna do a dynamic gallery takin the images names and locations (folders where they are in) from a database.
Gallery would have always 15 photos (the last entrys in the db) so I need to sabe the images directory and names into variables to pass they to the HTML for the carousel.
I got a column "álbum_name" with the name of the álbum (folder where the image is in) and another called "img_name" wich gots the imagenames.jpg, so I need to add a / between they. I was thinking in something like:
$sql = "SELECT album_name, img_name FROM gallery WHERE status = 1 ORDER by date DESC LIMIT 15";
$result = mysqli_query($conn, $sql);
$photo0;
$photo1;
$photo2;
$photo3;
$photo4;
$photo5;
$photo6;
$photo7;
$photo8;
$photo9;
$photo10;
$photo11;
$photo12;
$photo13;
$photo14;
$img_num = mysqli_num_rows($result );
for ($i = 0; $i < $img_num ; $i++) {
// and here something to pass for each row álbum_name . "/" . img_name to the variables.
}
I was looking that for this things PHP man use while and fech_array or fech_row, but they doesnt do what I m tryng to...
Thanks.
You should have a look to the arrays
It is very easy to get an array of results, see this example (code not tested, but it should work):
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world"); // Create a connection
$mysqli->query("SELECT album_name, img_name FROM gallery WHERE status = 1 ORDER by date DESC LIMIT 15"); // Perform the query
$gallery = $mysqli->fetch_array(MYSQLI_ASSOC); // Get the results. MYSQLI_ASSOC is used here to return an associative array with the name of each table field
That's it! You can see what's inside your array $gallery
<?php
echo '<pre>';
var_dump($gallery);
echo '</pre'>;
And you can iterate it without using any counter with a foreach! :D
<?php
foreach ($gallery as $image) {
echo '<p>Album name:'.$image['album_name'].'</p>';
echo '<img src="/images/'.img_name.'/>"';
}
$sql = "SELECT CONCAT(album_name, '/', img_name) FROM gallery WHERE status = 1 ORDER by date DESC LIMIT 15";
I am trying to dsiplay data from 2 different tables from my mysql database using a while loop.
Currently I can display the data from 1 table and limit the results to 3. I then want to display the first 5 records from another table. If I join the tables I can only display the same number of items from both using LIMIT?
I am using a while loop to display the content from a table called item, using the following code;
$query");
$result2 = #mysql_query($query, $connection)
or die ("Unable to perform query$query");
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['item'] ?>
<?php
}
?>
If I start another loop for the data from the next table called movie, however the data is not displayed using the following code;
<?php
while($row= mysql_fetch_array($result2))
{
?>
<?php echo $row['title'] ?>
<?php
}
?>
What is the best way to display the data from the 2 tables?
Many Thanks
I don't know if you forgot to paste a bit of code, but this should work:
<?php
$query = "select * from item order by date, time asc limit 0,3";
$result = mysql_query($query);
while($row= mysql_fetch_array($result))
{
echo $row['item'];
}
$query2 = "select * from movie limit 0,5";
$result2 = mysql_query($query2);
while($row= mysql_fetch_array($result2))
{
echo $row['movie'];
}
?>
You may be able to do it with one SQL Query too:
SELECT i.item, m.movie
FROM (SELECT * FROM item ORDER BY date, time ASC LIMIT 0,3) i,
(SELECT * FROM movie limit 0,5) m
Then in php:
<?php
while($row= mysql_fetch_array($result))
{
echo $row['item'];
echo $row['movie'];
}
?>
But that depends on how you want to format the output.