populate feed even if no images in PHP - php

I need to populate an ecommerce feed with extraimages
here is the header :
|image_1|image_2|image_3|
I've a table where I store or not, extra images for one product.
So I make a request to see if there are some extra images, with an sql limit of 3 as I only want 3 images max in my feed.
What I need is to populate the feed with empty pipes if there are no images and I don't know the logic to do that.
The output would be, for example, like this if I have 2 extra images :
|url/image_1.jpg|url/image_2.jpg|| <- empty pipe to match the header of 3
or only one image :
|url/image_1.jpg|||
My code so far :
$products_extra_images_query = tep_db_query(
"SELECT products_extra_image, products_extra_images_id
FROM " . TABLE_PRODUCTS_EXTRA_IMAGES .
" WHERE products_id='" . (int)$row->id . "' LIMIT 3");
if (tep_db_num_rows($products_extra_images_query) >= 1){
// there are some extra_images
while ($extra_images = tep_db_fetch_array($products_extra_images_query)) {
$output .= $extra_images['products_extra_image']."|" ;
}
}
thanks for your help.
Sebastien

Create an array of 4 and put your image path into it, then implode it into a string separated by "|".
$images = array_fill(0,4,null);
$idx = 0;
if (tep_db_num_rows($products_extra_images_query) >= 1) {
// there are some extra_images
while ($extra_images = tep_db_fetch_array($products_extra_images_query)) {
$images[$idx] = $extra_images['products_extra_image'];
$idx++;
}
}
$output .= implode($images, '|');

If I understood correctly then you could try an approach like this ~ though using non-standard names such as tep_db_fetch_array perhaps confuse the issue?
$rows = tep_db_num_rows( $products_extra_images_query );
if ( $rows > 0 ){
$output=[];
/* add found records to the `output` array rather than a string - or, use `fetch_all` */
while( $extra_images = tep_db_fetch_array($products_extra_images_query)) {
$output[]=$extra_images['products_extra_image'];
}
/* an odd looking loop but should add extra `pipe` chars when there are not 3 results */
for( $i=0; $i < ( 3 - $rows ); $i++ )$output[]='';
echo '|' . implode('|',$output) . '|';
}

Related

how to use more than one variable in a group array?

I currently have the following code, it works great, but I've never tried to do anything more complex with this sort of thing. I'm wondering how I can add more variables to my result output.
$check_alt_sizes = mysqli_query($link, "SELECT model, version, size, category FROM items WHERE model = '$model' AND size != '$category' AND id != '$item_id'");
if (mysqli_num_rows($check_alt_sizes) >= 1) {
$group = array();
while ($row = mysqli_fetch_assoc($check_alt_sizes)) {
$group[ $row['category'] ][] = $row;
}
then later
foreach ($group as $sizes => $alt_size_urls) {
foreach ($alt_size_urls as $alt__size_url) {
echo "<a href='/items/"; echo "$alt_size_url[slug]"; // slug set elsewhere
echo "'>";
echo "$sizes</a>";
}
}
}
Now the $sizes part displays a list of sizes that I have gotten from grabbing $row['category'] in the initial $group from the query. What I would like to know is, how can I add more variables to this group, I've only ever dealt with doing it this way, never expanding it.
Currently it displays
Alternate Sizes:
size1
size2
but I would like to be able to add version as well, such as
Alternate Sizes:
Version1 - size1
Version2 - size1
Version3 - size2
I tried doing this:
echo $row['version']; echo "$sizes</a></p></li>";
But that just uses the first version found and applies it to every item. obviously because $sizes is looping and the version echo is not. How do I go about doing this?
I modified your source code with this one:
$group_size = "";
foreach ($group as $sizes => $alt_size_urls) {
$group_size .= "Alternate Sizes: <br>";
$ctr = 0;
foreach ($alt_size_urls as $alt__size_url) {
$group_size .= "<a href='/items/' " . $alt_size_url[slug] . (++$ctr) . "'>" . $sizes . "</a><br>";
}
}
echo $group_size;

how to insert multiple php array values into mysql for the same table?

Hi I am very new to php and I am having 3 php arrays namely bookname, bookprice and bookisbn, I need to insert the values like
"bookisbn" "bookname" "bookprice" into mysql
eg:
isbn1 bookname1 bookprice1
isbn2 bookname2 bookprice2
isbn3 bookname3 bookprice3
As of now I tried to iterate the three arrays something like,
foreach($booknamearray as $bookname && $bookpricearray as $bookprice && $bookisbnarray as $bookisbn) { .. }
and
while($booknamearray as $bookname && $bookpricearray as $bookprice && $bookisbnarray as $bookisbn){ .. }
Nothing worked me, please kindly help me out to achieve this.
Thanks in advance,
Naveen.
Assuming they all have the same number of elements, you can use a for loop, and make a string of all the values:
for($i = 0; $i < count($booknamearray); $i++) {
$str = $booknamearray[$i] . " " . $bookpricearray[$i] . " " . $bookisbnarray[$i];
//Insert $str into db
}
While you don't say so explicitly, I'm guessing your 3 arrays have their various values in the SAME KEY, e.g.
$booknamearray[0] -> 'name1';
$bookisbnarray[0] -> 'isbn1';
$bookpricearray[0] -> 'price1';
In which case you can do
foreach($booknamearray as $key => $name) {
$isbn = $bookisbnarray[$key];
$price = $bookpricearray[$key];
etc...
}

Displaying tagged images across multiple pages fails

I feel this is a more logic problem than anything. A database has pictures saved via a source reference and booleans for tags e.g. isLandscape=1. I had made a system to traverse pages of results based on types asked. The following is an example of what I'm facing. I only see the same 12 pictures from page 0 -> page 22. Then I start to see new ones. I think I have just been overlooking this bug since I had not noticed it until now. One thing I noticed was page22*12pictures = 264 which is the same as the first new picture id that is seen. You can see the error here (just change the p to different pages).
<?php
$pictureid = -1;
$startpage = 0;
$viewsection = -1;
$uid = -1; //user id
$amntperrow = 4; //how many pictures per row, must correlate with doThumb()'s switch case amounts
$maxrows = 3; //how many rows of pictures to drop
if(isset($_GET['pid']) && is_int(intval($_GET['pid']))) $pictureid = clean($_GET['pid']);
if(isset($_GET['sec']) && is_int(intval($_GET['sec']))) $viewsection = clean($_GET['sec']);
if(isset($_GET['p']) && is_int(intval($_GET['p']))) $startpage = clean($_GET['p']);
$result = generateResult(array("isFlowers"), $startpage);
//**snip** -- drawing thumbnails would happen here
function generateResult($types, $page) {
global $amntperrow;
global $maxrows;
$sqlWheres = "";
$idAmnt = ($amntperrow*$maxrows)*$page;
if(isset($types) && !empty($types)) {
if(count($types) >= 1) {
for($i = 0; $i<count($types); $i++) {
$sqlWheres .= $types[$i] . "='1'";
if($i < count($types)-1) $sqlWheres .= " AND ";
}
}
}
$result = "SELECT * FROM pictures WHERE ";
if(!empty($sqlWheres)) $result .= $sqlWheres . " AND " ;
$result .= " private='0' AND id >='" . $idAmnt . "' LIMIT " . ($amntperrow*$maxrows);
return $result;
}
?>
This seems like a glaring bug that I am overlooking. Thanks for the help.
What is the difference between these two queries?
SELECT *
FROM pictures
WHERE private = '0' AND id >= '24'
LIMIT 12;
and
SELECT *
FROM pictures
WHERE private = '0' AND id >= '36'
LIMIT 12;
Answer: potentially no difference at all. The database engine can decide in either case that it wants to return pictures with ids 100 through 111 - that result set meets all of the conditions of either query.
Try a query like this instead:
"SELECT *
FROM pictures
WHERE private = '0'
ORDER BY id
LIMIT " . $idAmnt . ", " . ($amntperrow * $maxrows)
The ORDER BY id is really the key. Paging through database results is generally done with a combination of ORDER BY and LIMIT.

Simple PHP Array Issue with Key Comparison

I've been pulling my hair out on this one all afternoon. Basically, I have a long table of values (stored in SQL) and I want to go through the entire table and count the number of times each value shows up. I've called the values "pid" integers.
The best way I thought of to do this was to create an array with the PIDs as the key of the array, and the number of times each PID has occured in the table as the value at that key. Then go through the entire list and either add the PID to the array if it didn't already exist, or increment the click value if it already exists. The goal is to then figure out which PID has the highest number of clicks.
It sounds straightforward, and it is! I think I must have an error in my syntax somewhere because everything seems right. This is my first time working with arrays in PHP so be nice :)
Thanks so much!
$tabulation = array();
while ($row = mysql_fetch_array($result)) {
$pid = $row[1];
//if this post isn't in the tabulation array, add it w a click value of 1
if ( !isset( $tabulation[$pid] ) ){ array_push( $tabulation[$pid], 1 ); }
//if this post is already in the tabulation array, incrment its click value by 1
else {
$t = $tabulation[$pid]; $t++; $tabulation[$pid] = $t;
}
}
$highestClicksValue = -1;
$highestClicksPID = -1;
foreach ($tabulation as $pid => $clicks){
if ($clicks > $highestClicksValue){ $highestClicksPID = $pid; }
printf("PID: ". $tabulation[$pid] . " clicks: " . $tabulation[$clicks] . "<br />");
}
I know you're looking for a PHP answer, but have you considered that this is what SQL is best at?
select pid,count(*)
from theTable
group by pid
order by count(*) desc
Just a thought...
Why are you using the array key and value as keys for $tabulation in the last foreach?
This should work...
$tabulation = array();
while ($row = mysql_fetch_array($result)) {
$pid = $row[1];
//if this post isn't in the tabulation array, add it w a click value of 1
if ( ! isset( $tabulation[$pid] ))
$tabulation[$pid] = 1;
//if this post is already in the tabulation array, incrment its click value by 1
else
$tabulation[$pid]++;
}
arsort($tabulation);
$highestClicksValue = reset($tabulation);
$highestClicksPID = key($tabulation);
foreach ($tabulation as $pid => $clicks){
print("PID: ". $pid . " clicks: " . $clicks . "<br />");
}

PHP Order in alphabetical order

I'm trying to make a simple alphabetical list to order items in my database. The thing I can't figure out is how to actually list it.
I would like it to be the same format as you have on miniclip.com
Here's an image
I looked around, but couldnt find an answer really.
(I would like it to finish even at the end of each vertical column, except the last one for sure)
Any help would be welcome!
In MySQL:
SELECT * FROM table ORDER BY name ASC
In PHP:
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
Assuming that your result set already is sorted by using the ORDER BY clause, to group the results by their first character you just need to remember the first character of the previous entry and print out the first character of the current entry if they are different. So:
$prevLabel = null;
while ($row = mysql_fetch_assoc($result)) {
$currLabel = strtoupper(substr($row['name'], 0, 1));
if ($currLabel !== $prevLabel) {
echo $currLabel;
$prevLabel = $currLabel;
}
echo $row['name'];
}
This will print the first character as a label for each group that’s members have the same first character.
He doesn't seem to have an issue with the storting, but doing the column format and headers for each new letter.
Suppose $arr contains your alphabetically sorted list with numeric keys. each element has indexes 'name' and 'link'. This should be pretty safe assumption for data from a SQL query.
$firstLetter = -1;
$desiredColumns = 4; //you can change this!
$columnCount = (count($arr)+27)/$desiredColumns+1;
echo "<table><tr><td>";
foreach($arr as $key => $cur)
{
if ($key != 0 && $key % desiredColumns == 0) echo "</td><td>";
if ($cur['name'][0] !== $firstLetter)
{
echo "<strong>$firstLetter</strong> <br />"; $firstLetter = $cur['name'][0];
}
echo "".$cur['name']."<br />";
}
echo "</td><tr></table>";
You'll have to treat numbers as a special case, but this is the idea. If you are using a template engine there are obviously better ways of doing this, but I figure you would have mentioned that. This is a rough sketch, making pretty HTML isn't my thing.
--Query-- get table into $arr. I can't see your tables obviously, Im making assumptions if names nad stuff so you'll need to verify or change them
$sql = "SELECT * FROM table T ORDER BY name";
$conn = //you should have this
$res = mysql_query($sql, $conn);
$arr = array();
while($row = mysql_fetch_assc($res)
$arr[] = $row;
// start above code here. This isn't safe for empty query responses or other error but it works
I presume you're using MySQL (or another SQL) database, in which case you should simply retrieve the data in the required order using a SORT BY clause on the lookup SELECT. (Sorting this PHP is trivial via the sort function, but it makes sense to get the database to do this - that's pretty much what it's for.)
In terms of balancing the output of each of the columns, you could get a COUNT of the required rows in your database (or simply use the count of the resulting PHP array of data) and use this to ensure that the output is balanced.
As a final thought, if this is going to be output on a per-page basis, I'd highly recommend generating it into a static file when the structure changes and simply including this static file as a part of the output - generating this on the fly is needlessly resource inefficient.
The mysql option mentioned above is definitely the best bet. If the data comes out of the DM in order, that's the simplest way to go.
Your next option might be to look at the
asort and ksort functions in PHP to find the exact one you're looking for.
http://www.php.net/manual/en/array.sorting.php
How are you pulling the data?
<?php
$result = mysql_query("SELECT titles FROM gamelist ORDER BY title ASC");
while ($row = mysql_fetch_assoc($result)) {
echo "{$result['title']}<br/>";
}
?>
There are two ways to do it.
You could use your database and use the 'order' clause to pull them by a specific field alphabetically.
You could also use either a key sort or value sort on a PHP array.
The PHP functions are sort($array) and ksort($array).
http://php.net/manual/en/function.sort.php
http://php.net/manual/en/function.ksort.php
<?php
$list = $your_list_array_from_database
//if you need info on how to do this, just let me know
sort($list);
foreach($list as $item) {
echo $item;
}
?>
I found this post and had the same problem. I used the code below to output a list by category name with a header equal to the first letter. In my database table (category) I have name and category_letter. So, name = football and category_list = 'F'.
<section>
<?php
try {
$cats_sql = $dbo->prepare("SELECT name, category_list, FROM category WHERE category_list REGEXP '^[A-Z#]' GROUP BY category_list ASC");
$cats_sql->execute();
$results_cats = $cats_sql->fetchAll();
} catch(PDOException $e) {
include('basehttp/error');
}
$array_cats = $results_cats;
if(is_array($array_cats)) {
foreach($array_cats as $row_cats) {
$cat_var = $row_cats[category_list]; // Each Category list title
?>
<aside>
<h1><a name=""><? echo $cat_var ?></a></h1>
<?php
try {
$search_sql = $dbo->prepare("SELECT name, category_list FROM category WHERE category_list=:cat_var ORDER BY name ASC"); // Pulling a list of names for the category list
$search_sql->bindParam(":cat_var",$cat_var,PDO::PARAM_STR);
$search_sql->execute();
$results_search = $search_sql->fetchAll();
} catch(PDOException $e) {
include('basehttp/error');
}
$array_search = $results_search;
if(is_array($array_search)) { // Output list of names which match category
foreach($array_search as $row_search) {
?>
<h2><?php echo $row_search[name]; ?></h2>
<br class="clear">
<?php
}
}
?>
</aside>
<br class="clear">
<?php
}
}
?>
</section>
Its actually Simple....I did similar thing for my project once. I had to pull out all music albums name and categorize them in alphabetical order.
In my table, "album_name" is the column where names are stored.
$sql= "select * from album_table order by album_name ASC";
$temp_char= ""; // temporary variable, initially blank;
using while loop, iterate through records;
while($row= $rs->fetch_assoc())
{
$album_name= $row['album_name'];
$first_char_of_albm= $album_name[0]; // this will store first alphabet;
$first_char_of_albm= strtoupper($first_char_of_albm); // make uppercase or lower as per your needs
if($temp_char!=$first_char_of_albm)
{
echo $first_char_of_albm;
$temp_char= $first_char_of_albm; // update $temp_char variable
}
}
That's it....
I am posting my answer to this old question for 3 reasons:
You don't always get to write your queries to MySQL or another DBMS, as with a web service / API. None of the other answers address PHP sorting without query manipulation, while also addressing the vertical alphabetical sort
Sometimes you have to deal with associative arrays, and only a couple other answers deal with assoc. arrays. BTW, my answer will work for both associative and indexed arrays.
I didn't want an overly complex solution.
Actually, the solution I came up with was pretty simple--use multiple tags with style="float:left", inside of a giant table. While I was sceptical that having multiple tbody tags in a single table would pass HTML validation, it in fact did pass without errors.
Some things to note:
$numCols is your desired number of columns.
Since we are floating items, you may need to set the width and min-width of parent elements and/or add some <br style="clear: both" />, based on your situation.
for alternative sorting methods, see http://php.net/manual/en/array.sorting.php
Here's my full answer:
function sortVertically( $data = array() )
{
/* PREPARE data for printing */
ksort( $data ); // Sort array by key.
$numCols = 4; // Desired number of columns
$numCells = is_array($data) ? count($data) : 1 ;
$numRows = ceil($numCells / $numCols);
$extraCells = $numCells % $numCols; // Store num of tbody's with extra cell
$i = 0; // iterator
$cCell = 0; // num of Cells printed
$output = NULL; // initialize
/* START table printing */
$output .= '<div>';
$output .= '<table>';
foreach( $data as $key => $value )
{
if( $i % $numRows === 0 ) // Start a new tbody
{
if( $i !== 0 ) // Close prev tbody
{
$extraCells--;
if ($extraCells === 0 )
{
$numRows--; // No more tbody's with an extra cell
$extraCells--; // Avoid re-reducing numRows
}
$output .= '</tbody>';
}
$output .= '<tbody style="float: left;">';
$i = 0; // Reset iterator to 0
}
$output .= '<tr>';
$output .= '<th>'.$key.'</th>';
$output .= '<td>'.$value.'</td>';
$output .= '</tr>';
$cCell++; // increase cells printed count
if($cCell == $numCells){ // last cell, close tbody
$output .= '</tbody>';
}
$i++;
}
$output .= '</table>';
$output .= '</div>';
return $output;
}
I hope that this code will be useful to you all.

Categories