How to assign php while loop into smarty to get required result - php

i want to show featured ads in slider problem is there is two table have to use to get ads. First one is class_ads that have all info of ad like title, description, price etc and second table is class_ads_pictures from where i have to match id of each ad and get the name of folder and picture name from table ....
Please review my poor logic and teach me
<?php
require_once "include/include.php";
global $db;
global $lng;
$smarty = new Smarty;
$smarty = common($smarty);
$featured_ads = mysql_query("SELECT * FROM class_ads where active=1 and featured=1 limit 50");
while ($tmp = mysql_fetch_array($featured_ads)) {
$ad_id = $temp['id'];
$ad_title = $temp['title'];
//check for image if featured ad have image (Need to fetch only single image)
$featured_ads_images = mysql_query("select from class_ads_pictures where ad_id=$ad_id order by order_no");
$img = mysql_fetch_array($featured_ads_images);
$img_id = $img['id'];
$ad_img = $img['picture'];
$img_folder = $img['folder'];
// Problem is how to assign and what have to assign, to get display in html file ...
}
$smarty->assign('what', $what);
$db->close();
if($db->error!='') { $db_error = $db->getError(); $smarty->assign('db_error',$db_error); }
$smarty->display('header_featured.html');
close();
?>

Below code should work. However you should not use mysql but PDO or mysqli because mysql is deprecated.
<?php
require_once "include/include.php";
global $db;
global $lng;
$smarty = new Smarty;
$smarty = common($smarty);
$ads = array();
$featured_ads = mysql_query("SELECT * FROM class_ads where active=1 and featured=1 limit 50");
while ($temp = mysql_fetch_assoc($featured_ads)) {
$record = array();
$record['ad_id'] = $temp['id'];
$record['ad_title'] = $temp['title'];
//check for image if featured ad have image (Need to fetch only single image)
$featured_ads_images = mysql_query("select * from class_ads_pictures where ad_id={$record['ad_id']} order by order_no");
$img = mysql_fetch_assoc($featured_ads_images);
$record['img_id'] = $img['id'];
$record['ad_img'] = $img['picture'];
$record['img_folder'] = $img['folder'];
$ads[] = $record;
}
$smarty->assign('ads', $ads);
$db->close();
if($db->error!='') { $db_error = $db->getError(); $smarty->assign('db_error',$db_error); }
$smarty->display('header_featured.html');
close();
?>
In Smarty you can simple use it:
{foreach item=item from=$ads}
{$item.ad_id}
{$item.ad_title}
{$item.img_id}
{$item.ad_img}
{$item.img_folder}
{/foreach}

Related

php function to create array with all categories and subcategories ides

i wrote a function to create an array with category_id and all subcategories ides, the main category should be selected from the page url example pages.php?category_id = 1,
then the array should be like 1,23,25
"25 is a subcategory for parent 23 and 23 is a subcategory for 1",
i'll use this later to show items with item_cat exist in array example
SELECT * FROM items WHERE item_cat IN (1,23,25)
the problem is my function is echo in the page, and i'm not sure i wrote it in a correct way here is my function code
$category_id=$_REQUEST['category_id'];
function categoriesIdes($parentId, $connection) {
global $category_id;
$sqlCategories = "SELECT * FROM categories
WHERE category_parent = ".$parentId." ";
$rsCategories = mysql_query($sqlCategories, $connection);
$totalCategoriesRows = mysql_num_rows($rsCategories);
while($rowsCategories = mysql_fetch_assoc($rsCategories)) {
$catId = $rowsCategories['category_id'];
echo ''.$catId.',' ;
categoriesIdes($catId, $connection);
}
}
$ides = categoriesIdes($category_id, $connection);
$idesall = ''.$category_id.','.$ides.'';
$idesall = substr($idesall,0,-1);
Possibly try this:
<?php
$category_id=$_REQUEST['category_id'];
function categoriesIdes($parentId, $connection) {
//not sure why you're using this
global $category_id;
//select all the childeren
$sqlCategories = "SELECT * FROM categories
WHERE category_parent = ".$parentId." ";
//query
$rsCategories = mysql_query($sqlCategories, $connection);
$totalCategoriesRows = mysql_num_rows($rsCategories);
//will hold categoryIDs found
$categoryIDs = array();
//for every child
while($rowsCategories = mysql_fetch_assoc($rsCategories)) {
//child id
$catID = $rowsCategories['category_id'];
//add to array
$categoryIDs[] = $catID;
//debug
echo ''.$catID.',' ;
//find and add the childeren
$categoryIDs = array_merge($categoryIDs, categoriesIdes($catID, $connection));
}
return $categoryIDs;
}
$ides = categoriesIdes($category_id, $connection);
$ids = '';
if (count ($ides) > 0){
$ids = $category_id .','. implode(',',$ides);
}
else{
//only 1 id
$ids = $category_id;
}
echo $ids;
?>

How to delete file from directory using class

Im trying to delete a file from folder while deleting data from database. I have used a class.
I get the following error:
Call to undefined function getCodeName()
//This function is to get the file name from the database
public static function getCodeName($product_id) {
$db = Database::getDB();
$query = "SELECT * FROM products WHERE productID = '$product_id'";
$result = $db ->query($query);
$row = $result->fetch();
$product = new Product ($row['productCode']);
return $product;
}
//Delete file from folder and other data from database
public static function deleteProduct($product_id) {
$fileName = getCodeName($product_id);
$dir = "../images/";
unlink($dir.DIRECTORY_SEPARATOR.$fileName);
$db = Database::getDB();
$query = "DELETE FROM products
WHERE productID = '$product_id'";
$row_count = $db->exec($query);
return $row_count;
}
Use php code
unlink() function set full pat for delete file

{paginate_middle} in PHP Smarty pagination not working properly

I'm using smarty pagination My pagination URL look like this
categories.php?id=1&next=3
Now {paginate_prev} & {paginate_next} is working properly
but {paginate_middle} is stripping ID parameter it is generating url like this
categories.php?next=3
My pagination code is here
function get_db_results() {
global $conn;
$id = htmlspecialchars((int)$_GET['id']);
if ($id){
$_query = sprintf('SELECT SQL_CALC_FOUND_ROWS * FROM newser where idblog = '.$conn->qstr($id).' and (main = '.$conn->qstr('0').' or main = '.$conn->qstr('2').') ORDER BY blogid DESC LIMIT %d,%d',
SmartyPaginate::getCurrentIndex(),SmartyPaginate::getLimit());
}
else
{
$_query = sprintf('SELECT SQL_CALC_FOUND_ROWS * FROM newser where (main = '.$conn->qstr('0').' or main = '.$conn->qstr('2').') ORDER BY blogid DESC LIMIT %d,%d',
SmartyPaginate::getCurrentIndex(),SmartyPaginate::getLimit());
}
$brecordSet = $conn->Execute($_query);
if(!$brecordSet)
print $conn->ErrorMsg();
else
while(!$brecordSet->EOF) {
$_data[] = $brecordSet->GetRowAssoc(false);
$brecordSet->MoveNext();
}
$_query = "SELECT FOUND_ROWS() as total";
$crecordSet = $conn->Execute($_query);
if(!$crecordSet)
print $conn->ErrorMsg();
else
$_row = $crecordSet->GetRowAssoc();
$total = $crecordSet->fields['total'];
SmartyPaginate::setTotal($total);
return #$_data;
$brecordSet->Close();
$crecordSet->Close();
}
require ('libs/SmartyPaginate.class.php');
SmartyPaginate::connect();
SmartyPaginate::setLimit(4);
SmartyPaginate::setUrl('categories.php');
$smarty->caching = $caching;
$smarty->assign('results',get_db_results());
SmartyPaginate::assign($smarty);
$id = htmlspecialchars((int)$_REQUEST['id']);
#$next = htmlspecialchars((int)$_REQUEST['next']);
$cid = $id.$next;
$smarty->display('categories.php',$cid);
Please help me understand if there is any problem with my code or it a bug with smarty {paginate_middle} which is not handeling multiple parameters
I don't use SmartyPaginate at all but it seems you should change at least this line:
SmartyPaginate::setUrl('categories.php');
into
SmartyPaginate::setUrl('categories.php?id=1');

Error with fetch() method

I am getting the error statement:
Call to a member function fetch() on a non-object in /home/content/26/11794426/html/practice/home.php on line 16
Based off this, I believe that the mysql query isn't making an object. However, I am copying my code directly from a book so I am confused why I'm getting an error. Is it the fetch() part itself or the query?
Also, the database I copied and pasted the sql query into the phpmyadmin so I don't think there is an error there, but I'm not ruling it out.
Any ideas?
<?php
require_once('database.php');
// Get category ID
if(!isset($category_id)) {
$category_id = $_GET['category_id'];
if (!isset($category_id)) {
$category_id = 1;
}
}
// Get name for current category
$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
$category = $db->query($query);
$category = $category->fetch();
$category_name = $category['categoryName'];
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$categories = $db->query($query);
// Get products for selected category
$query = "SELECT * FROM products
WHERE categoryID = $category_id
ORDER BY productID";
$products = $db->query($query);
?>
this is what my database.php file looks like:
<?php
$dsn = 'mysql:host=guitarshop27.db.11794426.hostedresource.com;dbname = guitarshop27';
$username = 'changed';
$password = 'changed';
try {
$db = new PDO($dsn, $username, $password);
}catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
$category = $db->query($query);
$categorys = $category->fetch();
$category_name = $categorys['categoryName'];
You can try it with fetch_assoc();
$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
$category = $db->query($query);
$category = $category->fetch_assoc();
$category_name = $category['categoryName'];
But the problem is the database conection. Where is it defined?
Try to debug your Code and also add this add this Code
// Get name for current category
$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
$category = $db->query($query);
echo mysql_nun_rows($category);
$categories = $category->fetch();
$category_name = $categories['categoryName'];
if you find still error then check your database connection

Calling db rows by id but backwards

I am building a Links voting site, the formula works ok after the link is voted the second time, the problem is that when the link just has 1 vote it shows up backwards, from oldest to newest.
What I want is for links with one vote to show from newest to oldest. This is the line that calls the links in the front page:
$articles = Article::getAll("order by ranking desc limit $offset, $num_items");
This is the getAll function code:
static function getAll($conditions = ' ')
{
/* Retrieve all the records from the
* database according subject to
* conditions
*/
$db = null;
$results = null;
$records = array();
$query = "select id, created, modified, username, url, title, description, points, ranking from articles $conditions";
try
{
$db = parent::getConnection();
$results = parent::execSql($query);
while($row = $results->fetch_assoc())
{
$r_id = $row['id'];
$r_created = $row['created'];
$r_modified = $row['modified'];
$r_title = $row['title'];
$r_description = $row['description'];
if(!get_magic_quotes_gpc())
{
$r_title = stripslashes($r_title);
$r_description = stripslashes($r_description);
}
$r_url = $row['url'];
$r_username = $row['username'];
$r_points = $row['points'];
$r_ranking = $row['ranking'];
$article = new Article($r_title, $r_description , $r_url, $r_username, $r_created, $r_modified);
$article->id = $r_id;
$article->points = $r_points;
$article->ranking = $r_ranking;
$records[] = $article;
}
parent::closeConnection($db);
}
catch(Exception $e)
{
throw $e;
}
return $records;
}
If anyone can help I would appreciate it.
What about adding the created date to the order clause?
$articles = Article::getAll("order by ranking desc, created desc limit $offset, $num_items");
I'll do what David says, just that if you want the links ordered by the newest first then you have to add the "created" column in descending order:
$articles = Article::getAll("order by ranking desc, created DESC limit $offset, $num_items");

Categories