Php: While loop group output - php

I have two columns in my database, year and content i want to group the content by year (i have a lot of content and many years not only 2015 and 2016 as the example )
so i'll have this output in html
<div class="all">
<div class="2016">
2016
<div class="content_2016">
All the content of the column that is in the same ligne as 2016 in the database
</div>
</div>
<div class="2015">
2015
<div class="content_2015">
All the content of the column that is in the same ligne as 2015 in the database
</div>
</div>
</div>
<?php
$query = "SELECT * FROM publi where pub_type=0 order by pub_year DESC, pub_publi ";
$result = mysqli_query($connection, $query);
$previous =0;
while ($val = mysqli_fetch_array($result))
{
if ($previous <> $val['pub_year'])
{
$previous = $val['pub_year'];
$year = $previous;
echo $year;
echo '<br>';
$Temp = highlight("person1",$val['pub_publi'],"0000FF");
$Temp = highlight("person2",$Temp,"0000FF");
$Temp = highlight("person3",$Temp,"0000FF");
$Temp = highlight("person4",$Temp,"0000FF");
$Temp = highlight("person5",$Temp,"0000FF");
$Temp = highlight("person6",$Temp,"0000FF");
$Temp = highlight("person7",$Temp,"0000FF");
$Temp = highlight("person8",$Temp,"0000FF");
$Temp = highlight("person9",$Temp,"0000FF");
$Temp = highlight("person10",$Temp,"0000FF");
echo '<a target=blank href="http://www.test.com/query.f?term=' . $val['pub_pubmed'] . '";)><img border="0" src="img/test.gif" align=MIDDLE alt="Search in for ' . $val['pub_publi'] . '"></a>';
echo $Temp;
echo '<br>';
}
}
?>
It is outputing the years right
2016
2015
2014
etc...
but it is only showing the first ligne of each year not all the content for each year.

Run the following query:
Select Content From table order by year
echo like following (or concat):
while rs.hasNext(){
if (currentYear != lastyear){
echo div #with year As Class;
}
echo row # a single entry the way you want it dispalyed;
lastYear = currentYear;
}

what u are asking is huge chunk to write. so here are steps:
create array with this SQL statement below and fetch assoc in PHP
select distinct on year * from table
now use foreach($years as $year) on array and fetch content
select content from table where year=$year
to sandwich your code output in SQL keep concatenating like
$html = "";
$html .= "<div class=\"all\">";
foreach($years as $year){
$html .= "<div class=\"content_$year\">";
//then content fetched from second sql query
$html .= "</div>";
}
$html .= "</div>";
how to fetch data in sql | PHP.NET MANUAL
how to join/concat in php | PHP.NET MANUAL
LATER ADDITIONS, SNIPPET FROM MY OWN CODE :
$letter = $_POST['letter'];
$query_out = "SELECT link_id,singer_url FROM letter_mapping WHERE letter = '$letter'";
if($result_out = $conn_out->query($query_out)){
if($result_out->num_rows > 0){
while($row = $result_out->fetch_assoc()) {
$link_id = $row['link_id'];
$singer_url = $row['singer_url'];
/*
foreach($row as $name=>$value){
}
*/
}
}
$result_out->free();
}
if($conn_out->close()){
// Message for disconnect
//echo "Status : DISCONNECTED<br/>";
}

Related

Getting all data after clicking a particular cell in a table

Dbfiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=65b310b4b973a7577d4953e01c09a124
Currently I have a table that displays a total count of my data values for each source. I'm getting this value after comparing 2 tables 1 is crm_leads with all my product information and 1 is crm_sources with what sources are the products related to.
Now this is the output:
Now as you can see the total count is shown under each header next to its source. There are 8 cells for each source as seen in the picture. Now these count values are inside a tags which once clicked go to viewall page.
Now here basically I want to show the data of the item that I had clicked. So for example, if I clicked the 163 under Hot status, it takes me to the viewall page and shows me id, source, enquiry_date for all those under status Hot in a table.
So basically it should detect the data for which source and which status is clicked and then accordingly make a statement like this?
select * from crm_leads where lead_source = '.$source.' and lead_status = '.$status.';
Another thing I'm thinking I can do here is put my table inside a form and pass those values as post in my controller class leadstatus which will pass that value to viewall? Not really sure on how to proceed.
Model Class:
function get_statusreport($fdate='',$tdate='')
{
$this->db->select("l.lead_status,crm_sources.title,count(*) as leadnum,l.enquiry_date,l.sub_status");
$this->db->from($this->table_name." as l");
if($fdate !='')
$this->db->where("date(l.added_date) >=",date('Y-m-d',strtotime($fdate)));
if($tdate !='')
$this->db->where("date(l.added_date) <=",date('Y-m-d',strtotime($tdate)));
$this->db->where("lead_status <>",10);
$this->db->join("crm_sources ","crm_sources.id= l.lead_source","left");
$this->db->group_by("l.lead_status,crm_sources.title");
$this->db->order_by("leadnum DESC, crm_sources.title ASC,l.lead_status ASC");
$query = $this->db->get();
$results = $query->result_array();
return $results;
}
Controller Class(leadstatus holds the view for my current table):
public function leadstatus($slug='')
{
$content='';
$content['groupedleads'] = $this->leads_model->get_statusreport($fdate,$tdate);
$this->load->view('crm/main',$main);
$this->load->view('crm/reports/leadstatus',$content);
}
public function viewall($slug='')
{
$content='';
$this->load->view('crm/main',$main);
$this->load->view('crm/reports/viewall',$content);
}
View class:
<?php
$ls_arr = array(1=>'Open',8=>'Hot',2=>'Closed',3=>'Transacted',4=>'Dead');
foreach($groupedleads as $grplead){
$statuses[] = $status = $ls_arr[$grplead["lead_status"]];
if($grplead["title"] == NULL || $grplead["title"] == '')
$grplead["title"] = "Unknown";
if(isset($grplead["title"]))
$titles[] = $title = $grplead["title"];
$leaddata[$status][$title] = $grplead["leadnum"];
}
if(count($titles) > 0)
$titles = array_unique($titles);
if(count($statuses) > 0)
$statuses = array_unique($statuses);
?>
<table>
<tr">
<th id="status">Source</th>
<?php
if(count($statuses) > 0)
foreach($statuses as $status){
?><th id=<?php echo $status; ?>><?php echo $status; ?></th>
<?php
}
?>
<th>Total</th>
</tr>
<?php
if(is_array($titles))
foreach($titles as $title){
?>
<tr>
<?php
$total = 0;
echo "<td>".$title."</td>";
foreach ($statuses as $status) {
$num = $leaddata[$status][$title];
echo "<td><a target='_blank' href='".site_url('reports/viewall')."'>".$num."</a></td>";
$total += $num;
$sum[$status] += $num;
}
echo "<td>".$total."</td>";
$grandtotal += $total;
?>
</tr>
<?php } ?>
</table>
You can include the source and status in the URL like this:
foreach ($statuses as $status) {
$num = $leaddata[$status][$title];
echo "<td><a target='_blank' href='" . site_url('reports/viewall?source=' . $source . '&status=' . $status) . "'>" . $num . "</a></td>";
$total += $num;
$sum[$status] += $num;
}
Then in your controller:
public function viewall($slug = '')
{
$content = '';
$source = $this->input->get('source');
$status = $this->input->get('status');
// Do what you want with $source and $status
$this->load->view('crm/main', $main);
$this->load->view('crm/reports/viewall', $content);
}

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.

I don't get all the data from mysql - PHP

I've been searching for this for while but didn't find anything related.
So my problem is that I do get all the data from mysql with while(). However, all the articles I am trying to get displays as only 1 article even though the content is different. Sorry, it's not easy to explain that but see pictures below:
My database:
How it is displayed:
my articlesFunction.php code:
// check if user is logged in to view the content:
if(!isset($_SESSION['loggedin']) && !isset($_SESSION['loggedinAdmin'])){
header("Location: login.php");
}else{
}
//
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//
my articles.php:
<?php
///////////////////////////////////////////////////////////////////////////////////////
// UNFINISHED //
///////////////////////////////////////////////////////////////////////////////////////
session_start();
require_once 'connect.php';
include 'articlesFunction.php';
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog posts</title>
<link rel="stylesheet" href="css/articles.css">
</head>
<body>
<div id="bannerDiv" style="background-image: url(images/banner.jpg); background-size: 100% 100%; height:150px;">
<h2 id="bannerTitle"><u><i>Articles about travel that everyone loves...</i></u></h2>
<p>Homepage</p>
<span id="BannerMenu"><?php echo 'logged in as: '.$_SESSION['username'].' ';?></span><button>Logout</button>
</div>
<div id="container">
<div id="articles">
<div id="Display Articles">
<h1><u>Our set of articles:</u>
</h1>
<div id="display">
<?php
echo $fullArticle;
?>
</div>
</div>
</div>
</div>
</body>
</html>
So, I hope you understand my issue now. First, in this example, when I put it alone in the div, I only get the oldest article and I get only 1. If I add a while to the div, It gives me the results in the picture above:
So, how can I display the articles (all of them) and each one to be different as they are in the database.
You are overwriting your variable on every iteration of the while loop.
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}
so as a simple example
$a = 0;
$b = 3;
while($a < $b){
$output = $a;
$a++;
}
echo $output;
This gives back 2 because $output is being over written every-time. There are two approaches to keeping all the values.
Option one, concatenate the variable
$a = 0;
$b = 3;
$output = '';
while($a < $b){
$output .= $a;
$a++;
}
echo $output;
Which will output 012. We have to define the variable before using it with the .=. With the .= it is trying to concatenate the value first so it must already exist.
Option two, store the values in an array
$a = 0;
$b = 3;
while($a < $b){
$output[] = $a;
$a++;
}
print_r($output);
This will output:
Array
(
[0] => 0
[1] => 1
[2] => 2
)
This way is a bit more work because when you want to access it later you have to re-iterate through it. However it can be better if you want to be able to access each data point separately.
foreach($output as $value) {
echo $value;
}
Also note if users are providing their usernames, article name, or description and you aren't filtering that this will open you to XSS injections.
https://en.wikipedia.org/wiki/Cross-site_scripting
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#A_Positive_XSS_Prevention_Model
Usage in your actual code would be:
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
This should be your code, in order to avoid the errors you mentioned in the comments;
//init fullname variable
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//

Split text from the database in two columns

I have a bootstrap based website with 2 columns(col-lg-6 and col-lg-6).
I have the ability to add text from an admin panel (articles).
How can I make it so it splits in the second div (col-lg-6) after a specific number of characters or after I insert a character or something that will represent the breakage?
I prefer a PHP solution, but Javascript/Jquery would do too
edit *
if(isset($_GET['chapter']) && !empty($_GET['chapter'])){
$chapterid = (int)$_GET['chapter'];
$chaptertitle = mysql_query("SELECT bookname FROM books WHERE id=$chapterid");
$chaptertitle = mysql_fetch_array($chaptertitle);
$chaptertitle = $chaptertitle[0];
$chapter = mysql_query("SELECT bookContent FROM books WHERE id=$chapterid");
$chapter = mysql_fetch_array($chapter);
$chapter = $chapter[0];
$bookcontent = mysql_query("SELECT * FROM books WHERE bookid=$id");
$bookcontainer = '';
while($row = mysql_fetch_array($bookcontent)){
$bookcontainer .= '<h2>'.$row['bookname'].'</h2>' . $row['bookContent'];
}
and this is the place where the code is printed
<div class="row">
<div class="col-lg-6" id="paragraphs">
<div style="width:100%;">
<?php
//if($errors == false){
echo $chapter;
//}
//else{
//echo 'erorr madarfaker';
//}
?>
</div>
</div>
<div class="col-lg-6"></div>
</div>
If anyone is interested in this: I made 2 fields in the admin panel and the variable that was being sent to the database was "field 1 + ' | ' + field 2" and then I used explode to display the content on 2 sides, separator being " | "
Choose an arbitrary character for your split, like "|". Based on your posted code, use this as your echo statement:
echo str_replace($chapter, "|", "</div></div><div class='col-lg-6' id='paragraphs'><div style='width:100%;'>");
I am not sure if this solves your problem, but you can try :
<?php
// An array with your database data :
$arr = array('val1', 'val2', 'val3', 'val4');
$col1 = "";
$col2 = "";
$flag=false;
for($i=0; $i<sizeof($arr); $i++){
//Break condition :
$flag = ($arr[$i] == "val3" || $flag != true ) ? true : false;
if(!$flag){
$col1 .= $arr[$i];
}
else{
$col2 .= $arr[$i];
}
}
$html = "";
if($col1 != ""){
$html .= "<div class='col-lg-6'>".$col1."</div>";
}
if($col2 != ""){
$html .= "<div class='col-lg-6'>".$col2."</div>";
}
// The two div with your content (if the break rule is found) :
echo $html;
?>
If anyone is interested in this: I made 2 fields in the admin panel and the variable that was being sent to the database was "field 1 + ' | ' + field 2" and then I used explode to display the content on 2 sides, separator being " | "

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%";

Categories