Can't delete first value of my array - php

I got a script that shows products according to their id. In the echoed data there is a link which redirects the user to the same page but with a posted id, according to that id I delete a product (id) from my session which is an array. This works perfectly except for the first array value. What could be causing that?
How I have my code at the moment:
//Link to quote page and send product id with it
echo '<p><a class="offertelink" href="offerte.php?product='.$productcr[0]['id'].'">Request a quote</a></p>';
On my quote page:
ob_start();
include 'includes/header.php';
if(!isset($_SESSION['product'])){
$_SESSION['product'] = array();
}
// Check if product is set before putting it in an array
if(isset($_GET['product']) && !in_array($_GET['product'], $_SESSION['product'])){
$_SESSION['product'][] = $_GET['product'];
}
// Implode array to use ids in query
$prods = implode(",", $_SESSION['product']);
Query:
if(count($_SESSION['product']) != 0){
// Get all products with id in session
$offerte = "SELECT * FROM `web_content` WHERE `id` in (".$conn->real_escape_string($prods).") AND state = 1";
$offertecon = $conn->query($offerte);
$offertecr = array();
while ($offertecr[] = $offertecon->fetch_array());
}
And finally below my query:
// Check if id is send, and delete from session accordingly
if(isset($_GET['id'])){
$productID = $_GET['id'];
if( $index = array_search($productID, $_SESSION['product']) ) {
$_SESSION['product'][$index] = null;
unset($_SESSION['product'][$index]);
header('Location: http://www.web.nl/_extern/web/offerte.php');
}
}
if(count($_SESSION['product']) == 0){
echo 'No products added';
}else{
foreach($offertecr as $product){
$offerte_imgs = $product['images']; // Get image parameters of the article
$offertepic = json_decode($offerte_imgs); // Split the parameters apart
if($offertepic->{'image_intro'} != ''){
$image = 'cms/'.$offertepic->{'image_intro'};
}else{
$image = 'http://www.web.nl/_extern/web/cms/images/Producten/Untitled-7.jpg';
}
if($product['id'] != ''){
if (strlen($product['introtext']) > 100){
$shortcat = substr($product['introtext'], 0, 100) . '...';
}else{
$shortcat = $product['introtext'];
}
$deleteLink = "offerte.php?id=".$product['id'];
$offerteoverzicht .= '
<div class="row productofferte">
<a href="producten/'.$product['alias'].'.html">
<div class="col-md-6 offerteimg">
<img style="border:1px solid #ddd;" src="'.$image.'">
</div>
</a>
<div class="desc">
<a style="color:#2d4160;" href="producten/'.$product['alias'].'.html"><p style="font-weight:bold;">'.$product['title'].' </a>
<a href="'.$deleteLink.'">
<i class="fa fa-times" aria-hidden="true"></i>
</a>
</p>
<p>'.$shortcat.'</p>
</div>
</div>';
}
}
}
echo $offerteoverzicht;
I've read a bit on my problem and figured it has something to do with shifting the array if I'm correct. If I print my session all the arrays are deleted from it, except the first one. Doesn't matter what id it is, when I change the first product then that product cannot be deleted from the session.

Your test on finding an element in an array with array_search should compare to false. Doing ! will return false when the element found is at index 0:
Change:
if( $index = array_search($productID, $_SESSION['product']) ) {
to:
if( ($index = array_search($productID, $_SESSION['product'])) !== false ) {

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);
}

How to make specific button disappear

I am newbie at website programming. This is for my school 'end of the year' project. I need to know how to make upvote/downvote system. I managed to make +1 and -1 buttons for each of my posts, but when I want them to disappear when clicked all of them disappear (instead of only the specific one). The +1 and -1 works for individual posts but my solution does not work. example: When I click button +1 on post id=2 all of +1 buttons disappear and so on. I would like to know the solution for my problem. Thanks in advance
while ($forum = $vysledek->fetch_assoc())
{
if (isset($_SESSION['upvote'])) {
$type = 'hidden';
}
else
{
$type = 'button';
}
if (isset($_SESSION['downvote'])) {
$type1 = 'hidden';
}
else
{
$type1 = 'button';
}
?>
<a href='votes.php?pris=<?php echo $forum['id_prispevek'] ?> & ad_id=1'>
<input type="<?php echo $type ?>" value="+1"></a>
<a href='votes.php?pris=<?php echo $forum['id_prispevek'] ?> & ad_id=0'>
<input type="<?php echo $type1 ?>" value="-1"></a>
}
and on votes.php
<?php
include "pripojeni1.php";
$var_value = $_GET['ad_id'];
$prispevek = $_GET['pris'];
if ($var_value == 1) {
$query = mysqli_query($link,"
UPDATE forum
SET votes = votes + 1
WHERE id_prispevek = '".$prispevek."'
");
header("location:vypisForum.php?var=$prispevek");
$_SESSION['upvote'] = 1;
unset($_SESSION['downvote']);
}
if ($var_value == 0) {
$query = mysqli_query($link,"
UPDATE forum
SET votes = votes - 1
WHERE id_prispevek = '".$prispevek."'
");
header("location:vypisForum.php?var=$prispevek");
$_SESSION['downvote'] = 1;
unset($_SESSION['upvote']);
}
?>

Simple if else statement not working as usual

I got a simple if else statement where I show a list of pdf files, when the id is empty (aka there is no pdf file) I want to show: 'No available downloads'. But it shows that text no matter what, even if there are pdf files present.
My code:
<div class="widget broucher">
<h4>DOWNLOADS</h4>
<ul>
<?
//pdf bestanden
$pdf = "SELECT * FROM `snm_attachments` WHERE parent_id = '".$conn->real_escape_string($contentcr[0]['id'])."'";
$pdfcon = $conn->query($pdf);
$pdfcr = array();
while ($pdfcr[] = $pdfcon->fetch_array());
foreach($pdfcr as $pdf){
if($pdf['id'] != ''){
$downloads .= '<li><i class="fa fa-file-pdf-o"></i>'.$pdf['filename'].'</li>';
}else{
$downloads .= '<li>No available downloads</li>';
}
}
echo $downloads;
?>
</ul>
</div>
Why is it always showing, even when there is no id present for a row?
Use this code:
<?
//pdf bestanden
$pdf = "SELECT * FROM `snm_attachments` WHERE parent_id = '".$conn->real_escape_string($contentcr[0]['id'])."'";
$pdfcon = $conn->query($pdf);
// initialize downloads variable:
$downloads = '';
// see how while statement disappears (in your code you have the fetch_array attached to the first element of the array):
$pdfcr = $pdfcon->fetch_array();
foreach($pdfcr as $pdf){
if($pdf['id'] != ''){
$downloads .= '<li><i class="fa fa-file-pdf-o"></i>'.$pdf['filename'].'</li>';
}else{
$downloads .= '<li>No available downloads</li>';
}
}
echo $downloads;
?>
Note than the No available downloads message will be rendered in all iterations of the data array when id is different than empty. To show the message when there are no records use this code:
if(count($pdfcr) > 0) {
foreach($pdfcr as $pdf){
if($pdf['id'] != ''){
$downloads .= '<li><i class="fa fa-file-pdf-o"></i>'.$pdf['filename'].'</li>';
}
}
}

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

Variable exists but the if statement denies its existence

I have the statement if(isset($votes)) in votes_allvotes.tpl.php.
If I check the value on the same line right before that statement it tells me the value is 2, but for some reason the if statement refuses to acknowledge this.
Also tried if($votes > 0), did not work. I use this on 2 pages and on the other one it works fine, though there is nothing on this page that should conflict in any way with this (deleted everything on the page and it still didnt work.
Using Joomla 1.5.21 and Virtuemart 1.1.6
Here is the code:
<div class="rating" style="margin: 0px 0px 15px -9px">
<?php
$product_flypage = $_SERVER['REQUEST_URI'];
echo ps_reviews::allvotes( $product_flypage );
?>
ps_reviews::allvotes:
function allvotes( $product_id ) {
if (strstr($product_id, '&')) {
$arr = explode('&', $product_id);
$pro_arr = explode('=', $arr[2]);
$cat_arr = explode('=', $arr[3]);
$product_id = $pro_arr[1];
$category_id = $cat_arr[1];
}
global $db;
$tpl = new $GLOBALS['VM_THEMECLASS']();
$dbc = new ps_DB;
$q = "SELECT votes, rating FROM #__{vm}_product_votes "
. "WHERE product_id='$product_id' ";
$dbc->query( $q );
$votes = $dbc->f("votes");
$rating = $dbc->f("rating");
if( $votes != 0)
$tpl->set('votes', $votes );
$tpl->set('rating', $rating );
$tpl->set('product_id', $product_id );
$tpl->set('category_id', $category_id );
return $tpl->fetch( 'common/votes_allvotes.tpl.php' );
}
votes_allvotes.tpl.php (WHERE THE ACTUAL PROBLEM IS):
if (isset($votes)) { ?>
<img src="<?php echo VM_THEMEURL ?>images/stars/<?php echo $rating ?>.gif" align="middle" border="0" alt="<?php echo $rating ?> stars" />
<?php echo $VM_LANG->_('PHPSHOP_TOTAL_VOTES').": ". $votes;
}
else {
if (!empty($my->id)) {
if( $_GET['flypage']){
echo "<li class='reviews'><a href='javascript:void(0)' style='color:#000;'><b>Wees de eerste om een recensie te schrijven!</b></a></li>";
}else{
echo "<a href='/index.php?page=shop.product_details&flypage=flypage.tpl&product_id=". $product_id ."&category_id=". $category_id ."&option=com_virtuemart&Itemid=1&lang=nl&review=yes'><b>Wees de eerste om een recensie te schrijven!</b></a>";
}
}else {
echo $VM_LANG->_('PHPSHOP_REVIEW_LOGIN'); // Login to write a review!
}
}
isset might not be returning what you expected.
$votes = 0;
if(isset($votes)){
echo 'Ooer missus ...';
}
I am not sure but perhaps you want ...
if((int)$votes > 0){
echo 'well you got at least one vote ...';
}
Anyhow, if a condition does not do as you expect, then
var_dump()
that variable onto the page or into a log file and inspect it.
Even better, inspect it PRIOR to writing your conditional test.

Categories