Solved

PHP Script (Make Page Variable Change and Script Loop)

Posted on 2016-09-29
8
41 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
  • 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

785 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