I am making simple shopping cart and i got really stucked with final price a.k.a $fp variable.
there is always: Notice: Undefined variable: fp in C:\xampp\htdocs...
the thing is everything is working, data from database are fetched on site, price included but when i want to display $fp(final price) it shows that error.
I tried setting it to 0 in else statement after if($row['ID'] == $id) loop, nothing happened
I tried to make it global like:
global $fp;
$fp = $fp + intval($row['price']);
when i did that, error disappeared but it just didnt do anything(empty space). maybe i am just sitting too long looking at that but i just can't wrap my head around why i cant acess that variable or what is happening.
<section class="cart">
<?php
if(isset($_SESSION['cart'])){
$product_id = array_column($_SESSION['cart'],'product_id');
$sql = "SELECT * FROM muzi;";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
foreach($product_id as $id){
if($row['ID'] == $id){
echoItem($row['fotografia'],$row['price'],$row['znacka'],$row['konkretne'],$size);
$fp = $fp + intval($row['price']);
}
}
}
}else{
echo "<h5>Cart is empty</h5>";
}
?>
<h2 class="h2-cart-item">PRICE: <?php $fp;?> €</h2>
</section>
function echoItem($productIMG, $productPrice, $znacka, $typ_oblecenia){
$product = "
<article class='clearfix'>
<img src='../img/$productIMG' alt='hihi' style='width: 10%;'>
<div class='info-text-cart'>
<p>specific type: $typ_oblecenia</p>
<p>Brand: $znacka</p>
<button><i class='fas fa-times'></i></button>
</div>
<div class='important-info-cart'>
<p>Price: $productPrice €</p>
<p>quantity: 1</p>
</div>
</article>
";
echo $product;
}
ps: i have everything in terms of typing right. I just translated some things that are involved in this to english so it makes more sense.
$fp has never been declared as mentioned before.
If you declare it as global (or not) you should be able to use it on the second code block, the reason that you didn't see anything when you tried is because you forgot to echo it.
A working example would be:
<section class="cart">
<?php
$fp = 0;
if(isset($_SESSION['cart'])){
$product_id = array_column($_SESSION['cart'],'product_id');
$sql = "SELECT * FROM muzi;";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
foreach($product_id as $id){
if($row['ID'] == $id){
echoItem($row['fotografia'],$row['price'],$row['znacka'],$row['konkretne'],$size);
$fp = $fp + intval($row['price']);
}
}
}
}else{
echo "<h5>Cart is empty</h5>";
}
?>
<h2 class="h2-cart-item">PRICE: <?php echo $fp;?> €</h2>
</section>
Related
I am trying to keep all the PHP files separated from the HTML files. Sort of a template based project but without using any template engines as they are mostly bloated and the fact that you will need to learn another language which is not PHP at all.
Anyway, I have the following code in my index.php file:
<?php
$query = "SELECT id FROM products ORDER by id";
$product_list = "";
if ($stmt = mysqli_prepare($db_conx, $query)) {
/* execute statement */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $id);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
$product_list .= "
}
}
?>
<?php include "template.php"; ?>
And I have this code in my template.php file:
<html>
<head>
</head>
<body>
<div class='prod_box'>
<div class='center_prod_box'>
<div class='product_title'><a href='#'>$product_name</a></div>
<div class='product_img'><a href='#'><img src='images/" . $id . "Image1.jpg' alt='' border='0' /></a></div>
<div class='prod_price'><span class='reduce'>350$</span> <span class='price'>270$</span></div>
</div>
<div class='prod_details_tab'> <a href='#' class='prod_buy'>Add to Cart</a> <a href='#' class='prod_details'>Details</a> </div>
</div>
</body>
</html>
When I run the code, I basically get the HTML page displayed exactly as you see it above. So no data is being shown from the MySQL database!
EDIT:
I tried using the following code in my while loop and still the same:
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$shipping = $row["shipping"];
$category = $row["category"];
Could someone please help me out with this?
I would suggest using a template system to parse your template file.
Just something quick and dirty:
class Example {
// This will be used to save all the variables set trough the set() function within the class as an array
private $variables = array();
function set($name,$value) {
// Here we are going to put the key and value in the variables array
$this->variables[$name] = $value;
}
function Template($file) {
// First set the file path of the template, the filename comes from the Template({filename}) function.
$file = '/templates/'.$file.'.php';
// Here we are going to extract our array, every key will be a variable from here!
extract($this->variables);
// Check if it is actually a file
if (!is_file($file)) {
throw new Exception("$file not found");
// Check if the file is readable
} elseif(!is_readable($file)) {
throw new Exception("No access to $file");
} else {
// if both are fine we are going to include the template file :)
include($file);
}
}
}
and use it like this:
$class = new Example;
$class->set("data", $data);
// like passing a name:
$class->set("user", $username);
$class->Template("filename");
Then in your template file you can use $data and $user with their contents.
Also, in your template file you're not displaying the variable because it's not in between of PHP tags. Here's two examples for you, one short and the other in the normal format:
<?=$productname?>
// or :
<?php echo $productname; ?>
Oh, and you actually do nothing here:
while (mysqli_stmt_fetch($stmt)) {
$product_list .= "
}
}
You NEED to close the opening " with "; and nothing is added to $product_list.
Honestly, you should use a template system. If you don't want to hinder with learning how they work, there is a very easy approach: create a very simple one yourself. You'll need it sooner or later. The below solution should be very easy, and it's copy-pasteable.
The basic operation of such system is that you:
Load the template file with placeholder strings.
Process the template file (replace placeholders with actual values).
Output (or return) the HTML with now processed text.
An example class that is very easy to comprehend might be this:
class HtmlPage
{
private $html;
# Loads specified template file into $html
public function Load($template)
{
if (!file_exists($template)) {
echo "Specified template ($template) does not exist.";
return false;
}
$this->html = file_get_contents($template);
return true;
}
# Takes in an array of data, key is the placeholder replaced, value is the new text
public function Process($data_array)
{
if (!is_array($data_array)) return;
foreach ($data_array as $search => $replace)
{
# Add brackets so they don't have to be manually typed out when calling HtmlPage::Process()
$search = "{$search}";
$this->html = str_replace($search, $replace, $this->html);
}
}
# Returns the page
public function GetHtml()
{
return $this->html;
}
}
Can be used as:
$page_title = "My fancy page title";
$page_text = "All your base are belong to us.";
$page = new HtmlPage();
$page->Load('html/templates/mypage.html');
$page->Process(array(
'TITLE' => $page_title,
'TEXT' => $page_text
));
echo $page->GetHtml();
The above code will replace
<html>
<head>
{TITLE}
</head>
<body>
<p>{TEXT}</p>
</body>
</html>
...to...
<html>
<head>
My fancy page title
</head>
<body>
<p>All your base are belong to us.</p>
</body>
</html>
In your case, this will work like the following:
html/templates/product-item.html:
<div class='prod_box'>
<div class='center_prod_box'>
<div class='product_title'>
<a href='#'>{PRODUCT_NAME}</a>
</div>
<div class='product_img'>
<a href='#'><img src='images/{PRODUCT_ID}/Image1.jpg' alt='' border='0' /></a>
</div>
<div class='prod_price'>
<span class='reduce'>{PRODUCT_PRICE_REDUCE}</span> <span class='price'>{PRODUCT_PRICE}</span>
</div>
</div>
<div class='prod_details_tab'>
<a href='#' class='prod_buy'>Add to Cart</a> <a href='#' class='prod_details'>Details</a>
</div>
</div>
PHP code:
<?php
$query = "SELECT * FROM products ORDER by id";
$product_list = "";
if ($stmt = mysqli_prepare($db_conx, $query))
{
/* execute statement */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $id);
/* fetch values */
$result = mysqli_stmt_get_result($stmt);
while ($product = mysqli_fetch_array($result)) {
$product_html = new HtmlPage();
$product_html->Load('html/templates/product-list.html');
$product_html->Process(array(
'PRODUCT_NAME' => $product['name'];
'PRODUCT_ID' => $product['id'];
'PRODUCT_PRICE' => $product['price'];
'PRODUCT_PRICE_REDUCE' => $product['price_reduce'];
));
$product_list .= $product_html->GetHtml();
}
}
In index.php
<?php
$query = "SELECT id FROM products ORDER by id";
$product_list = "";
if ($stmt = mysqli_prepare($db_conx, $query)) {
/* execute statement */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $id);
/* fetch values */
}
define("PRODUCT_NAME",$row["product_name"]);
define("PRODUCT_ID",$row["id"]);
define("PRODUCT_PRICE",$row["price"]);
define("PRODUCT_SHIPPING",$row["shipping"]);
define("PRODUCT_CATEGORY",$row["category"]);
?>
<?php include "template.php"; ?>
and in template.php
<html>
<head>
</head>
<body>
<div class='prod_box'>
<div class='center_prod_box'>
<div class='product_title'><a href='#'><?=PRODUCT_NAME?></a></div>
<div class='product_img'><a href='#'><img src='images/<?=PRODUCT_ID?>/Image1.jpg' alt='' border='0' /></a></div>
<div class='prod_price'><span class='reduce'>350$</span> <span class='price'>270$</span></div>
</div>
<div class='prod_details_tab'> <a href='#' class='prod_buy'>Add to Cart</a> <a href='#' class='prod_details'>Details</a> </div>
</div>
</body>
</html>
Your code is a bit of a mess, you need to go back to the basics: your statement is returning $id and not $product as you mentioned. To return anything from the database, in your template.html do:
<html>
<body>
<!-- More html here ... -->
<div class='product_title'>
<!-- Return value like this -->
<a href='#'><?php echo $product_name; ?></a>
</div>
</body>
</html>
Make sure you check the value exists first.
You need to use the extract() function in PHP to get this sorted out. It will then start working as a Controller - View architecture that you are looking for.
For example:
<?php
$query = "SELECT id FROM products ORDER by id";
$product_list = "";
if ($stmt = mysqli_prepare($db_conx, $query)) {
/* execute statement */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $id);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
$product_list .= "";
}
}
$data['product_list'] = $product_list;
$view = 'template.php';
loadTemplate($view, $data);
function loadTemplate($view, $data)
{
extract($data);
include($template);
}
?>
Then directly use $product_list in the view section. This should do it.
Working example:
<?php
$data['test'] = 'This is a working example';
$view = 'workingExampleView.php';
loadTemplate($view,$data);
function loadTemplate($viewName,$viewData)
{
extract($viewData);
include($viewName);
}
?>
Create a new File naming it workingExampleView.php:
<html>
<body>
<span><?php echo $test; ?></span>
</body>
</html>
I'm pulling comments from MySQL with PDO with a limit of 2 comments to show, yet the query does not retrieve the comments nor can I var_dump neither print_r since it does print anything. I believe it should be an issue with the query itself, thought it hasn't worked for countless hours so I figured I'd ask more experienced programmers.
There is no data outputted onto the page, I'm unsure whether It's an issue with the second_count variable or the post_iD variable.
1. Am I using the while loop correctly?
2. Better to use while loop or foreach?
3. Does var_dump and print_r function not work due to errors in the
query or in PHP.INI from what it seems?
Here is how I'm pulling the data with PDO.
PUBLIC FUNCTION Comments( $post_iD,$second_count ){
if($second_count){
$sth = $this->db->prepare("
SELECT C.com_id, C.uid_fk, C.comment, C.created, U.username, U.photo
FROM comments C, users U
WHERE U.status = '1'
AND C.uid_fk = U.uiD
AND C.msg_id_fk = :postiD
ORDER BY C.com_id ASC LIMIT :second, 2");
$sth->execute(array(':postiD' => $post_iD, ':second' => $second_count));
while( $row = $sth->fetchAll())
$data[] = $row;
if(!empty($data)){
return $data;
}
}
}
And here is how I'm trying to display the information on my page,
<?php
$commentsarray = $Wall->Comments( $post_iD, 0 );
$x=1;
if($x){
$comment_count = count($commentsarray);
$second_count = $comment_count-2;
if($comment_count>2){
?>
<div class="comment_ui" id="view<?php echo $post_iD; ?>">
View all<?php echo $comment_count; ?> comments
</div>
<?php
$commentsarray = $Wall->Comments( $post_iD, $second_count );
}
}
if( $commentsarray ){
foreach($commentsarray as $data){
$com_id = $data['com_id'];
$comment = tolink(htmlcode($data['comment'] ));
$time = $data['created'];
$mtime = date("g:i", $time);
$username = $data['username'];
$com_uid = $data['uid_fk'];
$photo = $data['photo'];
?>
<div class="stcommentbody" id="stcommentbody<?php echo $com_id; ?>">
<div class="stcommentimg">
<img src="<?php echo $photo;?>" class="small_face">
</div>
<div class="stcommenttext">
<?php if($uiD == $com_uid || $uiD == $post_iD ){ ?>
<a class="stcommentdelete" href="#" id="<?php echo $com_id;?>" title="Delete Comment"></a>
<?php } ?>
<div class="stmessage"><?php echo clear($comment); ?></div>
</div>
<div class="stime"><?php echo $mtime;?> — Like</div>
</div>
<?php
}
}
?>
1.Simply like this:
$data = $sth->fetchAll();
if(!empty($data) AND count($data) > 0){
return $data;
}
You don't need while to work with fetchAll.
2.I'ts better to use Exception in every your query then you can see if there is any error.
e.g
try
{
//your PDO stuffs here
}
catch (PDOException $e)
{
echo $e->getMessage();
}
I have the code below that is selecting a random set of questions from Wordpress.
<?php
$rows = get_field('step_by_step_test');
$row_count = count($rows);
$rand_rows = array();
$questions = get_field('select_number_of_questions');
for ($i = 0; $i < min($row_count, $questions); $i++) {
$r = rand(0, $row_count - 1);
while (array_search($r, $rand_rows) !== false) {
$r = rand(0, $row_count - 1);
}
$rand_rows[] = $r;
echo $rows[$r]['question'];
}
?>
I want to incorporate a bit of extra code (below), how can I make sure it's selecting the same random question?
<?php if(get_sub_field('answer_options')): ?>
<?php while(has_sub_field('answer_options')): ?>
<?php echo the_sub_field('answer'); ?>
<?php endwhile; ?>
<?php endif; ?>
Why dont you change your approach slightly?
<?php
$rows = get_field('step_by_step_test'); // Get the test
$question_count = get_field('select_number_of_questions'); // Get the number of questions
$rows = shuffle($rows); // Randomize your questions
$rows = array_slice($rows, $question_count); // Now set the array to only contain the number of questions you wanted
foreach ($rows as $row) {
echo $row['question']; // Show the question
if(get_sub_field('answer_options', $row['id'])) {
while(has_sub_field('answer_options', $row['id'])) {
echo the_sub_field('answer');
}
}
}
?>
I made the assumption that you can alter "get_sub_field" to include the ID of the question, so you can then include the ID in your "where" field of "answer_options". This will allow you to link the question.
I think that what you need is to set up the whole thing in a loop. query by custom field
Or you could store the ids of the questions you got above, an then, below, query for the answers for those specific posts.
Here's how I randomized my WordPress slider using the Advanced Custom Fields plugin + Royal Slider with a modified version of TheSwiftExchange's code above
<div id="full-width-slider" class="royalSlider heroSlider rsMinW">
<?php
/*
* Slider Repeater field shuffled
* http://stackoverflow.com/questions/12563116/incorporating-extra-loop-into-random-selection
*/
$rows = get_field('slider');
// For Debugging:
// echo "<pre>";
// var_dump($rows);
// echo "</pre>";
$quotes = get_field('slide_text'); // Get the number of images
shuffle($rows); // Randomize your slides
foreach ($rows as $row) {
$slideImageID = $row['slide_image'];
$slideImage = wp_get_attachment_image_src( $slideImageID, 'full' );
$slideText = $row['slide_text'];
?>
<div class="rsContent">
<div class="royalCaption">
<div class="royalCaptionInner">
<div class="infoBlock">
<?php if(!empty($slideText)) {
echo $slideText;
}; ?>
</div>
</div>
</div>
<img src="<?php echo $slideImage[0]; ?>" class="" />
</div><!-- /.rsContent -->
<?php } // end foreach ?>
</div><!-- /slider-wrap -->
This question already has answers here:
Fatal error: [] operator not supported for strings
(9 answers)
Closed 7 years ago.
I wrote (thanks to Stackoverflow help, too) a PHP script (called wunder_temp.php) which shows the temperature and location for a given number of Weatherunderground.com Stations.
I included this script in my footer, and it works well BUT on a single page.
If I open http://www.flapane.com/guestbook/guestbook.php the temperatures won't be shown in my footer, and error.log says:
[09-Sep-2012 09:46:45 UTC] PHP Fatal error: [] operator not supported for strings in /home/xxx/public_html/wunder_temp.php on line 47
$display = file($cachename, FILE_IGNORE_NEW_LINES); //ignore \n for non-reporting stations
foreach ($display as $key=>$value){
if($key % 2 == 0){
$temperature[] = $value; // EVEN (righe del file cache pari)
}else{
$location[] = $value; // ODD - **HERE IS LINE 47**
}
}
The weird thing is that guestbook.php is the ONLY page of my website where wunder_temp.php doesn't work.
What the above code does is reading the cachefile and put in a $temperature[] array the even lines and in $location[] array the odd lines.
Here's a sample from my cachefile:
26.8
Stadio San Paolo di Napoli, Napoli
24.4
Pozzuoli
Honestly I don't know why I see that errors just on my guestbook page.
It turns out that the "culprit" is the function loadmore.php which loads the guestbook comments (and which is included in guestbook.php) using a twitter-style ajax function. If I don't include it, wunder_temp.php works well, and it doesn't produce any error.
loadmore.php:
<div id='contcomment'>
<div class="timeline" id="updates">
<?php
$sql=mysql_query("select * from gbook_comments ORDER BY id DESC LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['id'];
$name=$row['name'];
$url=$row['url'];
$email=$row['email'];
$location=$row['location'];
$date= strtotime($row['dt']); //unix timestamp
$country_code=$row['country_code'];
$message=$row['body'];
$link_open = '';
$link_close = '';
if($url){
// If the person has entered a URL when adding a comment,
// define opening and closing hyperlink tags
$link_open = '<a href="'.$url.'" target="_blank" rel="nofollow">';
$link_close = '</a>';
}
// Needed for the default gravatar image:
$url_grav = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
// Show flags
$image = strtolower($country_code) . ".png";
if (file_exists("./img/flags/" . $image)){
$show_image = true;
$image_link = "<img src='/guestbook/img/flags/$image' alt='user flag' />";
}else{
$show_image = false;
}
echo '<div class="comment">
<div class="avatar">
'.$link_open.'
<img src="http://www.gravatar.com/avatar/'.md5($email).'?size=50&default='.urlencode($url_grav).'" alt="gravatar icon" />
'.$link_close.'
</div>
<div class="name">'.$link_open.$name.$link_close.' </div><div class="location"><i>(da/from '.$location.' '.$image_link.' )</i></div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$date).'">'.date('d M Y',$date).'</div>
<p>'.$message.'</p>
</div>' ;
} ?>
</div>
<div id="more<?php echo $msg_id; ?>" class="morebox">
Carica Commenti più vecchi / Load older entries
</div>
</div>
ajax_more.js AJAX twitter-style load-more-comments function:
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else
{
$(".morebox").html('Nessun altro commento / No more comments');
}
return false;
});
});
ajax_more.php (needed by the above script):
<?
include "connect.php";
if(isSet($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$lastmsg=mysql_real_escape_string($lastmsg);
$result=mysql_query("select * from gbook_comments where id<'$lastmsg' order by id desc limit 9");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['id'];
$name=$row['name'];
$url=$row['url'];
$email=$row['email'];
$location=$row['location'];
$date= strtotime($row['dt']); //unix timestamp
$country_code=$row['country_code'];
$message=$row['body'];
$link_open = '';
$link_close = '';
if($url){
// If the person has entered a URL when adding a comment,
// define opening and closing hyperlink tags
$link_open = '<a href="'.$url.'" target="_blank" rel="nofollow">';
$link_close = '</a>';
}
// Needed for the default gravatar image:
$url_grav = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
// Show flags
$image = strtolower($country_code) . ".png";
if (file_exists("./img/flags/" . $image)){
$show_image = true;
$image_link = "<img src='/guestbook/img/flags/$image' alt='user flag' />";
}else{
$show_image = false;
}
echo '<div class="comment">
<div class="avatar">
'.$link_open.'
<img src="http://www.gravatar.com/avatar/'.md5($email).'?size=50&default='.urlencode($url_grav).'" alt="gravatar icon" />
'.$link_close.'
</div>
<div class="name">'.$link_open.$name.$link_close.' </div><div class="location"><i>(da/from '.$location.' '.$image_link.' )</i></div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$date).'">'.date('d M Y',$date).'</div>
<p>'.$message.'</p>
</div>' ;
}
?>
<div id="more<?php echo $msg_id; ?>" class="morebox">
Carica Commenti più vecchi / Load older entries
</div>
<?php
}
?>
Any help is appreciated
$location is already a string on that page. This is why you properly initialize variables before you use them:
$temperature = $location = array();
foreach ($display as $key => $value){
if ($key % 2 == 0){
$temperature[] = $value;
} else {
$location[] = $value;
}
}
Even better, separate your variable scopes better so you don't get a name clash like that. Use functions and classes with their private variable scopes and don't put everything in the global scope.
It seems a matter of variable scope.
When you include loadmore.php in guestbook.php you are implicitly declaring $location as a string:
$location=$row['location'];
So this line of your loop:
$location[] = $value; // ODD - **HERE IS LINE 47**
is not implicitly declaring a new array variable on the first iteration but trying to append $value to the previously declared string variable, hence the error.
Try giving a different name to $location either in loadmore.php or guestbook.php or making loadmore.php a function (so it runs in its own scope) and then call it from your guestbook.php script after including its code on it. Or use explicit declaration of $location variable if you want to reuse it as an array (just add $location = array(); before the loop).
I think that loadmore.php and/or ajaxmore.php are setting a global variable ($location) to a string. When the guestbook page tries to index this variable you get the error.
Solution: use functions and local variables.
$location=$row['location']; is the issue. Because PHP doesn't have block level scope, you are essentially pre-setting this variable and trying to set it's array index using []. Because it's a string, that will break.
You should always initialize your variables to avoid these kinds of conflicts:
i.e.
$location = array();
Rename $location for one of the scripts. You have $location=$row['location'] somewhere. Also, declare the variable when using it as an array:
$array = array();
$array[] = 'item'; // when you add an item here, $array will always accept an array push.
while ($row = mysql_fetch_array($result)) {
<h3> <?php echo $row['ideaTitle']; ?> </h3>
<blockquote>
<p>
<em>
<?php echo $row['feedback']; ?>
</em>
</p>
</blockquote>
<?php } ?>
Here's my working code. I want to attempt to find when $row['ideaTitle'] is new, but I'm not sure how to do it. I thought about setting a temp variable w/ the title name, but I feel like there needs to be a simpler solution.
Using a temporary variable is pretty much the way to go, I would say -- that's what I do in this kind of situation.
And it generally translates to this kind of code :
$previousTitle = null;
while ($row = mysql_fetch_array($result)) {
if ($row['ideaTitle'] != $previousTitle) {
// do something when the current line
// is the first with the current title
}
// work with $row
// Store the current title to the temporary variable,
// to be able to do the comparison on next iteration
$previousTitle = $row['ideaTitle'];
}
There is no other way than to use a temporary variable. But instead of using a single last value string, try a count map:
if (#$seen_titles[ $row["ideaTitle"] ]++ == 0) {
print "new title";
}
This trick works, because the counting up ++ is in effect done after the comparison. It needs an # error suppression however for the redundant notices here.
Imo this is quite a simple solution. However, you could also preprocess the data and create a title => feedbacks map:
$feedbacks = array();
while (($row = mysql_fetch_array($result))) {
if(!array_key_exists($row['ideaTitle'], $feedbacks) {
$feedbacks[$row['ideaTitle']] = array();
}
$feedbacks[$row['ideaTitle']][] = $row['feedback'];
}
And then create the output:
<?php foreach($feedbacks as $title => $fbs): ?>
<h3> <?php echo $title; ?> </h3>
<?php foreach($fbs as $fb): ?>
<blockquote>
<p>
<em><?php echo $fb ?></em>
</p>
</blockquote>
<?php endforeach; ?>
<?php endforeach; ?>
Keep a track of previously encountered titles in a key value array.
$prevTitles = array();
while ($row = mysql_fetch_array($result)) {
if($prevTitles[$row['ideaTitle']] == true)
continue;
$prevTitles[$row['ideaTitle']] = true;
<h3> <?php echo $row['ideaTitle']; ?> </h3>
<blockquote>
<p>
<em>
<?php echo $row['feedback']; ?>
</em>
</p>
</blockquote>
<?php } ?>