Solved

PHP Script (Make Page Variable Change and Script Loop)

Posted on 2016-09-29
8
51 Views
Last Modified: 2016-09-29
Here is my current Code.  To be clear this script works perfect from the help of Experts on this forum. The remaining thing I need this script to do is change the page number  in $params.   For Example here is the string

$params = array('p'=>27,'withBreweries'=>'Y');        Where p=27 that represent a page number. There are 1154 pages. Each page has an array of 50 values in it. This script right now will copy everything off of that page. However I need it to copy pages 1 -1154 without having to go into this file and change P=1 to p=2 .  So at the end of this script it loops back and changes that variable to 2,3,4 and so fourth. Id appreciate any help or point me in a direction to get this to work. Thanks



 <?php
include ("Brewerydb.php");
echo "
Step 2 GET beers from Brewery DB";

#API*************************************INFO
$apikey = '';

$bdb = new Pintlabs_Service_Brewerydb($apikey);
$bdb->setFormat('php'); 
$params = array('p'=>27,'withBreweries'=>'Y');
$results = array();

#RUNS************************************API
try {
    
// The first argument to request() is the endpoint you want to call
// 'brewery/BrvKTz', 'beers', etc.
// The third parameter is the HTTP method to use (GET, PUT, POST, or DELETE)
    $results = $bdb->request('beers', $params, 'GET'); // where $params is a keyed array of parameters to send with the API call.
} catch (Exception $e) {
    $results = array('error' => $e->getMessage());
}

#DUMPS API******************************RESULTS
var_dump($results);


#MYSQL CONNECTION***********************INFO
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";

// Create MYSQL connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 



#SQL QUERY******************************SETTINGS
foreach($results['data'] as $result){
	
if($result['abv'] == null){
continue;
}
if($result['description'] == null){
continue;
}

  $sql = "INSERT INTO masterbrewlist (BreweryDbId, BeerName,Description,Organic,ABV)
VALUES (
'{$result['id']}',
   '".$conn->real_escape_string ($result['name'])."',
   '".$conn->real_escape_string ($result['description'])."',
   '".$conn->real_escape_string ($result['isOrganic'])."',
   '".$conn->real_escape_string ($result['abv'])."') ON DUPLICATE KEY 
  UPDATE BreweryDbId=BreweryDbId";
   echo 'Processing ' . $result['name'] . '<br />'; 
	  


if ($conn->query($sql) === TRUE) {
echo "New record created successfully <br>";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
}
$conn->close();
?>

Open in new window

0
Comment
Question by:Ray Zuchowski
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 35

Expert Comment

by:Terry Woods
ID: 41822453
To start with, would you rather try working towards putting the repeated code into a function, or would you rather have just one really long loop around the whole lot? A function is neater, but a little more effort.
0
 

Author Comment

by:Ray Zuchowski
ID: 41822457
Hey Terry : )

Well function would be nice but it was messing up the API on this line earlier.

 $results = $bdb->request('beers', $params, 'GET'); // where $params is a keyed array of parameters to send with the API call.

I think in the end if its possible to just do a longer loop if its easier, id prefer that.
0
 
LVL 35

Accepted Solution

by:
Terry Woods earned 500 total points
ID: 41822478
Ok, lets do just the loop then. If you want to tidy up the code later, it could have it's own separate question. Try this. Some stuff has been re-ordered to move it out of the loop. I've temporarily limited it to 60 pages, starting from page 1.

 <?php
include ("Brewerydb.php");
echo "
Step 2 GET beers from Brewery DB";

#MYSQL CONNECTION***********************INFO
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";

// Create MYSQL connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

#API*************************************INFO
$apikey = '';

$bdb = new Pintlabs_Service_Brewerydb($apikey);
$bdb->setFormat('php'); 
$results = array();

$page = 1; #counter for which page to get
while (true) { #will break out of the loop when needed
$params = array('p'=>$page,'withBreweries'=>'Y');
$page++; # increment ready for next iteration of the loop
if ($page > 60) { break; } #TODO: prevent infinite loops during testing... review this logic before go-live

#RUNS************************************API
try {
    
// The first argument to request() is the endpoint you want to call
// 'brewery/BrvKTz', 'beers', etc.
// The third parameter is the HTTP method to use (GET, PUT, POST, or DELETE)
    $results = $bdb->request('beers', $params, 'GET'); // where $params is a keyed array of parameters to send with the API call.
} catch (Exception $e) {
    $results = array('error' => $e->getMessage());
    break; # exit the while loop
}


#DUMPS API******************************RESULTS
var_dump($results);


#SQL QUERY******************************SETTINGS
foreach($results['data'] as $result){
	
if($result['abv'] == null){
continue;
}
if($result['description'] == null){
continue;
}

  $sql = "INSERT INTO masterbrewlist (BreweryDbId, BeerName,Description,Organic,ABV)
VALUES (
'{$result['id']}',
   '".$conn->real_escape_string ($result['name'])."',
   '".$conn->real_escape_string ($result['description'])."',
   '".$conn->real_escape_string ($result['isOrganic'])."',
   '".$conn->real_escape_string ($result['abv'])."') ON DUPLICATE KEY 
  UPDATE BreweryDbId=BreweryDbId";
   echo 'Processing ' . $result['name'] . '<br />'; 
	  


if ($conn->query($sql) === TRUE) {
echo "New record created successfully <br>";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
}

} #end while loop
$conn->close();

?>

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 35

Expert Comment

by:Terry Woods
ID: 41822485
It would be worth you fixing up the indentation to help show where loops start and end... some text editors do that automatically, so it usually isn't difficult. You just need to watch for multiline strings that might be actually part of data, in which case indentation can sometimes be added to the data by mistake.
0
 

Author Comment

by:Ray Zuchowski
ID: 41822504
Terry you are coding genious. Thanks brother. Where can I put the pause command so I don't flood there server ?
0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 41822525
You mean like a sleep(5) to slow down each iteration of the loop? Just after the try-catch block would be suitable.
0
 

Author Comment

by:Ray Zuchowski
ID: 41822529
sweet thanks dude. You are the man.
0
 

Author Closing Comment

by:Ray Zuchowski
ID: 41822531
Awesome
0

Featured Post

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
MySQL stored procedure returning null values 4 36
A responsive image gallery using flexbox 6 76
Change Wording in Wordpress Plugin 4 38
How do I add date to text file name 15 28
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
This article discusses how to implement server side field validation and display customized error messages to the client.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question