PHP print all the values inside while without repeat html - php

i got a problem with my php script.
I can't figure out how to print the values of my last query inside the same div with a while cycle, without repeat the div! Here's the code.
$query_serie = "SELECT nome_serie FROM serie";
$result_serie = mysql_query($query_serie);
while ($row_serie = mysql_fetch_array($result_serie)) {
echo '<h4 class="intestazione_catalogo"><span>serie:</span> '.$row_serie['nome_serie'].'</h4>';
$query_finitura = "SELECT nome_finitura FROM finitura JOIN serie ON finitura.id_serie = serie.id_serie WHERE nome_serie = '" .$row_serie['nome_serie']. "'";
$result_finitura = mysql_query($query_finitura);
while ($row_finitura = mysql_fetch_array($result_finitura)) {
echo '<div class="finitura_catalogo">'.$row_finitura['nome_finitura'].'</div>';
$query_codice = "SELECT codice FROM codice JOIN finitura ON codice.id_finitura = finitura.id_finitura LEFT JOIN serie ON finitura.id_serie = serie.id_serie WHERE visibile = 'si' AND nome_finitura = '".$row_finitura['nome_finitura']."'";
$result_codice = mysql_query($query_codice);
while ($row_codice = mysql_fetch_array($result_codice)) {
echo '<div class="codice_catalogo">'.$row_codice['codice'].'</div>';
}
echo '<div class="clear"></div>';
}
}
I need to ouput something like this
and following the others blocks and go on...
Any help would be appreciated!

Try putting divisions outside the while loop. Something like this:
<div class="codice_catalogo">
while ($row_codice = mysql_fetch_array($result_codice)) {
echo $row_codice['codice'];
}
</div>
Hope it works.

Related

PHP: creating select options from MYSQL database?

I'm trying to create multiple select dropdowns from MYSQL database!
basically I need to create select dropdowns based on the given sub-categories and put every op_value related to that sub_cate_name under the created dropdown menu as options.
at the moment, my code creates the dropdowns and select options BUT it will put them in separate select dropdwons and all over the place.
For example: if we have 2 sub_cate_name as Apples and 3 op_value as Reds, Greens, Yellows it will create 2 select dropdown menus and split them op_value which is (Reds, Greens, Yellows) as select options where ever it likes!
but i need it to make sure it creates 1 select dropdown as Apples and put ever op_value related to apples under the Apples dropdown as option!
This is code seems to have mind of its own as it works sometimes and it doesn't others!
this is the entire code:
$drops ="";
$sql44 ="SELECT * FROM drop_options WHERE sub_cat_name='$currentproduct'";
$query44 = mysqli_query($db_conx, $sql44);
$productCount44 = mysqli_num_rows($query44);
if ($productCount44 > 0)
{
$op_name = '';
$first = 0;
while($row44 = mysqli_fetch_array($query44, MYSQLI_ASSOC))
{
$op_value = $row44["op_value"];
if($op_name != $row44["op_name"])
{
if($first)
{
$drops .='</select></div>';
}
$op_name = $row44["op_name"];
$drops .='<div class="col-md-3 col-xs-12">
<p class="margin-bottom-zero">'.$op_name.'</p>
<select name="keyword[]" class="selectpicker">
<option value="'.$op_value.'">'.$op_value.'</option>';
}
else
{
$drops .= '<option value="'.$op_value.'">'.$op_value.'</option>';
}
/*$first = 1;*/
$first++;
}
}
else
{
$drops ='';
}
$drops .='</select></div>';
echo $drops;
Could someone please advise on this issue?
any help would be appreciated.
EDIT:
Okay, now i tried it this way and I can get the exact amount of the select drop downs created as it should:
if($db_conx->connect_errno > 0){
die('Unable to connect to database [' . $db_conx->connect_error . ']');
};
// Perform queries
$sql45 = "SELECT DISTINCT op_name FROM drop_options WHERE sub_cat_name='Custom Booklets";
$result45 = $db_conx->query($sql45);
//echo '<li class="product-types">';
foreach ($result45 as $menu45)
{
// echo "<li>".$menu["cat_name"];
echo '<div class="col-md-3 col-xs-12">
<p class="margin-bottom-zero">'.$menu45["op_name"].'</p>
<select name="keyword[]" class="selectpicker">';
//echo "<ul>";
$menu_title45 = $menu45["sub_cat_name"];
$sql455 = "SELECT * FROM drop_options WHERE op_name='".$menu45["op_name"]."'";
$result455 = $db_conx->query($sq455);
foreach ($result455 as $submenu455)
{
//echo "<li>".$submenu["sub_cat_name"]."</li>";
echo '<option value="'.$submenu455["op_value"].'">'.$submenu455["op_value"].'</option>';
}
echo "</select>";
echo "</div>";
}
//echo "</ul>";
$db_conx->close();
BUT i get no select options created at all Also i get this error: Warning: Invalid argument supplied for foreach() in line 18
and this is on line 18 : foreach ($result45 as $menu45){
any idea what i'm doing wrong?
This is how you're code should look like-
// Perform queries
$sql45 = "SELECT DISTINCT op_name FROM drop_options WHERE sub_cat_name='Custom Booklets'";
$result45 = $db_conx->query($sql45);
//echo '<li class="product-types">';
while ($menu45 = mysqli_fetch_array($result45,MYSQLI_ASSOC))
{
// echo "<li>".$menu["cat_name"];
echo '<div class="col-md-3 col-xs-12">
<p class="margin-bottom-zero">'.$menu45["op_name"].'</p>
<select name="keyword[]" class="selectpicker">';
//echo "<ul>";
$menu_title45 = $menu45["sub_cat_name"];
$sql455 = "SELECT * FROM drop_options WHERE op_name='".$menu45["op_name"]."'";
$result455 = $db_conx->query($sql455);
while($submenu455 = mysqli_fetch_array($result455,MYSQLI_ASSOC))
{
//echo "<li>".$submenu["sub_cat_name"]."</li>";
echo '<option value="'.$submenu455["op_value"].'">'.$submenu455["op_value"].'</option>';
}
echo "</select>";
echo "</div>";
}
//echo "</ul>";
$db_conx->close();
You may want to add if condition to check whether there are actually select options so you wont end up with an empty select.

MySQL GROUP by or using PHP?

I have an issue that seems to be quiet easy but I just would like to ask how you would solve it:
In a MySQL-table there is the following structure:
provider artist
a 1
a 2
a 3
b 4
Now it is necessary to echo a list in HTML like:
provider a
1
2
3
provider b
4
I stuck at the point where I would like to group the results and echo them out with for-each and while loop.
The main idea is quiet simple like:
<?php $query = mysqli->query("SELECT * FROM `table` GROUP by provider");
foreach GROUP {?>
echo some styling HTML-code for each group of headline;
<?php while ($data= $query->fetch_assoc()){?>
echo some styling HTML-code for each list-item;
<?php};?>
Thanks in advance.
UPDATE:
Thanks for answering.
The solution fro RiggsFolly seems to work fine. There is just a small problem with the HTML. There is a surrounding div-tag that wont be closed when adding the HTML code in that line:
echo 'provider '. $data->provider;
The problem is that the while loop needs to be in the div. The closing div-tag is missing for every
if ( $current_provider != $data->provider ) {
Here is the original HTML-code:
<?php
$service = $db->query("SELECT * FROM `system` ORDER BY provider, artist");
$current_provider = NULL;
while ($data = $service->fetch_object()) {
if ( $current_provider != $data->provider ) {// new provider?>
<div class="service">
<p class="lower">
<?php echo $data->provider;?>
</p>
<?php
$current_provider = $data->provider;
}?>
<a href='?artist=<?php echo $data->artist;?>'><?php echo "/".$data->artist;?</a><br/>
<?php };?>
</div><!--service -->
The list-items will be shown nicely. But when looking into the Source code you can see that the closing div-tag is missing. Thanks
Kind regards.
It would seem simpler to not use a GROUP BY especially as it will not provide you with the data that you want. So instead just select them all and sort them by provider and maybe artist as a sub sort like so
<?php
$result = $mysqli->query("SELECT * FROM `table` ORDER BY provider, artist");
$current_provider = NULL;
while ($data = $result->fetch_object()){
if ( $current_provider != $data->provider ) {
// new provider
echo 'provider '. $data->provider;
$current_provider = $data->provider;
}
echo $data->artist;
}
?>
AFTER UPDATE:
<?php
$service = $db->query("SELECT * FROM `system` ORDER BY provider, artist");
$current_provider = NULL;
while ($data = $service->fetch_object()) {
if ( $current_provider != $data->provider ) {
if ( $current_provider !== NULL ) {
echo '</div>';
}
echo '<div class="service">';
echo '<p class="lower">' . $data->provider . '</p>';
$current_provider = $data->provider;
}
echo '<a href="?artist=' . $data->artist '">' .
$data->artist . '</a><br/>';
}
echo '</div>';
How about that.
<?php $query = mysqli->query("SELECT * FROM `table`");
$current_group = array();
while ($data= $query->fetch_assoc()){
if(in_array($data['provider'],$current_group)){
echo "<h1>New Group" . $data['provider'] ."</h1>";
$current_group[] = $data['provider']
}
echo $data['artist'] . "<br/>";
}

creating a dynamic search query in php and pdo

Ive been trying to get this to work but I dont think my sql is setup correctly.
For instance I am trying to get a search word from the URL and then insert it using prepared statements so that its safe to use in the database.
First I call the userid of the products they own from the sessions.
Then I check if they have more than 1 item, if they do I setup an array and insert into database, if they do not have more than 1 item then I just simply insert into database to retrieve data.
The reason why I am setting it into variables is because its being sent to the pagination class so it will paginate the results.
Here is the header of the html:
<?php
$searchword = $urlmaker->geturlandsearch($_GET["search"]);
$findcomma = strpos($_SESSION["SESS_USERSPRODUCTIDS"], ",");
if($findcomma == true){
$userproductid = explode(',', $_SESSION["SESS_USERSPRODUCTIDS"]);
$prep = array(':like' => "%$searchword%", ':like2' => "%$searchword%");
$q = '';
$e = '';
$i = 1;
foreach($userproductid as $productid){
$q .= 'productid=:productid' . $i . ' || ';
$prep[":productid{$i}"] = $productid;
$i++;
}
$q = rtrim($q, " || ");
} else {
$q = 'productid=:productid';
$prep = array(':productid' => $_SESSION["SESS_USERSPRODUCTIDS"], ':like' => "%$searchword%", ':like2' => "%$searchword%");
}
$maxlimit = 15;
$geturi = "/Search-Forum/" . $_GET['search'] . "/";
$string = "SELECT id,title,date,username,viewcount,replycount,replyuser,replydate FROM forum_topics WHERE " . $q . " AND title LIKE :like OR content like :like2 ORDER BY replydate DESC";
$pagstring = "SELECT id FROM forum_topics WHERE " . $q . " AND title LIKE :like OR content like :like2";
$pagurl = $geturi;
Here is the frontend code:
<?php
$topicQuery = $pagination->paginatedQuery($pdo, $string, $maxlimit, $prep);
if($topicQuery != "no query"){
while($fetchquery = $topicQuery->fetch()) {
$topicid = stripslashes($fetchquery["id"]);
$topictitle = stripslashes($fetchquery["title"]);
$topicdate = stripslashes($fetchquery["date"]);
$topicusername = stripslashes($fetchquery["username"]);
$topicviewcount = stripslashes($fetchquery["viewcount"]);
$topicreplycount = stripslashes($fetchquery["replycount"]);
$topicreplyuser = stripslashes($fetchquery["replyuser"]);
$topicreplydate = stripslashes($fetchquery["replydate"]);
?>
<li>
<div class="topiclisttitle"><p><b><?php echo ucwords($topictitle); ?></b><br><?php echo $topicusername ; ?> on <?php echo $betterTime->dateAndtime($topicdate); ?></p></div>
<div class="topiclistview"><p><b><?php echo $topicviewcount ; ?></b><br>Views</p></div>
<div class="topiclistview"><p><b><?php echo $topicreplycount ; ?></b><br>Replies</p></div>
<div class="topiclistlastposted"><?php if(!empty($topicreplyuser)){ ?><p>By: <b><?php echo $topicreplyuser ; ?></b> On<br><?php echo $betterTime->dateAndtime($topicreplydate); ?></p><?php } else { ?><p>By: <b><?php echo $topicusername ; ?></b> On<br><?php echo $betterTime->dateAndtime($topicreplydate); ?></p><?php } ?></div>
</li>
<?php } } else { ?>
<li><p class="morepadding">No Topics Regarding Your Search Words :(</p></li>
<?php } ?>
Here is the database input on the pagination class:
$freebiesquery = $pdo->prepare($string . " LIMIT " . $maxlimit);
$freebiesquery->execute($prep);
$freebiesquery_num = $freebiesquery->rowCount();
All this works on other pages so it has to be the way Im doing the header section of the code, the way im formating the sql query in the first place.
The only errors I am getting are as follows:
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number
And
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number
But this cant be as I have counted thema and they are the same?
Putting strings containing => into an array doesn't make associations. => is part of the syntax of array literals, they have to be outside the strings.
Replace:
$prep[] = "':productid{$i}' => {$productid}";
with:
$prep[":productid{$i}"] = $productid};
Replace:
$e = "':productid' =>" . $_SESSION["SESS_USERSPRODUCTIDS"];
With:
$prep = array(':productid' => $_SESSION["SESS_USERSPRODUCTIDS"]);
Replace:
$prep = array($e, ':like' => "%$searchword%", ':like2' => "%$searchword%");
with:
$prep[':like'] = "%$searchword%";
$prep[':like2'] = "%$searchword%";

php working locally and remotely on own hosting, but not remotely on client's hosting

I'm not good with PHP, so please bear with me. I have the following code:
<?php $thisPage="designers";
include("phpincludes/header.php") ?>
<div id="contentLeft">
<?echo "<h2><a href='designer_display.php?d_name=".$_GET['d_name']."'>" . $_GET['d_name']. "</a></h2>";?>
<?
error_reporting(0);
require_once "phpincludes/connection.php";
$designer = $_GET['d_name'];
// Category Selection Start.
$cat_qry = "SELECT DISTINCT (
`own_category`
)
FROM `products`
WHERE `designer` ='".$designer."' && own_category != ''";
$rs_qry = mysql_query($cat_qry);
$i = 0;
while($rec_qry = mysql_fetch_array($rs_qry))
{
if($i==0)
$first_cat = $rec_qry['cat_name'];
$cat_name[$i]=$rec_qry['cat_name'];
$i++;
}
// Category Selection Start.
$cat_name = $_GET['catName1'];
$cat_qry = "SELECT DISTINCT (
`own_category`
)
FROM `products`
WHERE `designer` ='".$designer."' && own_category != ''";
//"select * from categories";
$rs_qry = mysql_query($cat_qry);
$rec_no = mysql_affected_rows();
/*if($_GET["catName1"]=="")
$catName = $first_cat;
else
$catName = $cat_name;*/
$n1 = 1;
echo "<ul id=\"designers\">";
while($rec_qry = mysql_fetch_array($rs_qry))
{
$cate_name = str_replace('_',' ',$rec_qry['own_category']);
//print_r($cate_name[1]);
if($rec_qry["own_category"]!= $_GET['catName'])
echo "<li><A HREF='d_items.php?no=".$n1."&d_name=".$designer."&catName=".$rec_qry["own_category"]."'>".strtoupper($cate_name)."</A></li>";
else
echo "<li><A HREF='d_items.php?no=".$n1."&d_name=".$designer."&catName=".$rec_qry["own_category"]."'><font color='#8d9354'>".strtoupper($cate_name)."</font></a></li>";
if($rec_qry["own_category"]== $_GET['catName'])
{
$query="SELECT A.photo_filename, A.photo_title, B.dc_cat_name FROM displays A
LEFT JOIN displays_categories B ON B.dc_display_photos = A.photo_filename
WHERE dc_cat_name ='".$rec_qry["cat_name"]."'";
$query="SELECT B.pro_name, B.own_category, B.own_photo_filename from categories as A LEFT JOIN
products as B ON A.cat_name = B.own_category
where cat_name ='".$_GET["catName"]."' and designer ='".$designer."' order by B.pro_name";
$rs1_qry = mysql_query($query);
echo "<ul class=\"items\">";
while($row = mysql_fetch_array($rs1_qry))
{
if ($designer == "Jardan") {
$p1name = str_ireplace($designer,'',$row["pro_name"]);
$pname = substr($p1name, 0, -3);
} else {
$pname = str_ireplace($designer,'',$row["pro_name"]);
}
if($_GET['ProName'] != $row["pro_name"])
echo "<li><A HREF='d_item_details.php?d_name=".$designer."&ProName=".$row['pro_name']."&catName1=".$rec_qry['own_category']."&catName=".$rec_qry['own_category']."'>".$pname."</A></li>";
else
echo "<li><A HREF='d_item_details.php?d_name=".$designer."&ProName=".$row['pro_name']."&catName1=".$rec_qry['own_category']."&catName=".$rec_qry['own_category']."'><font color='#fff'>".$pname."</font></A></li>";
}
echo "</ul>";
}
}
echo "</ul>";
$f=1;
$recnm = $_GET['ProName'];
$owncat = $_GET['catName1'];
$photo_title = $_GET['ptitle'];
$query2="SELECT pro_code, pro_dimensions, own_photo_filename, designer_pdf, palette FROM products
WHERE pro_name ='".$recnm."' and own_category ='".$owncat."'";
$rt2=mysql_query($query2);
echo mysql_error();
?>
</div>
<div id="contentRight">
<?
while($row2 = mysql_fetch_array($rt2))
{
?>
<?$d = explode(' ',$designer);
for($p=0;$p<count($d);$p++)
{
$des.=$d[$p];
}
if ($designer == "Playstar") {
$p2name = str_ireplace($designer,'',$recnm);
$poname = substr($p2name, 0, -3);
} else {
$poname = str_ireplace($designer,'',$recnm);
}
?>
<img class="lighting" src="img/designers/<?echo $des."/".$row2['own_photo_filename'];?>.jpg" />
<div class="mailerBtn"><h4>ENQUIRE</h4>
<h4>Download Product PDF</h4></div>
<h3><?echo $poname;?></h3>
<p>
<?
echo "<b>Product code:</b> ". $row2['pro_code']."<BR>";
if ($designer == "Playstar") {
echo $row2['pro_dimensions'];
} else {
echo "<b>Dimensions:</b> ". $row2['pro_dimensions'];
} ?>
</p>
<? if($row2[4]=='yes') {
?>
<img class="palette" src="img/designers/<?echo $des."/".$row2['own_photo_filename'];?>-palette.jpg" />
<? } ?>
<?}?>
<?php include("phpincludes/base.php") ?>
Much of the code was written by someone else, but I've been modifying it in a couple of ways. It works locally (on XAMP) and on my personal site where I've been hosting it as a test site.
But when i uploaded it to the client's host, this page stops abruptly at echo "<ul class=\"items\">"; - roughly line 73. I can't see what's stopping it from running properly.
Some assistance would be gratefully received!
MTIA.
That's hard to tell. It's very obviously something with the clients setup.
Taking a wild guess, that client is still running PHP4. Because after line 73 you have a call to str_ireplace which wasn't available for that.
You would likely get a fatal error for this one. And this is the right avenue for investigation here. Add this on top for debugging (instead of error_reporting(0) which is not so helpful):
error_reporting(E_ALL|E_WARNING);
And ask for errors. Better yet, provide a custom error handler which prints out something shiny for end user-type clients. Otherwise ask for the error.log which should contain the exact error likewise.
You should avoid using the "short tags" <? and replace with the regular <?php tags. At a minimum, on that line not having a space after the "?" is asking for trouble, but overall you should just replace the short tags as they can cause trouble for various reasons and many installations do not have them enabled by default.
FYI, one specific case where they often cause trouble is for XHTML documents, if the xml declaration isn't printed with PHP, it will throw an error. Now with HTML5 I guess this will be less of an issue, but IMHO, best practice would be to avoid them.
Glad you got it working, but I wouldn't be using this code in production on your clients web host.
$f=1;
$recnm = $_GET['ProName'];
$owncat = $_GET['catName1'];
$photo_title = $_GET['ptitle'];
$query2="SELECT pro_code, pro_dimensions, own_photo_filename, designer_pdf, palette FROM products WHERE pro_name ='".$recnm."' and own_category ='".$owncat."'";
This and all the other queries here are vulnerably to sql injection. (if I passed in catName1='; DELETE * FROM products where 1=1 or '2'='2)
You need to either convert the queries to paramaterised queries, or use mysql_real_escape_string.
ie
$owncat = mysql_real_escape_string($_GET['ProName']);

Help with my funky PHP loop

Ok so i have this page and when viewed in firefox the proper results show up but when i look at it in chrome or safari it is way off. Could it be the funky php loop that i am using that makes it off in the browsers..Here is my code
I am generating a left and right array..seems like a hack to me
$left = array();
$right = array();
$finaltot=0.00;
for($i=0;$i<count($steps);$i++)
{
$sql="SELECT * FROM configure_system WHERE EstimateID='".$_SESSION['ESTQUOTE']."' AND StepID=".($i+1) ;
$expstep=ExecuteGetRows($sql);
if ($i % 2 == 0) {
$sql="SELECT SUM(TotalPrice) AS TOT FROM configure_system WHERE EstimateID='".$_SESSION['ESTQUOTE']."' AND StepID=".($i+1);
$tots=ExecuteGetRows($sql);
$left["Step"][$i][] = $steps[$i];
$left["expstep"][$i][] = $expstep;
$left["final_total"][$i][] = $tots[0]['TOT'];
$finaltot+=$tots[0]['TOT'];
} else {
$sql="SELECT SUM(TotalPrice) AS TOT FROM configure_system WHERE EstimateID='".$_SESSION['ESTQUOTE']."' AND StepID=".($i+1);
$tots=ExecuteGetRows($sql);
$right["Step"][$i][] = $steps[$i];
$right["expstep"][$i][] = $expstep;
$left["final_total"][$i][] = $tots[0]['TOT'];
$finaltot+=$tots[0]['TOT'];
}
then since the left array only has 0,2,4,6,8,10
and right has 1,3,5,7,9,11
so my loops are like this
<?php for($i=0;$i<count($left['Step']) * 2;$i++) { ?>
<?php $i++; ?>
<?php } ?>
<?php for($i=1;$i<count($right['Step'])* 2;$i++) { ?>
<?php $i++; ?>
<?php } ?>
So as you can see the code is a bit off and i think that maybe the problem with why safari and chrome are off...any suggestions
Why do not use foreach instead?
foreach ($right['Step'] as $i => $val) {
// ...
}
Also you could get the same results with only one query:
SELECT SUM(TotalPrice) AS TOT
FROM configure_system
WHERE EstimateID='".$_SESSION['ESTQUOTE']."'
GROUP BY StepID

Categories