public function import() { ini_set("auto_detect_line_endings", true); $city_name = $this->city_name; $file_name = $this->csv_file_path; $file_handle = fopen($file_name, "r"); $connection = null; try { $connection = MysqlUtils::getConnection(); } catch (DatabaseConnectionException $e) { echo "Cannot connect to database" . PHP_EOL; exit; } /** * id,area_name,pincode */ $line_number = 0; $header_line = null; while (($line = fgetcsv($file_handle, $file_name)) !== FALSE) { $line_number++; //Skip first line as they are the column headers in excel sheet if ($line_number == 1) { $header_line = $line; continue; } $id = $line[0]; $area_name = $line[1]; $pincode = $line[2]; $query = "INSERT INTO `pincodes` (`id`, `pincode`, `area_name`, `city`) " . "VALUES (NULL, '{$pincode}', '{$area_name}', '{$city_name}')"; $result = mysqli_query($connection, $query); } mysqli_close($connection); }
public static function getConnection() { MysqlUtils::$CONFIG_FILE = ROOT_DIRECTORY . "/config/prod/mysql-config.json"; $config_file = file_get_contents(MysqlUtils::$CONFIG_FILE); $config = json_decode($config_file, TRUE); $host = $config["host"]; $username = $config["username"]; $password = $config["password"]; $database = $config["database"]; $connection = mysqli_connect($host, $username, $password, $database); $error = mysqli_connect_error($connection); if ($error !== NULL) { throw new exceptions\DatabaseConnectionException("Db connection failed"); } return $connection; }
<?php require_once "config.php"; use citibytes\utils\MysqlUtils; use citibytes\LeaderBoard; use citibytes\exceptions\DatabaseConnectionException; use citibytes\exceptions\QueryFailedException; $email_id = $_REQUEST["email_id"]; try { $connection = MysqlUtils::getConnection(); $leader_board = new LeaderBoard($email_id); $result = $leader_board->getLeaderBoardData($connection); $result["status"] = "success"; echo json_encode($result); } catch (DatabaseConnectionException $e) { $failure_json = array("status" => "error", "error" => "Database Unavailable"); echo json_encode($failure_json); return; } catch (QueryFailedException $e) { $failure_json = array("status" => "error", "error" => "Unable to get pending pincode requests"); echo json_encode($failure_json); return; } mysqli_close($connection);