Solved

PHP Script (Make Page Variable Change and Script Loop)

Posted on 2016-09-29
8
34 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 35

Expert Comment

by:Terry Woods
Comment Utility
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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:Ray Zuchowski
Comment Utility
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
Comment Utility
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
Comment Utility
sweet thanks dude. You are the man.
0
 

Author Closing Comment

by:Ray Zuchowski
Comment Utility
Awesome
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

743 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now