Skip to content

Instantly share code, notes, and snippets.

@RSquaredSoftware
Last active December 28, 2015 11:28
Show Gist options
  • Save RSquaredSoftware/7493246 to your computer and use it in GitHub Desktop.
Save RSquaredSoftware/7493246 to your computer and use it in GitHub Desktop.
<?php
// Establishes a connection to the database
function connect(&$dbh) {
$auth = include("auth.php");
$dbName = "DNC";
try {
$dbh = new PDO($auth['server'], $auth['user'], $auth['password']);
}
catch (PDOException $e) {
die('Connection authorization failed: ' . $e->getMessage());
}
try {
$sth = $dbh->prepare("USE $dbName");
$sth->execute();
}
catch (PDOException $e) {
die('Cannot locate database on server: ' . $e->getMessage());
}
}
// Returns the top 1000
function getNumbers() {
connect($dbh);
try {
$sth = $dbh->prepare("SELECT * FROM DNC_LIST LIMIT 1000");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $e) {
die("Query failed: ". $e->getMessage());
}
return $result;
}
// Takes an array of DNC numbers and inserts them into the DNC_LIST table
function insertNumbers(array $numbers) {
connect($dbh);
$dbh->beginTransaction();
$sql = "INSERT INTO DNC_LIST (NUMBER) VALUES (" . implode("),(", $numbers).")";
try {
$sth = $dbh->prepare($sql);
$sth->execute();
}
catch (PDOException $e) {
$dbh->rollBack();
die("Query failed at number: " . $numbers[0] . ". Error: " . $e->getMessage());
}
$dbh->commit();
}
// Opens $filename and reads in some number of lines into an array and then performs
// insertNumbers() on them. This breaks up the inserts, making the process safer
function loadNumbers($filename) {
$fileHandle = fopen($filename);
if(!$fileHandle) {
die("Could not open DNC numbers file.");
}
$numbers = array();
// track the number of rows read
$i = 0;
while(!feof($fileHandle)) {
array_push($numbers, fgets($fileHandle));
$i++;
// Periodically, insert the data and clear the array
if ($i % 10000 == 0) {
insertNumbers($numbers);
//$numbers = [];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment