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 ) {
Hi Can anyone tell me how to display customer name after login into the site in magento.
As of now instead of customer name it is displaying as DROPDOWN. Can anyone check this and solve this it will be very helpful for me.As i am new to magento
app\code\core\Mage\Page\Block\Html\header.php(code from this file).
public function getWelcome()
{
if (empty($this->_data['welcome'])) {
if (Mage::isInstalled() && Mage::getSingleton('customer/session')->isLoggedIn()) {
$this->_data['welcome'] = $this->__('Welcome, %s!', $this->escapeHtml(Mage::getSingleton('customer/session')->getCustomer()->getName()));
} else {
$this->_data['welcome'] = Mage::getStoreConfig('design/header/welcome');
}
}
return $this->_data['welcome'];
}
This is the code from where it is getting as 'DROPDOWN' but not getting how to get the name and display the customer name instead of dropdown.
<div data-toggle="dropdown" class="dropdown-toggle md-ink">
<span class="fa fa-cog hidden-sm hidden-lg hidden-md"></span>
<span class="hidden-xs"><?php echo $this->__('Dropdown') ?>
<span class="caret"></span></span>
</div>
Check if any customer is logged in or not
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
//Load the customer's data
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customer->getPrefix();
$customer->getName(); // Full Name
$customer->getFirstname(); // First Name
$customer->getMiddlename(); // Middle Name
$customer->getLastname(); // Last Name
$customer->getSuffix();
// All other customer data
$customer->getWebsiteId(); // ID
$customer->getEntityId(); // ID
$customer->getEntityTypeId(); // ID
$customer->getAttributeSetId(); // ID
$customer->getEmail();
$customer->getGroupId(); // ID
$customer->getStoreId(); // ID
$customer->getCreatedAt(); // yyyy-mm-ddThh:mm:ss+01:00
$customer->getUpdatedAt(); // yyyy-mm-dd hh:mm:ss
$customer->getIsActive(); // 1
$customer->getDisableAutoGroupChange();
$customer->getTaxvat();
$customer->getPasswordHash();
$customer->getCreatedIn(); // Admin
$customer->getGender(); // ID
$customer->getDefaultBilling(); // ID
$customer->getDefaultShipping(); // ID
$customer->getDob(); // yyyy-mm-dd hh:mm:ss
$customer->getTaxClassId(); // ID
}
Help me guys to make page loader while the page is loading. I'm doing some paypal payment system. As I watch some pages, when the page is directing to paypal page, they put some loader(ajax loader) while the page is processing to redirect to "Paypal gateway". I'm also planning to put some Ajax loader in my other page while they're loading. So please help me guys. Here is my code.
<?php
$current_url = base64_encode($url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_POST['checkoutnow'])){
header('Location: checkout_now1.php');
}
if(isset($_SESSION["products"])){
$total = 0;
echo '<ol>';
echo '<form action="paypal-express-checkout/process.php" method="POST">';
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm)
{
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT product_name,product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-price">'.$currency.$obj->price.'</div>';
echo '<div class="product-info">';
echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->product_desc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
}
echo '</ol>';
echo '<strong>Total: '.$currency.$total.'</strong><br />';
echo '<center>
<div id="check_out">
<button>Check Out with US</button><br />OR<br />
<div class="paypal-button"><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckoutsm.gif"></div>
</center>
</div>';
echo '</form>';
}else{
echo 'Your Cart is Empty<br />Go to Home And Order';
}
?>
To do so, you can use javascript method "setInterval()" to put a time between two process or more. I didn't get where is you condition to put this delay, but I link you my code and hope it helps :
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8" />
<title> title-page </title>
</head>
<body>
<script type = "text/javascript">
function loading() {
var miliSecTime = 1000; // 1 sec time between each process for example
document.getElementById("waitDiv").InnerHtml = "<img src = 'wait.gif' />";
var timer = setInterval(function () {
// BEGIN : Your process
// END : Your process
// Condition to abort the process
// Likely when you want to stop
// the waiting view
if (leftLoading_condition) {
clearInterval(timer);
document.getElementById("waitDiv").innerHTML = ""; // Hidding the wait view
}
},
miliSecTime
);
}
</script>
<!-- This is where you want to show you wait gif -->
<div id = "waitDiv">
</div>
<input type = "button" onClick = "loading()" />
</body>
</html>
The "setInterval()" function takes two parameters : the first is you function, the second is the delay you want to put between each tick. So you make a proces into the function method, and the trick is to put a left tick event condition, with the call of the method "clearInterval" which will stop the tick.
So here is the work of this code :
The function "loading" is called by clicking on the button. The method launch the process which is included in the "function () {}" code. Before launching this process, we show the wait gif, which can be a loading gif or whatever. Then, the process run in loop until the left tick condition (the if() call). If we have reach the end of the process, the timer is aborted by clearing the interval parameters (by calling "clearInterval()" method).
<?php
session_start();
include_once("../config.php");
include_once("paypal.class.php");
$paypalmode = ($PayPalMode=='sandbox') ? '.sandbox' : '';
if($_POST) //Post Data received from product list page.
{
//Other important variables like tax, shipping cost
$TotalTaxAmount = 2.58; //Sum of tax for all items in this order.
$HandalingCost = 2.00; //Handling cost for this order.
$InsuranceCost = 1.00; //shipping insurance cost for this order.
$ShippinDiscount = -3.00; //Shipping discount for this order. Specify this as negative number.
$ShippinCost = 3.00; //Although you may change the value later, try to pass in a shipping amount that is reasonably accurate.
//we need 4 variables from product page Item Name, Item Price, Item Number and Item Quantity.
//Please Note : People can manipulate hidden field amounts in form,
//In practical world you must fetch actual price from database using item id.
//eg : $ItemPrice = $mysqli->query("SELECT item_price FROM products WHERE id = Product_Number");
$paypal_data ='';
$ItemTotalPrice = 0;
foreach($_POST['item_name'] as $key=>$itmname)
{
$product_code = filter_var($_POST['item_code'][$key], FILTER_SANITIZE_STRING);
$results = $mysqli->query("SELECT product_name, product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
$obj = $results->fetch_object();
$paypal_data .= '&L_PAYMENTREQUEST_0_NAME'.$key.'='.urlencode($obj->product_name);
$paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER'.$key.'='.urlencode($_POST['item_code'][$key]);
$paypal_data .= '&L_PAYMENTREQUEST_0_AMT'.$key.'='.urlencode($obj->price);
$paypal_data .= '&L_PAYMENTREQUEST_0_QTY'.$key.'='. urlencode($_POST['item_qty'][$key]);
// item price X quantity
$subtotal = ($obj->price*$_POST['item_qty'][$key]);
//total price
$ItemTotalPrice = $ItemTotalPrice + $subtotal;
//create items for session
$paypal_product['items'][] = array('itm_name'=>$obj->product_name,
'itm_price'=>$obj->price,
'itm_code'=>$_POST['item_code'][$key],
'itm_qty'=>$_POST['item_qty'][$key]
);
}
//Grand total including all tax, insurance, shipping cost and discount
$GrandTotal = ($ItemTotalPrice + $TotalTaxAmount + $HandalingCost + $InsuranceCost + $ShippinCost + $ShippinDiscount);
$paypal_product['assets'] = array('tax_total'=>$TotalTaxAmount,
'handaling_cost'=>$HandalingCost,
'insurance_cost'=>$InsuranceCost,
'shippin_discount'=>$ShippinDiscount,
'shippin_cost'=>$ShippinCost,
'grand_total'=>$GrandTotal);
//create session array for later use
$_SESSION["paypal_products"] = $paypal_product;
//Parameters for SetExpressCheckout, which will be sent to PayPal
$padata = '&METHOD=SetExpressCheckout'.
'&RETURNURL='.urlencode($PayPalReturnURL ).
'&CANCELURL='.urlencode($PayPalCancelURL).
'&PAYMENTREQUEST_0_PAYMENTACTION='.urlencode("SALE").
$paypal_data.
'&NOSHIPPING=0'. //set 1 to hide buyer's shipping address, in-case products that does not require shipping
'&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice).
'&PAYMENTREQUEST_0_TAXAMT='.urlencode($TotalTaxAmount).
'&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode($ShippinCost).
'&PAYMENTREQUEST_0_HANDLINGAMT='.urlencode($HandalingCost).
'&PAYMENTREQUEST_0_SHIPDISCAMT='.urlencode($ShippinDiscount).
'&PAYMENTREQUEST_0_INSURANCEAMT='.urlencode($InsuranceCost).
'&PAYMENTREQUEST_0_AMT='.urlencode($GrandTotal).
'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&LOCALECODE=GB'. //PayPal pages to match the language on your website.
'&LOGOIMG='. //site logo
'&CARTBORDERCOLOR=FFFFFF'. //border color of cart
'&ALLOWNOTE=1';
//We need to execute the "SetExpressCheckOut" method to obtain paypal token
$paypal= new MyPayPal();
$httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
//Respond according to message we receive from Paypal
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
//Redirect user to PayPal store with Token received.
$paypalurl ='https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='.$httpParsedResponseAr["TOKEN"].'';
header('Location: '.$paypalurl);
}
else
{
//Show error message
echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
}
}
//Paypal redirects back to this page using ReturnURL, We should receive TOKEN and Payer ID
if(isset($_GET["token"]) && isset($_GET["PayerID"]))
{
//we will be using these two variables to execute the "DoExpressCheckoutPayment"
//Note: we haven't received any payment yet.
$token = $_GET["token"];
$payer_id = $_GET["PayerID"];
//get session variables
$paypal_product = $_SESSION["paypal_products"];
$paypal_data = '';
$ItemTotalPrice = 0;
foreach($paypal_product['items'] as $key=>$p_item)
{
$paypal_data .= '&L_PAYMENTREQUEST_0_QTY'.$key.'='. urlencode($p_item['itm_qty']);
$paypal_data .= '&L_PAYMENTREQUEST_0_AMT'.$key.'='.urlencode($p_item['itm_price']);
$paypal_data .= '&L_PAYMENTREQUEST_0_NAME'.$key.'='.urlencode($p_item['itm_name']);
$paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER'.$key.'='.urlencode($p_item['itm_code']);
// item price X quantity
$subtotal = ($p_item['itm_price']*$p_item['itm_qty']);
//total price
$ItemTotalPrice = ($ItemTotalPrice + $subtotal);
}
$padata = '&TOKEN='.urlencode($token).
'&PAYERID='.urlencode($payer_id).
'&PAYMENTREQUEST_0_PAYMENTACTION='.urlencode("SALE").
$paypal_data.
'&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice).
'&PAYMENTREQUEST_0_TAXAMT='.urlencode($paypal_product['assets']['tax_total']).
'&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode($paypal_product['assets']['shippin_cost']).
'&PAYMENTREQUEST_0_HANDLINGAMT='.urlencode($paypal_product['assets']['handaling_cost']).
'&PAYMENTREQUEST_0_SHIPDISCAMT='.urlencode($paypal_product['assets']['shippin_discount']).
'&PAYMENTREQUEST_0_INSURANCEAMT='.urlencode($paypal_product['assets']['insurance_cost']).
'&PAYMENTREQUEST_0_AMT='.urlencode($paypal_product['assets']['grand_total']).
'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode);
//We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
$paypal= new MyPayPal();
$httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
//Check if everything went ok..
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
echo '<h2>Success</h2>';
echo 'Your Transaction ID : '.urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
/*
//Sometimes Payment are kept pending even when transaction is complete.
//hence we need to notify user about it and ask him manually approve the transiction
*/
if('Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"])
{
echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
}
elseif('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"])
{
echo '<div style="color:red">Transaction Complete, but payment is still pending! '.
'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
}
// we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails
// GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut
$padata = '&TOKEN='.urlencode($token);
$paypal= new MyPayPal();
$httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
echo '<br /><b>Stuff to store in database :</b><br />';
echo '<pre>';
/*
#### SAVE BUYER INFORMATION IN DATABASE ###
//see (http://www.sanwebe.com/2013/03/basic-php-mysqli-usage) for mysqli usage
//use urldecode() to decode url encoded strings.
$buyerName = urldecode($httpParsedResponseAr["FIRSTNAME"]).' '.urldecode($httpParsedResponseAr["LASTNAME"]);
$buyerEmail = urldecode($httpParsedResponseAr["EMAIL"]);
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$insert_row = $mysqli->query("INSERT INTO BuyerTable
(BuyerName,BuyerEmail,TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
VALUES ('$buyerName','$buyerEmail','$transactionID','$ItemName',$ItemNumber, $ItemTotalPrice,$ItemQTY)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
*/
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
} else {
echo '<div style="color:red"><b>GetTransactionDetails failed:</b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
}
}else{
echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
}
}
?>
I have set up the Indeed.com xml feed on my site. Their API only allows 25 results per query. How can I paginate the results if there are more than 25?
I have not found a satisfactory or thorough enough answer anywhere online. I've searched for weeks on this.
Here is what I have in my code:
PHP:
// Indeed.com API URL parameters
$url = 'http://api.indeed.com/ads/apisearch'.'?';
$publisher = 'xxxxxxxxxxxxxxxx';
$q = $query;
$location = '';
if (isset($_POST['location'])) {
$location = $_POST['location'];
} else {
$geo = geoCheckIP($_SERVER['REMOTE_ADDR']);
if (isset($geo) && ($geo != "not found, not found")) {
$location = $geo;
}
}
$sort = 'date';
$radius = '20';
$st = '';
$jt = '';
$start = '0';
$limit = '25';
$fromage = '';
$highlight = '0';
$filter = '1';
$latlong = '0';
$co = 'us';
$chnl = '';
$userip = $_SERVER['REMOTE_ADDR'];
$useragent = isset($_SERVER['HTTP_USER_AGENT']) ? ($_SERVER['HTTP_USER_AGENT']) : 'unknown';
$v = '2';
$xml = simplexml_load_file($url."publisher=".$publisher."&q=".$q."&l=".$location."&sort=".$sort."&radius=".$radius."&st=".$st."&jt=".$jt."&start=".$start."&limit=".$limit."&fromage=".$fromage."&highlight=".$highlight."&filter=".$filter."&latlong=".$latlong."&co=".$co."&chnl=".$chnl."&userip=".$userip."&useragent=".$useragent."&v=".$v);
HTML BODY
<div class="paradiv">
<h1><?php echo $xml->totalresults . " " . $jobroll_title . " Near " . $location ?></h1>
<!-- BEGIN INDEED ORDERED LIST-->
<ol class="jobs">
<?php
foreach($xml->results->result as $result) { ?>
<li class="job <?php echo (++$liBgColor%2 ? 'odd' : 'even'); ?>">
<div class="title_wrapper">
<div id="jobtitle"><strong><a onmousedown="<?php echo $result->onmousedown;?>" rel="nofollow" href="<?php echo $result->url;?>" target="_blank"><?php echo $result->jobtitle;?></a></strong></div>
<div id="company"><?php echo $result->company;?></div>
</div>
<div id="snippet">
<?php $result->snippet = str_replace(" ", ". ", $result->snippet); echo $result->snippet;?>
</div>
<div id="location"><strong>Location:</strong> <?php echo $result->formattedLocationFull;?></div>
<div id="date"><span class="posted <?php echo (++$locationBgColor%2 ? 'even' : 'odd'); ?>">Posted <?php echo $result->formattedRelativeTime;?></span></div>
<div id="details-2"><strong><a onmousedown="<?php echo $result->onmousedown;?>" rel="nofollow" href="<?php echo $result->url;?>" target="_blank">Details</a></strong></div>
</li>
<?php } ?>
</ol>
<!-- END INDEED ORDERED LIST -->
<!-- THIS IS WHERE THE PAGINATION WILL DISPLAY -->
<div class="pagenumber"><?php echo "Page Number " . "" . $xml->pageNumber . "" ?></div>
</div>
This is how it works. A user arrives on the web page, then the page loads with the job results based on the users location. If less than 25 results are found for their zip code then there is no problem and pagination isn't needed.
But if the xml feed has more than 25 results, it will show 25 and that's it. If I want to display the rest, I have to paginate. This is what I need help with.
Here is how their API url works.
http://api.indeed.com/ads/apisearch?publisher=xxxxxxxxxxxxxxx&q=java&l=austin%2C+tx&sort=&radius=&st=&jt=&start=0&limit=25&fromage=&filter=&latlong=1&co=us&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2
The part that says &start=0&limit=25 is how to display the results based on page number of the xml.
So for example: &start=0&limit=25 would be page 0 showing 25 results, &start=25&limit=25 would be page 1 showing the next 25 results and &start=50&limit=25 would be page 2 showing the remaining 25 results. This example is based on if there are a total of 75 results in the xml feed.
And in my // Indeed.com API URL parameters above I have it set to start on page 0 and limit to 25. They do not allow beyond 25 in limit. If set higher it will default to 25.
$start = '0';
$limit = '25';
I need some help on implementing a way to paginate using my current PHP code above. How can I add on to what I have in my PHP code?
has_more function returns true if there are 25 results in the xml
$start = 0;
do {
$xml = simplexml_load_file(...$start...);
// process $xml
$start += 25;
} while(has_more($xml));
I have an online store. A products page that allows the user to view a product and add it to the basket. It is added to the basket by clicking "Add to basket" button.
When a user clicks "add to basket", the script redirects them to the basket page and adds the product to the basket.
My question is, how do I print the basket output on the "basket.php" page? How do I pass the session content into variables to be printed?
Thank you.
"products" table in the database:
id int(11), name varchar(255), price int(11)
product.php
...
<form id="basket" name="basket" method="post" action="basket.php">
<input type="hidden" name="p_id" value="<?php echo $id; ?>"/>
<input type="submit" name="submit" value="Add to basket"/>
</form>
...
basket.php
<?php
//add product to cart with product ID passed from previous script
if (isset($_POST["p_id"]))
{
$p_id = $_POST["p_id"];
$q = mysql_query("SELECT * FROM products WHERE id='$p_id'");
$is = mysql_fetch_row($q); $is = $is[0];
$result = "";
while($row = mysql_fetch_array($q)) {
$name = $row["name"];
$price = $row["price"];
$info = $row["info"];
}
$result .= $name .= $price .= $info;
//$_SESSION['p_id'] contains product IDs
//$_SESSION['counts'] contains item quantities
// ($_SESSION['counts'][$i] corresponds to $_SESSION['p_id'][$i])
//$_SESSION['p_id'][$i] == 0 means $i-element is 'empty' (does not refer to any product)
if (!isset($_SESSION["p_id"]))
{
$_SESSION["p_id"] = array();
$_SESSION["counts"] = array();
}
//check for current product in visitor's shopping cart content
$i=0;
while ($i<count($_SESSION["p_id"]) && $_SESSION["p_id"][$i] != $_POST["p_id"]) $i++;
if ($i < count($_SESSION["p_id"])) //increase current product's item quantity
{
$_SESSION["counts"][$i]++;
}
else //no such product in the cart - add it
{
$_SESSION["p_id"][] = $_POST["p_id"];
$_SESSION["counts"][] = 1;
}
}
?>
<div>
<?php echo $result ?>
</div>
create ajax request on button click, to basket.php with GET veriable todo='add_to_basket', witch you will handle in basket.php
HTML of you add product button or link
Your count of product, you will get by Jquery, just type your count html selectors with IDs
<select id="count_<?=$YOUR_PRODUCT_ID?>"></select>
function add_to_basket(product_id){
var product = {};
product['prod_id'] = product_id;
//here you get count of current product
product['count'] = $("count_"+product_id).val();
$.ajax({
type: "GET",
url: "your_domain/basket.php?todo=add_to_basket",
data: "product",
success:function () {
}
});
}
on your basket.php you handle this request like that
if ($GET['todo'] == "add_to_basket"){
// here you add your data(witch comes from ajax) to SESSION
$_SESSION['basket'] [$GET['prod_id']] = $GET['count'];
return true;
}
then when user click on basket image you redirect him to basket page, in wich you display all product in session
<?foreach ($_SESSION['basket'] as $item){?>
// here you get product info by product id from your database and product count from $_SESSION print it to view , price wille be count*price
<?}?>