Solved

PHP Script (Make Page Variable Change and Script Loop)

Posted on 2016-09-29
8
54 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
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

This article discusses four methods for overlaying images in a container on a web page
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
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…

623 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