Query dont want to show all related post from table - php

I try to retrive all rows related to the specific category(continent table) but it only shows one and not all.
<?php
$townid = $_GET['id'];
$query = "SELECT * FROM towns INNER JOIN continents ON towns.catid = continents.id WHERE continents.id = '$townid'";
$row = mysqli_fetch_assoc(mysqli_query($link, $query));
// The category/Continent
echo '<h1>';
echo $row['catname'];
echo '</h1>';
//The post name/Town name
echo $row['title'];
?>

You need to call mysqli_fetch_assoc() in a loop.
$result = mysqli_query($link, $query);
$first = true;
while ($row = mysqli_fetch_assoc($result)) {
if ($first) { // Only show the category header once.
// The category/Continent
echo '<h1>';
echo $row['catname'];
echo '</h1>';
$first = false;
}
//The post name/Town name
echo $row['title'];
}

You can do something like:
<?php
$townid = $_GET['id'];
$query = "SELECT * FROM towns INNER JOIN continents ON towns.catid = continents.id WHERE continents.id = '$townid'";
$rows = mysqli_fetch_all(mysqli_query($link, $query), MYSQLI_ASSOC);
// The category/Continent
foreach ($rows as $row) {
echo '<h1>';
echo $row['catname'];
echo '</h1>';
//The post name/Town name
echo $row['title'];
}
?>
On another note, its better to parameterised your query since you are getting the $townid from a GET params.
This is how to do it in PHP https://www.php.net/manual/en/mysqli-stmt.bind-param.php

Related

paginate the list in php

i have this php code that fetches images from the database using the userid, then displays all the images in a list form. im trying to paginate the images, in a limit of 5 items per page. but the code is showing only the first page, without a link to the other pages. here's my php code
<?php
include 'connect.php';
$Category = " ";
$query = "SELECT Img_dir, Caption, Category FROM images WHERE Category = '". $_REQUEST['Category'] ."' AND user_id = '". $_SESSION['user_id'] ."' LIMIT 0,5";
$result = mysqli_query($conn,$query);
while ($row=mysqli_fetch_array($result)){
$image = $row["Img_dir"];
$Caption= $row["Caption"];
$Category = $row["Category"];
echo "<dl>";
echo "<dd>$Category &nbsp&nbsp <img src='base64_encode($image)' />&nbsp&nbsp $Caption<dd>";
echo "</dl>";
}
//number of total pages available
$results_per_page = 10;
$number_of_results = mysqli_num_rows($result);
echo $number_of_pages = ceil($number_of_results / $results_per_page);
echo "<br>"; echo "<br>";
for($r=1;$r<=$number_of_pages;$r++)
{
?><?php echo $r." "; ?><?php
}
?>
You can try this:
Change your query (use prepare statments):
$query = "SELECT Img_dir, Category FROM images WHERE user_id = ? AND Category = ? ";
As for the structure of your data.
$results = [];
while ($row = $result->fetch_assoc()){
$key = $row['Category'];
if(!isset($results[$key])) $results[$key] = [];
$results[$key][] = $row['Img_dir ']; //['Category' => [Img_dir,Img_dir, ...]]
}
And your HTML. I would use a description list or dl as it has a nice place for the title:
foreach($results as $Category => $image){
echo "<dl>";
echo "<dt>$Category</dt>";
foreach($data as $row){
echo "<dd><img src='base64_encode($image)' /><dd>";
}
echo "</dl>";
}
Untested.
The order will probably be all wanky, so you can use ksort on it. Simply
ksort($results);
Before the foreach loops.
Cheers.

Search multiple row separate by comma from mysql using php

It is a tracking system like DHL. Tracking shipment number from MySQL database using php form.
but I need it Search multiple row separate by comma from mysql using php.
<?php
$ship=$_POST['Consignment'];
$cons = explode(',',$ship);
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no = '$cons[]'";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Shipment Name: <?php echo $ship_name; ?>
Shipment Phone: <?php echo $phone; ?>
<?php }//while
}//if
else {
echo 'In else....';
?>
Consignment Number not found.Search Again.
<?php
}//else
?>
So I need my search will work with separating by comma(,).
Thanks for helping me.
You can use IN operator in that case.
<?php
$ship=$_POST['Consignment'];
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Hope it will help to you.
change your sql query you have written '$cons[]' in select query which is wrong . after explode you will get data as 1,2,3 so you just need to write variable in query not array and user IN Operator like this.
`$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";`
You should always prepare/sanitize the POST data before using it in MySql query (in terms of security):
<?php
if (isset[$_POST['Consignment']] && !empty($_POST['Consignment'])) {
$ship = $_POST['Consignment'];
$cons = explode(',', $ship);
$cons = array_filter($cons, function($v){
return trim(strip_tags($v));
});
$cons = '"' . implode('","', $cons) . '"';
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN ($cons)";
$result = dbQuery($sql);
$no = dbNumRows($result);
if ($no == 1) {
while ($data = dbFetchAssoc($result)) {
extract($data);
....
}
....
}
?>
Please Use Find IN SET
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'1,2,3,4,5')
Updated
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'$ship')
Note :- $ship Comma Separated Value not an array
I found the Answer:
if(isset($_POST['Consignment'])){
$ship=$_POST['Consignment'];
$shipment= explode(',',$_POST['Consignment']);
$ship = implode("', '",$shipment) ;
$query = "SELECT * FROM `tbl_courier` WHERE `cons_no` IN('$ship')";
$results = $mysqli->query($query);
if($results){
print '<table border="1">';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["cons_no"].'</td>';
print '<td>'.$row["customerName"].'</td>';
print '<td>'.$row["customerPhone"].'</td>';
print '</tr>';
}
print '</table>';
// Frees the memory associated with a result
$results->free();
}
else {
echo "Query Not Match";
}
$mysqli->close();
}
Thanks to Answer.

How to fetch recent 3 post from a blog table: magento

I have a table in database as "neotheme_blog_post" and there are many post in there, now i want to fetch recent 3 posts from this table and show them on home page: I have tried to fetch the data as follows but nothing worked:
<?php $connection =
Mage::getSingleton('core/resource')->getConnection('core_read');
$query = "Select * FROM 'neotheme_blog_post'";
$rows = $connection->fetchAll($query);
foreach ($rows as $values) {
echo $name = $values['name'];
}?>
You may use LIMIT over here.
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$query = "Select * FROM neotheme_blog_post LIMIT 3";
$rows = $connection->fetchAll($query);
foreach ($rows as $values){
echo $name = $values['name'];
}
In my case i get the three recent posts as like follows using neotheme blog extension:
$connection =
Mage::getSingleton('core/resource')->getConnection('core_read');
$query = "Select * FROM neotheme_blog_post ORDER BY created_at DESC LIMIT 3 ";
$rows = $connection->fetchAll($query);
foreach ($rows as $values) {
$post_titile = $values['cms_identifier'];
echo '<div>';
echo '<h1>' . $name = $values['title'] . '</h1>';
echo $summery = $values['summary'];
echo 'Read More';
echo '</div>';

How do you display a "No Results Found" message (PHP)

Just wondering how I can display this message when I type something in my search bar, and nothing matches what is stored in my MySQL database.
So far what I have is this.
<?php
if(isset($_POST['submit'])){
$search = trim($_POST['search']);
if($search != ""){
//echo "search: ". $search;
$result = mysql_query("SELECT * FROM catalogue WHERE
name LIKE '$name' OR
category LIKE '$category' OR
brand LIKE '$brand' OR
season LIKE '$season' OR
price LIKE '$price' OR
store LIKE '$store' OR
description LIKE '%$search%' ");
while($row = mysql_fetch_array($result)){
$name = $row['name'];
$file = $row['file'];
$description = $row['description'];
$category = $row['category'];
$brand = $row['brand'];
$season = $row['season'];
$price = $row['price'];
$store = $row['store'];
$cid = $row['cid'];
echo "\n<div class=\"thumb\">";
echo "\n\t<img src=\"thumbs/$file\" class=\"thumbnailImg\" width=\"150\" height=\"200\"/><br/>";
echo "\n\t".$name. " ";
echo "\n\t$". $price;
echo "\n</div>";
}//end while loop
}else{
echo "<h2><em>No results were found.</em></h2>";
}//end if search ,else
}//end if submit
?>
This code snippet works if I just click search without typing anything in, but if I type something in the search that doesn't match up, nothing is displayed. How do I fix that?
Set a flag counter and you will get it working.
$results=0; // Setting a flag here
while($row = mysql_fetch_array($result)){
$name = $row['name'];
$file = $row['file'];
$description = $row['description'];
$category = $row['category'];
$brand = $row['brand'];
$season = $row['season'];
$price = $row['price'];
$store = $row['store'];
$cid = $row['cid'];
echo "\n<div class=\"thumb\">";
echo "\n\t<img src=\"thumbs/$file\" class=\"thumbnailImg\" width=\"150\" height=\"200\"/><br/>";
echo "\n\t".$name. " ";
echo "\n\t$". $price;
echo "\n</div>";
$results++; //Incrementing flag if results found.
}//end while loop
}
else if($results==0)
{
echo "<h2><em>No results were found.</em></h2>";
}
else{
echo "<h2><em>No results were found.</em></h2>";
}//end if search ,else
Set a variable to 0 before the while() loop. Set it to 1 inside the loop. Print some text if it's still 0 after the loop. Like this:
$found=0;
while($row = mysql_fetch_array($result)){
$found=1;
...
}//end while loop
if ($found==0) {
echo "no results found";
}
You need to see if any rows were returned. According to the php.net manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement or mysql_affected_rows() to find out how many rows
were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.
Something like this would help in your code:
...
$result = mysql_query("SELECT * FROM catalogue WHERE
name LIKE '$name' OR
category LIKE '$category' OR
brand LIKE '$brand' OR
season LIKE '$season' OR
price LIKE '$price' OR
store LIKE '$store' OR
description LIKE '%$search%' ");
if (mysql_num_rows($result) == 0 ) {
// display no results found
} else {
while($row = mysql_fetch_array($result)){
$name = $row['name'];
$file = $row['file'];
$description = $row['description'];
$category = $row['category'];
$brand = $row['brand'];
$season = $row['season'];
$price = $row['price'];
$store = $row['store'];
$cid = $row['cid'];
echo "\n<div class=\"thumb\">";
echo "\n\t<img src=\"thumbs/$file\" class=\"thumbnailImg\" width=\"150\" height=\"200\"/><br/>";
echo "\n\t".$name. " ";
echo "\n\t$". $price;
echo "\n</div>";
$results++; //Incrementing flag if results found.
}//end while loop
}
}
...
}
Easy. Just take those echo statements & place them in a variable. If the variable is not empty, echo it. If the statement is empty, echo your “No results were found.” message. Adjusted code below:
if(isset($_POST['submit'])){
$ret = '';
$search = trim($_POST['search']);
if($search != ""){
//echo "search: ". $search;
$result = mysql_query("SELECT * FROM catalogue WHERE
name LIKE '$name' OR
category LIKE '$category' OR
brand LIKE '$brand' OR
season LIKE '$season' OR
price LIKE '$price' OR
store LIKE '$store' OR
description LIKE '%$search%' ");
while($row = mysql_fetch_array($result)){
$name = $row['name'];
$file = $row['file'];
$description = $row['description'];
$category = $row['category'];
$brand = $row['brand'];
$season = $row['season'];
$price = $row['price'];
$store = $row['store'];
$cid = $row['cid'];
$ret = "\n<div class=\"thumb\">"
. "\n\t<img src=\"thumbs/$file\" class=\"thumbnailImg\" width=\"150\" height=\"200\"/><br/>"
. "\n\t".$name. " "
. "\n\t$". $price
. "\n</div>"
;
}//end while loop
}
// Check if '$ret' has content or not.
if (!empty($ret)) {
echo $ret;
}
else {
echo "<h2><em>No results were found.</em></h2>";
}
}//end if submit

mysqli_fetch_array reading result as null?

Any idea why this is showing a result of null? I'm guessing it has to do with where I put $link before I did the query, but it has to be done that way, correct?
function getcatposts($cat_id) {
$qc = #mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
}
$qc2 = #mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
}
Updated code:
function getcatposts($cat_id) {
$link = mysqli_connect("localhost", "lunar_lunar", "", "lunar_users");
$qc = mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
}
echo $cat_name;
echo '<br />';
echo $topic_title;
echo '<br />';
echo $topic_id;
}
New issue is that its displaying like this:
http://gyazo.com/43e8a91b9e0cf4f5e413536907891dcf.png
When the DB looks like this:
http://gyazo.com/1ead8bd0f150838dae3ee4a476419679.png
It should be displaying all three of them and this is a function meaning it will keep redoing all the code until it can't query anymore data. Any ideas?
The problem here is that you're trying to echo the values outside your loop. The variables inside the loop will get overwritten on each iteration and at the end of looping, the variable will hold the value of the last iteration.
If you want to display all the values, move the echo statement inside your loop, like so:
while($row = mysqli_fetch_array($qc))
{
$topic_title = $row['topic_subject'];
$topic_id = $row['topic_id'];
echo $topic_title.'<br/>';
echo $topic_id.'<br/>';
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2))
{
$cat_name = $row2['cat_name'];
echo $cat_name.'<br/>';
}
If you care about the order, you could store the titles, ids and cat_names in arrays like so:
while($row = mysqli_fetch_array($qc))
{
$topic_title[] =$row['topic_subject'];
$topic_id[] = $row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2))
{
$cat_name[] =$row2['cat_name'];
}
And then loop through them:
for ($i=0; $i < count($topic_id); $i++) {
if( isset($topic_id[$i], $topic_title[$i], $cat_name[$i]) )
{
echo $cat_name[$i].'<br/>';
echo $topic_title[$i].'<br/>';
echo $topic_id[$i].'<br/>';
}
}
Your function displays only one result because your echo is outside the while loop...
Put the Echo statements inside the loop, or you will print only the last result!
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
echo $topic_title;
echo '<br />';
echo $topic_id;
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
echo $cat_name;
echo '<br />';
}

Categories