I am trying to modify a class that I found that is a Steam API class. I want it to work with codeigniter. I keep getting the error in the question title when I call the getProfileData function. Not sure why it's happening. Here is the code:
The library:
<?php
// Disable XML warnings to avoid problems when SteamCommunity is down
libxml_use_internal_errors(true);
// Use SteamUtility to fetch URLs and other stuff
require_once 'SteamUtility.php';
/**
* SteamUser - Representation of any Steam user profile
*
* #category SteamAPI
* #copyright Copyright (c) 2012 Matt Ryder (www.mattryder.co.uk)
* #license GPLv2 License
* #version v1.3
* #link https://github.com/MattRyder/SteamAPI/blob/master/steam/SteamUser.php
* #since Class available since v1.0
*/
class SteamUser {
private $userID;
private $vanityURL;
private $apiKey;
public $info;
/**
* Constructor
* #param mixed $id User's steamID or vanityURL
* #param string $apiKey API key for http://steamcommunity.com/dev/
*/
/**
* GetProfileData
* - Accesses Steam Profile XML and parses the data
*/
function __construct($params){
$userId = $params['userId'];
$this->CI =& get_instance();
$this->CI->load->config('steam');
if(empty($userId)) {
echo "Error: No Steam ID or URL given!", PHP_EOL;
return NULL;
}
if(is_numeric($userId)) {
$this->userID = $userId;
}
else {
$this->vanityURL = strtolower($userId);
}
$this->apiKey = $this->CI->config->item('api_key');
}
function getProfileData() {
$info = array();
//Set Base URL for the query:
if(empty($this->vanityURL)) {
$base = "http://steamcommunity.com/profiles/{$this->userId}/?xml=1";
} else {
$base = "http://steamcommunity.com/id/{$this->vanityURL}/?xml=1";
}
try {
$content = SteamUtility::fetchURL($base);
if ($content) {
$parsedData = new SimpleXMLElement($content);
} else {
return null;
}
} catch (Exception $e) {
//echo "Whoops! Something went wrong!\n\nException Info:\n" . $e . "\n\n";
return null;
}
if(!empty($parsedData)) {
$info['steamID64'] = (string)$parsedData->steamID64;
$info['steamID'] = (string)$parsedData->steamID;
$info['stateMessage'] = (string)$parsedData->stateMessage;
$info['visibilityState'] = (int)$parsedData->visibilityState;
$info['privacyState'] = (string)$parsedData->privacyState;
$info['avatarIcon'] = (string)$parsedData->avatarIcon;
$info['avatarMedium'] = (string)$parsedData->avatarMedium;
$info['avatarFull'] = (string)$parsedData->avatarFull;
$info['vacBanned'] = (int)$parsedData->vacBanned;
$info['tradeBanState'] = (string)$parsedData->tradeBanState;
$info['isLimitedAccount'] = (string)$parsedData->isLimitedAccount;
$info['onlineState'] = (string)$parsedData->onlineState;
$info['inGameServerIP'] = (string)$parsedData->inGameServerIP;
//If their account is public, get that info:
if($info['privacyState'] == "public") {
$info['customURL'] = (string)$parsedData->customURL;
$info['memberSince'] = (string)$parsedData->memberSince;
$info['steamRating'] = (float)$parsedData->steamRating;
$info['hoursPlayed2Wk'] = (float)$parsedData->hoursPlayed2Wk;
$info['headline'] = (string)$parsedData->headline;
$info['location'] = (string)$parsedData->location;
$info['realname'] = (string)$parsedData->realname;
$info['summary'] = (string)$parsedData->summary;
}
//If they're in a game, grab that info:
if($info['onlineState'] == "in-game") {
$info['inGameInfo']['inGameInfo'] = array();
$info['inGameInfo']["gameName"] = (string)$parsedData->inGameInfo->gameName;
$info['inGameInfo']["gameLink"] = (string)$parsedData->inGameInfo->gameLink;
$info['inGameInfo']["gameIcon"] = (string)$parsedData->inGameInfo->gameIcon;
$info['inGameInfo']["gameLogo"] = (string)$parsedData->inGameInfo->gameLogo;
$info['inGameInfo']["gameLogoSmall"] = (string)$parsedData->inGameInfo->gameLogoSmall;
}
//Get their most played video games:
if(!empty($parsedData->mostPlayedGames)) {
$info['mostPlayedGames'] = array();
$i = 0;
foreach ($parsedData->mostPlayedGames->mostPlayedGame as $mostPlayedGame) {
$info['mostPlayedGames'][$i] = new stdClass();
$info['mostPlayedGames'][$i]['gameName'] = (string)$mostPlayedGame->gameName;
$info['mostPlayedGames'][$i]['gameLink'] = (string)$mostPlayedGame->gameLink;
$info['mostPlayedGames'][$i]['gameIcon'] = (string)$mostPlayedGame->gameIcon;
$info['mostPlayedGames'][$i]['gameLogo'] = (string)$mostPlayedGame->gameLogo;
$info['mostPlayedGames'][$i]['gameLogoSmall'] = (string)$mostPlayedGame->gameLogoSmall;
$info['mostPlayedGames'][$i]['hoursPlayed'] = (string)$mostPlayedGame->hoursPlayed;
$info['mostPlayedGames'][$i]['hoursOnRecord'] = (string)$mostPlayedGame->hoursOnRecord;
$info['mostPlayedGames'][$i]['statsName'] = (string)$mostPlayedGame->statsName;
$i++;
}
}
//Any weblinks listed in their profile:
if(!empty($parsedData->weblinks)) {
$this['weblinks'] = array();
$i = 0;
foreach ($parsedData->weblinks->weblink as $weblink) {
$info['weblinks'][$i]['title'] = (string)$weblink->title;
$info['weblinks'][$i]['link'] = (string)$weblink->link;
$i++;
}
}
//And grab any subscribed groups:
if(!empty($parsedData->groups)) {
$this->groups = array();
$i = 0;
foreach ($parsedData->groups->group as $group) {
$info['groups'][$i] = array();
$info['groups'][$i]['groupID64'] = (string)$group->groupID64;
$info['groups'][$i]['groupName'] = (string)$group->groupName;
$info['groups'][$i]['groupURL'] = (string)$group->groupURL;
$info['groups'][$i]['headline'] = (string)$group->headline;
$info['groups'][$i]['summary'] = (string)$group->summary;
$info['groups'][$i]['avatarIcon'] = (string)$group->avatarIcon;
$info['groups'][$i]['avatarMedium'] = (string)$group->avatarMedium;
$info['groups'][$i]['avatarFull'] = (string)$group->avatarFull;
$info['groups'][$i]['memberCount'] = (string)$group->memberCount;
$info['groups'][$i]['membersInChat'] = (string)$group->membersInChat;
$info['groups'][$i]['membersInGame'] = (string)$group->membersInGame;
$info['groups'][$i]['membersOnline'] = (string)$group->membersOnline;
$i++;
}
}
}
return $info;
}
My model where I call it:
function retrieve($member_id = 0){
$info = array();
$this->db->select('memberId AS id, facebookId, steamId, userName, emailAddress, dateJoined, dateBorn')
->from('members')
->where('memberId', $member_id)
->limit(1);
if($query = $this->db->get()){
if($query->num_rows() > 0){
$member = $query->row_array();
var_dump($member);
$info = $member;
if($member['steamId'] != ''){
$this->load->library('SteamUser', array('userId' => $member['steamId']));
$steam = $this->SteamUser->getProfileData();
$info['steam'] = array(
'id' => $member['steamId'],
'avatar' => $steam['avatarIcon']
);
}
}
}
$this->info = $info;
}
Dumping the $member variable returns this:
array (size=7)
'id' => string '11' (length=2)
'facebookId' => string '' (length=0)
'steamId' => string 'STEAM_0:1:000000000' (length=17)
'userName' => string 'John Smith' (length=18)
'emailAddress' => string '' (length=0)
'dateJoined' => string '2015-09-23 19:38:17' (length=19)
'dateBorn' => string '0000-00-00 00:00:00' (length=19)
Try these methods
print_r($member['steamId']); to check data is empty or not.
If you passing data as objective array, then you need to access data with pointing [0],
ex: $this->SteamUser->getProfileData($member[0]['steamId']);
Check aging with print_r
print_r($member[0]['steamId']);
So final code will be
print_r($member['steamId']);//check data exist
print_r($member[0]['steamId']);//check data exist
if($member['steamId'])
{
$this->load->library('SteamUser');
$this->SteamUser->getProfileData($member['steamId']);
$steam = array('id' => $member['steamId'], 'avatar' => $this->SteamUser->avatarIcon);
$info = array_merge($info, $steam);
}
Apparently, when you load a class with CodeIgniter, the name of the object that is given is all lower case. So I was loading $this->SteamUser->getProfileData() when I should have been doing it like $this->steamuser->getProfileData().
Related
We have several GPS installed in different units and I am trying to retrieve the messages using the Wialon's Remote API but i am getting this error, can someone please help me? Thanks a lot!:
{"error":4, "reason":"VALIDATE_PARAMS_ERROR: {itemId: long, timeFrom: uint, timeTo: uint, flags: uint, flagsMask: uint, loadCount: uint}"}
Below is my script:
<?php
include('wialon.php');
$wialon_api = new Wialon();
$token = '{token here}';
$result = $wialon_api->login($token);
$json = json_decode($result, true);
if(!isset($json['error'])){
echo $wialon_api->messages_load_interval('{"itemId":24611387,"lastTime":1073741831,"lastCount":1,"flags":0,"flagMask":0,"loadCount":1}');
$wialon_api->logout();
} else {
echo WialonError::error($json['error']);
}
?>
Here is the Wialon Class which i downloaded from their site:
<?php
/* Classes for working with Wialon RemoteApi using PHP
*
* License:
* The MIT License (MIT)
*
* Copyright:
* 2002-2015 Gurtam, http://gurtam.com
*/
/** Wialon RemoteApi wrapper Class
*/
class Wialon{
/// PROPERTIES
private $sid = null;
private $base_api_url = '';
private $default_params = array();
/// METHODS
/** constructor */
function __construct($scheme = 'https', $host = 'hst-api.wialon.com', $port = '', $sid = '', $extra_params = array()) {
$this->sid = '';
$this->default_params = array_replace(array(), (array)$extra_params);
$this->base_api_url = sprintf('%s://%s%s/wialon/ajax.html?', $scheme, $host, mb_strlen($port)>0?':'.$port:'');
}
/** sid setter */
function set_sid($sid){
$this->sid = $sid;
}
/** sid getter */
function get_sid(){
return $this->sid;
}
/** update extra parameters */
public function update_extra_params($extra_params){
$this->default_params = array_replace($this->default_params, $extra_params);
}
/** RemoteAPI request performer
* action - RemoteAPI command name
* args - JSON string with request parameters
*/
public function call($action, $args){
$url = $this->base_api_url;
if (stripos($action, 'unit_group') === 0) {
$svc = $action;
$svc[mb_strlen('unit_group')] = '/';
} else {
$svc = preg_replace('\'_\'', '/', $action, 1);
}
$params = array(
'svc'=> $svc,
'params'=> $args,
'sid'=> $this->sid
);
$all_params = array_replace($this->default_params , $params);
$str = '';
foreach ($all_params as $k => $v) {
if(mb_strlen($str)>0)
$str .= '&';
$str .= $k.'='.urlencode(is_object($v) || is_array($v) ? json_encode($v) : $v);
}
/* cUrl magic */
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $str
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if($result === FALSE)
$result = '{"error":-1,"message":'.curl_error($ch).'}';
curl_close($ch);
return $result;
}
/** Login
* user - wialon username
* password - password
* return - server response
*/
public function login($token) {
$data = array(
'token' => urlencode($token),
);
$result = $this->token_login(json_encode($data));
$json_result = json_decode($result, true);
if(isset($json_result['eid'])) {
$this->sid = $json_result['eid'];
}
return $result;
}
/** Logout
* return - server responce
*/
public function logout() {
$result = $this->core_logout();
$json_result = json_decode($result, true);
if($json_result && $json_result['error']==0)
$this->sid = '';
return $result;
}
/** Unknonwn methods hadler */
public function __call($name, $args) {
return $this->call($name, count($args) === 0 ? '{}' : $args[0]);
}
}
/** Wialon errorCode to textMessage converter
*/
class WialonError{
/// PROPERTIES
/** list of error messages with codes */
public static $errors = array(
1 => 'Invalid session',
2 => 'Invalid service',
3 => 'Invalid result',
4 => 'Invalid input',
5 => 'Error performing request',
6 => 'Unknow error',
7 => 'Access denied',
8 => 'Invalid user name or password',
9 => 'Authorization server is unavailable, please try again later',
1001 => 'No message for selected interval',
1002 => 'Item with such unique property already exists',
1003 => 'Only one request of given time is allowed at the moment'
);
/// METHODS
/** error message generator */
public static function error($code = '', $text = ''){
$code = intval($code);
if ( isset(self::$errors[$code]) )
$text = self::$errors[$code].' '.$text;
$message = sprintf('%d: %s', $code, $text);
return sprintf('WialonError( %s )', $message);
}
}
?>
I have problem with a WebService function for moodle callen "mod_scorm_insert_scorm_tracks"
This function is used for inserting track information (i.e. star time) of a user in his SCORM progress.
Part of the estructure of this function is
scoid= int
attempt= int
tracks[0][element]= string
tracks[0][value]= string
NEW
PHP structe has to look like this
[tracks] =>
Array
(
[0] =>
Array
(
[element] => string
[value] => string
)
)
I have used one of the examples they had in his website everything was fine until I got this error
<b>Notice</b>: Array to string conversion in <b>C:\xampp\htdocs\otros\PHP-REST\curl.php</b> on line <b>247</b><br />
<?xml version="1.0" encoding="UTF-8" ?>
<EXCEPTION class="invalid_parameter_exception">
<ERRORCODE>invalidparameter</ERRORCODE>
<MESSAGE>Invalid parameter value detected</MESSAGE>
<DEBUGINFO>tracks => Invalid parameter value detected: Only arrays accepted. The bad value is: 'Array'</DEBUGINFO>
</EXCEPTION>
And the problem seems to be here:
$item1 = new stdClass();
$item1->scoid = '2';
$item1->attempt = '1';
$item1->tracks = array(
array(
array(
'element' => 'x.start.time',
'value' => '1473102672'
),
),
array(
array(
'element' => 'x.start.time',
'value' => '1473102680'
),
),
);
I tried in many ways
$item1 = new stdClass();
$item1->scoid = '2';
$item1->attempt = '1';
$item1->tracks = array('element' => 'x.start.time','value' => '1473102672');
or
$item1 = new stdClass();
$item1->scoid = '2';
$item1->attempt = '1';
$item1->tracks = array(array ('element' => 'x.start.time','value' => '1473102672'));
And still getting the same message, I'm pretty that is problema with my wyntax but I have tried in many ways and still not working I hope yo can help me.
Complete Code:
/// SETUP - NEED TO BE CHANGED
$token = '481bf3d85a7eb539e37eabc88feccb3c';
$domainname = 'http://localhost/moodle';
//$functionname = 'mod_scorm_launch_sco';
$functionname = 'mod_scorm_insert_scorm_tracks';
//$functionname ='mod_scorm_view_scorm';
// REST RETURNED VALUES FORMAT
$restformat = 'xml'; //Also possible in Moodle 2.2 and later: 'json'
//Setting it to 'json' will fail all calls on earlier Moodle version
$item1 = new stdClass();
$item1->scoid = '2';
$item1->attempt = '1';
$item1->tracks = array(
array(
array(
'element' => 'x.start.time',
'value' => 1473102672
),
),
array(
array(
'element' => 'x.start.time',
'value' => 1473102680
),
),
);
$params = $item1;
/// REST CALL
header('Content-Type: text/plain');
$serverurl = $domainname . '/webservice/rest/server.php'. '?wstoken=' . $token . '&wsfunction='.$functionname;
require_once('./curl.php');
$curl = new curl;
//if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->post($serverurl . $restformat, $params);
print_r($resp);
curl.php
<?php
/**
* cURL class
*
* This is a wrapper class for curl, it is quite easy to use:
* <code>
* $c = new curl;
* // enable cache
* $c = new curl(array('cache'=>true));
* // enable cookie
* $c = new curl(array('cookie'=>true));
* // enable proxy
* $c = new curl(array('proxy'=>true));
*
* // HTTP GET Method
* $html = $c->get('http://example.com');
* // HTTP POST Method
* $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
* // HTTP PUT Method
* $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
* </code>
*
* #author Dongsheng Cai <dongsheng#moodle.com> - https://github.com/dongsheng/cURL
* #license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
class curl {
/** #var bool */
public $cache = false;
public $proxy = false;
/** #var array */
public $response = array();
public $header = array();
/** #var string */
public $info;
public $error;
/** #var array */
private $options;
/** #var string */
private $proxy_host = '';
private $proxy_auth = '';
private $proxy_type = '';
/** #var bool */
private $debug = false;
private $cookie = false;
private $count = 0;
/**
* #param array $options
*/
public function __construct($options = array()){
if (!function_exists('curl_init')) {
$this->error = 'cURL module must be enabled!';
trigger_error($this->error, E_USER_ERROR);
return false;
}
// the options of curl should be init here.
$this->resetopt();
if (!empty($options['debug'])) {
$this->debug = true;
}
if(!empty($options['cookie'])) {
if($options['cookie'] === true) {
$this->cookie = 'curl_cookie.txt';
} else {
$this->cookie = $options['cookie'];
}
}
if (!empty($options['cache'])) {
if (class_exists('curl_cache')) {
$this->cache = new curl_cache();
}
}
}
/**
* Resets the CURL options that have already been set
*/
public function resetopt(){
$this->options = array();
$this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
// True to include the header in the output
$this->options['CURLOPT_HEADER'] = 0;
// True to Exclude the body from the output
$this->options['CURLOPT_NOBODY'] = 0;
// TRUE to follow any "Location: " header that the server
// sends as part of the HTTP header (note this is recursive,
// PHP will follow as many "Location: " headers that it is sent,
// unless CURLOPT_MAXREDIRS is set).
//$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
$this->options['CURLOPT_MAXREDIRS'] = 10;
$this->options['CURLOPT_ENCODING'] = '';
// TRUE to return the transfer as a string of the return
// value of curl_exec() instead of outputting it out directly.
$this->options['CURLOPT_RETURNTRANSFER'] = 1;
$this->options['CURLOPT_BINARYTRANSFER'] = 0;
$this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
$this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
$this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
}
/**
* Reset Cookie
*/
public function resetcookie() {
if (!empty($this->cookie)) {
if (is_file($this->cookie)) {
$fp = fopen($this->cookie, 'w');
if (!empty($fp)) {
fwrite($fp, '');
fclose($fp);
}
}
}
}
/**
* Set curl options
*
* #param array $options If array is null, this function will
* reset the options to default value.
*
*/
public function setopt($options = array()) {
if (is_array($options)) {
foreach($options as $name => $val){
if (stripos($name, 'CURLOPT_') === false) {
$name = strtoupper('CURLOPT_'.$name);
}
$this->options[$name] = $val;
}
}
}
/**
* Reset http method
*
*/
public function cleanopt(){
unset($this->options['CURLOPT_HTTPGET']);
unset($this->options['CURLOPT_POST']);
unset($this->options['CURLOPT_POSTFIELDS']);
unset($this->options['CURLOPT_PUT']);
unset($this->options['CURLOPT_INFILE']);
unset($this->options['CURLOPT_INFILESIZE']);
unset($this->options['CURLOPT_CUSTOMREQUEST']);
}
/**
* Set HTTP Request Header
*
* #param array $headers
*
*/
public function setHeader($header) {
if (is_array($header)){
foreach ($header as $v) {
$this->setHeader($v);
}
} else {
$this->header[] = $header;
}
}
/**
* Set HTTP Response Header
*
*/
public function getResponse(){
return $this->response;
}
/**
* private callback function
* Formatting HTTP Response Header
*
* #param mixed $ch Apparently not used
* #param string $header
* #return int The strlen of the header
*/
private function formatHeader($ch, $header)
{
$this->count++;
if (strlen($header) > 2) {
list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
$key = rtrim($key, ':');
if (!empty($this->response[$key])) {
if (is_array($this->response[$key])){
$this->response[$key][] = $value;
} else {
$tmp = $this->response[$key];
$this->response[$key] = array();
$this->response[$key][] = $tmp;
$this->response[$key][] = $value;
}
} else {
$this->response[$key] = $value;
}
}
return strlen($header);
}
/**
* Set options for individual curl instance
*
* #param object $curl A curl handle
* #param array $options
* #return object The curl handle
*/
private function apply_opt($curl, $options) {
// Clean up
$this->cleanopt();
// set cookie
if (!empty($this->cookie) || !empty($options['cookie'])) {
$this->setopt(array('cookiejar'=>$this->cookie,
'cookiefile'=>$this->cookie
));
}
// set proxy
if (!empty($this->proxy) || !empty($options['proxy'])) {
$this->setopt($this->proxy);
}
$this->setopt($options);
// reset before set options
curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
// set headers
if (empty($this->header)){
$this->setHeader(array(
'User-Agent: MoodleBot/1.0',
'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Connection: keep-alive'
));
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
if ($this->debug){
echo '<h1>Options</h1>';
var_dump($this->options);
echo '<h1>Header</h1>';
var_dump($this->header);
}
// set options
foreach($this->options as $name => $val) {
if (is_string($name)) {
$name = constant(strtoupper($name));
}
curl_setopt($curl, $name, $val);
}
return $curl;
}
/**
* Download multiple files in parallel
*
* Calls {#link multi()} with specific download headers
*
* <code>
* $c = new curl;
* $c->download(array(
* array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
* array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
* ));
* </code>
*
* #param array $requests An array of files to request
* #param array $options An array of options to set
* #return array An array of results
*/
public function download($requests, $options = array()) {
$options['CURLOPT_BINARYTRANSFER'] = 1;
$options['RETURNTRANSFER'] = false;
return $this->multi($requests, $options);
}
/*
* Mulit HTTP Requests
* This function could run multi-requests in parallel.
*
* #param array $requests An array of files to request
* #param array $options An array of options to set
* #return array An array of results
*/
protected function multi($requests, $options = array()) {
$count = count($requests);
$handles = array();
$results = array();
$main = curl_multi_init();
for ($i = 0; $i < $count; $i++) {
$url = $requests[$i];
foreach($url as $n=>$v){
$options[$n] = $url[$n];
}
$handles[$i] = curl_init($url['url']);
$this->apply_opt($handles[$i], $options);
curl_multi_add_handle($main, $handles[$i]);
}
$running = 0;
do {
curl_multi_exec($main, $running);
} while($running > 0);
for ($i = 0; $i < $count; $i++) {
if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
$results[] = true;
} else {
$results[] = curl_multi_getcontent($handles[$i]);
}
curl_multi_remove_handle($main, $handles[$i]);
}
curl_multi_close($main);
return $results;
}
/**
* Single HTTP Request
*
* #param string $url The URL to request
* #param array $options
* #return bool
*/
protected function request($url, $options = array()){
// create curl instance
$curl = curl_init($url);
$options['url'] = $url;
$this->apply_opt($curl, $options);
if ($this->cache && $ret = $this->cache->get($this->options)) {
return $ret;
} else {
$ret = curl_exec($curl);
if ($this->cache) {
$this->cache->set($this->options, $ret);
}
}
$this->info = curl_getinfo($curl);
$this->error = curl_error($curl);
if ($this->debug){
echo '<h1>Return Data</h1>';
var_dump($ret);
echo '<h1>Info</h1>';
var_dump($this->info);
echo '<h1>Error</h1>';
var_dump($this->error);
}
curl_close($curl);
if (empty($this->error)){
return $ret;
} else {
return $this->error;
// exception is not ajax friendly
//throw new moodle_exception($this->error, 'curl');
}
}
/**
* HTTP HEAD method
*
* #see request()
*
* #param string $url
* #param array $options
* #return bool
*/
public function head($url, $options = array()){
$options['CURLOPT_HTTPGET'] = 0;
$options['CURLOPT_HEADER'] = 1;
$options['CURLOPT_NOBODY'] = 1;
return $this->request($url, $options);
}
/**
* Recursive function formating an array in POST parameter
* #param array $arraydata - the array that we are going to format and add into &$data array
* #param string $currentdata - a row of the final postdata array at instant T
* when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
* #param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
*/
function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
foreach ($arraydata as $k=>$v) {
$newcurrentdata = $currentdata;
if (is_object($v)) {
$v = (array) $v;
}
if (is_array($v)) { //the value is an array, call the function recursively
$newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
$this->format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
} else { //add the POST parameter to the $data array
$data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
}
}
}
/**
* Transform a PHP array into POST parameter
* (see the recursive function format_array_postdata_for_curlcall)
* #param array $postdata
* #return array containing all POST parameters (1 row = 1 POST parameter)
*/
function format_postdata_for_curlcall($postdata) {
if (is_object($postdata)) {
$postdata = (array) $postdata;
}
$data = array();
foreach ($postdata as $k=>$v) {
if (is_object($v)) {
$v = (array) $v;
}
if (is_array($v)) {
$currentdata = urlencode($k);
$this->format_array_postdata_for_curlcall($v, $currentdata, $data);
} else {
$data[] = urlencode($k).'='.urlencode($v);
}
}
$convertedpostdata = implode('&', $data);
return $convertedpostdata;
}
/**
* HTTP POST method
*
* #param string $url
* #param array|string $params
* #param array $options
* #return bool
*/
public function post($url, $params = '', $options = array()){
$options['CURLOPT_POST'] = 1;
if (is_array($params)) {
$params = $this->format_postdata_for_curlcall($params);
}
$options['CURLOPT_POSTFIELDS'] = $params;
return $this->request($url, $options);
}
/**
* HTTP GET method
*
* #param string $url
* #param array $params
* #param array $options
* #return bool
*/
public function get($url, $params = array(), $options = array()){
$options['CURLOPT_HTTPGET'] = 1;
if (!empty($params)){
$url .= (stripos($url, '?') !== false) ? '&' : '?';
$url .= http_build_query($params, '', '&');
}
return $this->request($url, $options);
}
/**
* HTTP PUT method
*
* #param string $url
* #param array $params
* #param array $options
* #return bool
*/
public function put($url, $params = array(), $options = array()){
$file = $params['file'];
if (!is_file($file)){
return null;
}
$fp = fopen($file, 'r');
$size = filesize($file);
$options['CURLOPT_PUT'] = 1;
$options['CURLOPT_INFILESIZE'] = $size;
$options['CURLOPT_INFILE'] = $fp;
if (!isset($this->options['CURLOPT_USERPWD'])){
$this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply#moodle.org'));
}
$ret = $this->request($url, $options);
fclose($fp);
return $ret;
}
/**
* HTTP DELETE method
*
* #param string $url
* #param array $params
* #param array $options
* #return bool
*/
public function delete($url, $param = array(), $options = array()){
$options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
if (!isset($options['CURLOPT_USERPWD'])) {
$options['CURLOPT_USERPWD'] = 'anonymous: noreply#moodle.org';
}
$ret = $this->request($url, $options);
return $ret;
}
/**
* HTTP TRACE method
*
* #param string $url
* #param array $options
* #return bool
*/
public function trace($url, $options = array()){
$options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
$ret = $this->request($url, $options);
return $ret;
}
/**
* HTTP OPTIONS method
*
* #param string $url
* #param array $options
* #return bool
*/
public function options($url, $options = array()){
$options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
$ret = $this->request($url, $options);
return $ret;
}
public function get_info() {
return $this->info;
}
}
/**
* This class is used by cURL class, use case:
*
* <code>
*
* $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
* $ret = $c->get('http://www.google.com');
* </code>
*
* #package core
* #subpackage file
* #copyright 1999 onwards Martin Dougiamas {#link http://moodle.com}
* #license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class curl_cache {
/** #var string */
public $dir = '';
/**
*
* #param string #module which module is using curl_cache
*
*/
function __construct() {
$this->dir = '/tmp/';
if (!file_exists($this->dir)) {
mkdir($this->dir, 0700, true);
}
$this->ttl = 1200;
}
/**
* Get cached value
*
* #param mixed $param
* #return bool|string
*/
public function get($param){
$this->cleanup($this->ttl);
$filename = 'u_'.md5(serialize($param));
if(file_exists($this->dir.$filename)) {
$lasttime = filemtime($this->dir.$filename);
if(time()-$lasttime > $this->ttl)
{
return false;
} else {
$fp = fopen($this->dir.$filename, 'r');
$size = filesize($this->dir.$filename);
$content = fread($fp, $size);
return unserialize($content);
}
}
return false;
}
/**
* Set cache value
*
* #param mixed $param
* #param mixed $val
*/
public function set($param, $val){
$filename = 'u_'.md5(serialize($param));
$fp = fopen($this->dir.$filename, 'w');
fwrite($fp, serialize($val));
fclose($fp);
}
/**
* Remove cache files
*
* #param int $expire The number os seconds before expiry
*/
public function cleanup($expire){
if($dir = opendir($this->dir)){
while (false !== ($file = readdir($dir))) {
if(!is_dir($file) && $file != '.' && $file != '..') {
$lasttime = #filemtime($this->dir.$file);
if(time() - $lasttime > $expire){
#unlink($this->dir.$file);
}
}
}
}
}
/**
* delete current user's cache file
*
*/
public function refresh(){
if($dir = opendir($this->dir)){
while (false !== ($file = readdir($dir))) {
if(!is_dir($file) && $file != '.' && $file != '..') {
if(strpos($file, 'u_')!==false){
#unlink($this->dir.$file);
}
}
}
}
}
}
Thanks!
Well after some research I finally took plan B
I wrote tracks in a different variable:
$tracks = array();
$tracks[] = array(
'element' => 'cmi.core.lesson_status',
'value' => 'completed'
);
And I followed curl.php array set option:
$arrayName = array('' => , );
Then when I inserted scoid and attemps as single variables in the array:
$params = array('scoid' => '2', 'attempt' => '1', 'tracks' => $tracks);
and boala!the record is on my table:
Can someone please help. I am getting a fatal error on the following PHP script.
I am getting an error "unidentified method Pass::_createpass()" whick relates to the second last line of the code below.
<?php
$engine = Pass::start('xxxxxxxxxxxxxxxx');
$pass = $engine->createPassFromTemplate(xxxxxxxxxxxxxx);
$engine->redirectToPass($pass);
if (!function_exists('curl_init')) {
throw new Exception('Pass needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
throw new Exception('Pass needs the JSON PHP extension.');
}
$engine = Pass::start($appKey);
$values = array(
'first' => 'John',
'last' => 'Platinum',
);
$images = array(
'thumbnail' => 'image1.jpg'
);
$pass = $engine->createPassFromTemplate(5688667418918912, $values, $images);
$passData = $engine->downloadPass($pass);
$engine->redirectToPass($pass);
class Pass
{
private $_appKey = null;
private $_endpoint = 'https://pass.center/api/v1';
private $_debug = false;
private static $_instance = null;
private static $_imageTypes = array('icon', 'logo', 'strip', 'thumbnail', 'background', 'footer');
const VERSION = '0.5';
const USER_AGENT = 'PassSDK-PHP/0.5';
public function __construct($appKey = null, $endpoint = null, $debug = false)
{
if (is_null($appKey)) {
throw new Exception('App Key required');
}
$this->_appKey = $appKey;
if ($endpoint !== null) {
$this->_endpoint = $endpoint;
}
$this->_debug = $debug;
}
public static function start($appKey = null, $endpoint = null, $debug = false)
{
if (self::$_instance == null) {
self::$_instance = new self($appKey, $endpoint, $debug);
}
return self::$_instance;
}
public function createPassFromTemplate($templateId, $values = array(), $images = array())
{
$resource = sprintf("https://xxxxxxx/api/v1/templates/names/Test/pass", $templateId);
return $this->_createPass($resource, $values, $images);
}
}
I hope someone can help me as I am not familiar with Functions PHP.
Thanks All
Rob
The function createPass is missing.
You need something like this:
/**
* Prepares the values and image for the pass and creates it
*
* #param string $resource Resource URL for the pass creation
* #param array $values Values
* #param array $images Images
* #return object Pass
*/
private function _createPass($resource, $values, $images)
{
$multipart = count($images) > 0;
if ($multipart) {
$content = array();
foreach ($images as $imageType => $image) {
$this->_addImage($image, $imageType, $content, $imageType);
}
var_dump($content);
// Write json to file for curl
$jsonPath = array_search('uri', #array_flip(stream_get_meta_data(tmpfile())));
file_put_contents($jsonPath, json_encode($values));
$content['values'] = sprintf('#%s;type=application/json', $jsonPath);
} else {
$content = $values;
}
return $this->_restCall('POST', $resource, $content, $multipart);
}
..And full script here
I am trying to figure out best practices for writing robust object oriented database models in PHP. I would like to use a data access layer and then have an abstract model class that my actual models would be able to extend. I was hoping to be able to encapsulate all basic CRUD functionality in these layers so I don't have to write lots of redundant code. I am having trouble finding tutorial on how to do this. Does anyone know of a tutorial or have example code on how to do this?
If you want to abstract this further to just make procedural calls to DbMgr.php above,
you can use the below code. This will help you develop project fast and anyone who doesn't have database knowledge can also use below methods to develop php mysql application.
CALL THIS FILE : DbMgrInterface.php
//Includes complete implementation of DB operations
require_once __DIR__.'/DbMgr.php';
$perform_Database_Operation = null; // Global variable to reuse the connection
$error_code = null; // Global variable holding the error_code for a transaction
function getDBConfig($config = ''){
$source = 'Func';
$type = 'mysql';
if(isset($config['source'])){
$source = $config['source'];
}
if( (strcasecmp("Func",$source) == 0) && (function_exists('get_DbConfig')) ) {
$config = get_DbConfig();
}
if(isset($config['type'])){
$type = $config['type'];
}
$config['dbType'] = strtolower($type);
$config['servername'] = $config['host'];
$config['Port'] = $config['port'];
$config['userName'] = $config['username'];
$config['passWord'] = $config['password'];
$config['DatabaseName'] = $config['database'];
return $config;
}
/**
Logic: If config array is passed to this method then definitely the new handle is required.
Else, If DBMgrHandle already exists then return the existing handle.
Else, get the default DB config, and instantiate a new DBMgr Handle.
*/
function DBMgr_Handle($config = '') {
global $perform_Database_Operation;
$className = 'DBMgr';
if(is_array($config)){
$config = getDBConfig($config);
if(strcasecmp($config['dbType'], 'mssql') == 0){
$className = 'SSRV';
}
$perform_Database_Operation = new $className($config);
return $perform_Database_Operation;
}
if(isset($perform_Database_Operation))
return $perform_Database_Operation;
$config = getDBConfig($config);
if(strcasecmp($config['dbType'], 'mssql') == 0){
$className = 'SSRV';
}
if(function_exists('getclassObject'))
$perform_Database_Operation = getclassObject($className, $config);
else
$perform_Database_Operation = new $className($config);
return $perform_Database_Operation;
}
/*=====================================================READ==============================================================*/
/*
* #access public
* #param associative_Array $readInput. Format is described below:
* array(
* 'Fields'=> 'Field1, Field2, Field3', //Mandatory
* 'Table'=> 'TableName', //Mandatory
* 'clause'=> 'FieldName = FieldValue', //optional
* 'order' => 'FieldName DESC' //optional
* )
clause refers exact/valid values as mysql query accepts.
clause is a condition to filter output. e.g. 'FieldName = DesiredValue' would return entries where FieldName has DesiredValue value only.
Order refers exact/valid values as mysql query accepts and is used to sort data selection. example value can be 'FieldName ASC' or 'FieldName DESC'.
* #param string $outputFormat. Values can be one of 'RESULT, NUM_ROWS, NUM_ARR, ASSOC', where ASSOC is default value.
* It defines whether the read should return 'mysql result resource/ Numbers of rows in result set / Numbered array / Associative array
* #param string $DataType. Value can only be 'JSON' else ''. Use this to get data set returned as json.
* #param string $keyField_Output. This can be a field name so that indexes of assoc array can be defined with value of the field passed.
*
* #return false, else 0(zero- for no corresponding entry), else output in described format.
* If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Read($readInput, $outputFormat = "ASSOC", $DataType = "", $keyField_Output = '') {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Read($readInput, $outputFormat, $DataType, $keyField_Output);
}
/*=====================================================INSERT==============================================================*/
/*
* #access public
* #param associative_Array $insertInput. Format is described below:
* array(
* 'Table'=> 'TableName', //Mandatory
* 'Fields'=> array( //Mandatory
'FieldName1' =>Value1,
'FieldName2' =>Value2,
'FieldName_n'=>Value_n
)
* )
* So in above associative array the element refered by key 'Fields' is itself an associative array which would specify DbField and corresponding Value to be stored
* #return Inserted Id on success, else false on failure. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Insert($insertInput) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Insert($insertInput);
}
/*=====================================================UPDATE==============================================================*/
/*
* #access public
* #param associative_Array $updateInput. Format is described below:
* array(
* 'Table'=> 'TableName', //Mandatory
* 'Fields'=> array( //Mandatory
'FieldName1' =>Value1,
'FieldName2' =>Value2,
'FieldName_n'=>Value_n
),
* 'clause'=> 'FieldName = FieldValue', //optional
* )
* So in above associative array the element refered by key 'Fields' is itself an associative array which would specify DbField and corresponding Value to be stored
* #return true on success, else false. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Update($updateInput) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Update($updateInput);
}
/*=====================================================DELETE==============================================================*/
/*
* #access public
* #param associative_Array $deleteInput. Format is described below:
* array(
* 'Table'=> 'TableName', //Mandatory
* 'clause'=> 'FieldName = FieldValue', //OPTIONAL. But if not specified all the data from database would be deleted
* )
* So in above associative array the element refered by key 'Fields' is itself an associative array which would specify DbField and corresponding Value to be stored
* #return true on success, else false on failure. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Delete($deleteInput) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Delete($deleteInput);
}
/*=====================================================RUN ABSOLUTE QUERY==============================================================*/
/*
* #access public
* #param Query as a string. Query can be of any type
* #param string $outputFormat. Values can be one of 'RESULT, NUM_ROWS, NUM_ARR, ASSOC', where ASSOC is default value.
* It defines whether the read should return 'mysql result resource/ Numbers of rows in result set / Numbered array / Associative array
* #param string $DataType. Value can only be 'JSON' else ''. Use this to get data set returned as json.
* #param string $keyField_Output. This can be a field name so that indexes of assoc array can be defined with value of the field passed.
*
* #return false, else 0(zero- for no corresponding entry), else output in described format. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Query($query, $outputFormat = "ASSOC", $DataType = "", $keyField_Output = '') {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Query($query, $outputFormat, $DataType, $keyField_Output);
}
/**
* The function makes a complete database dump of dump for selective tables, depending upon the TABLE_LIST. If TABLE_LIST is empty,
* a complete database dump is made, else dump for selective tables is carried out.
* #param unknown $ExportDBArray
* $ExportDBArray = array(
'DUMP_FILE_NAME' => 'dump.sql', // optional
'TABLE_LIST' => array( // optional
'Table1' => 'userinfo',
'Table2' => 'usageinfo'
)
);
* #return boolean
*/
function DB_ExportTable($ExportDBArray) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Export($ExportDBArray);
}
/**
* The function imports SQL Dump from the given file path.
* #param unknown $ImportDBArray
* $ImportDBArray = array(
'COMPLETE_PATH' => __DIR__ . "\\database_dump.sql"
);
*/
function DB_ImportTable($ImportDBArray) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Import($ImportDBArray);
}
/**
*
* #param unknown $multipleFieldsArray
* $multipleFieldsArray = array(
'TABLE_NAME' => 'userinfo',
'ID_LIST' => true ,
'FIELD_DETAILS' => array(
array('Username' => 'bjam123','Password' =>md5('password123'), 'UserType' => 1),
array('Username' => 'ppu12', 'Password' => md5('password1234'), 'UserType' => 2),
array('Username' => 'ppu13', 'Password' => md5('password12345'), 'UserType' => 3),
array('Username' => 'ppu14', 'Password' => md5('password123456'), 'UserType' => 4)
)
);
* #return array containing the insert_id
*/
function DB_InsertMultipleRows($multipleFieldsArray) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->InsertMR($multipleFieldsArray);
}
/**
* Call this function to perform MSSQL Server specific transactions
* #param unknown $fieldValueArray
* Format is described below:
* array(
* 'Fields'=> 'Field1, Field2, Field3', //Mandatory
* 'Table'=> 'TableName', //Mandatory
* 'clause'=> 'FieldName = FieldValue', //optional
* 'order' => 'FieldName DESC' //optional
* )
clause refers exact/valid values as mysql query accepts.
clause is a condition to filter output. e.g. 'FieldName = DesiredValue' would return entries where FieldName has DesiredValue value only.
Order refers exact/valid values as mysql query accepts and is used to sort data selection. example value can be 'FieldName ASC' or 'FieldName DESC'.
* #param unknown $operationType
* Possible Values - READ, INSERT, UPDATE, DELETE
* #param unknown $outputFormat
* Possible Values - ASSOC, NUM_ARR, NUM_ROWS
*/
function DB_SSRV_Transact($fieldValueArray, $operationType, $outputFormat) {
$perform_Database_Operation = SSRV_Handle();
$perform_Database_Operation->transact($fieldValueArray, $operation, $outputFormat);
}
/*=====================================================Close mysql connection or destroy mysqli object==============================================================*/
/*
* #access public
*/
function DB_Close()
{
$perform_Database_Operation = DBMgr_Handle();
$perform_Database_Operation->closeConnection();
global $perform_Database_Operation;
$perform_Database_Operation = null;
return;
}
?>
Something on these lines:
This is abstraction that uses mysqli extensions of php
CALL THIS FILE : DbMgr.php
<?php
class DBMgr{
private $mysql_Host, $Port, $userName, $passWord, $DatabaseName, $connection, $dbType;
//Constructor function to connect and select database.
/*
* The argument is a assoc array with possible following structure
* array(
* 'source' => 'value is a string. Possible values are Func/Coded', Default value is Func. For Func, the application must have already defined a functiobn name get_DbConfig, which will return assoc array with following structure,
* array(
* 'host' => '',
* 'port' => '',
* 'username' => '',
* 'password' => '',
* 'database' => '',
* 'type' => 'optional. The default value is mysql'
* );
* 'type' => 'mandatory/Required only for Coded Source' Default value is mysql. Other possible values are nssql,postgresql.
* 'host' => 'mandatory/Required only for Coded Source'
* 'port' => 'mandatory/Required only for Coded Source'
* 'username' => 'mandatory/Required only for Coded Source'
* 'password' => 'mandatory/Required only for Coded Source'
* 'database' => 'mandatory/Required only for Coded Source. This is the database name.'
* );
*
*/
function __construct($config)
{
$this->dbType = $config['dbType'];
$this->mysql_Host = $config['host'];
$this->Port = $config['port'];
$this->userName = $config['username'];
$this->passWord = $config['password'];
$this->DatabaseName = $config['database'];
$this->connect_SpecificDatabase();
}
function __destruct() {
$this->connection = null;
}
private function connect_SpecificDatabase(){
if(!isset($this->connection)) {
switch ($this->dbType) {
case 'mysql':
$db = new mysqli('p:'.$this->mysql_Host, $this->userName, $this->passWord, $this->DatabaseName, $this->Port); // Make a connection my MySQL
$this->connection = $db;
break;
case 'postgresql':
// Make a connection to PostgreSQL
$connectionString = "host = '".$this->mysql_Host."' port = '".$this->Port."' dbname = '".$this->DatabaseName."' user='".$this->userName."' password = '".$this->passWord."'";
$db = pg_connect($connection_string);
$this->connection = $db;
break;
}
}
else {
$db = $this->connection;
}
if (!$db)
return "Error: Connection failed '".$this->set_dbError()."'";
}
private function set_dbError($Query, &$DB_OperationError = '')
{
include_once __DIR__.'./../ErrorHandling.php';
$DB_OperationError = "";
global $error_code;
switch ($this->dbType) {
case 'mysql':
$DB_OperationError = mysqli_error($this->connection);
$error_code = mysqli_errno($this->connection);
break;
case 'mssql':
$DB_OperationError = mssql_get_last_message();
break;
case 'postgresql':
$DB_OperationError = pg_last_error($this->connection);
break;
}
ErrorLogging('query: --'.$Query.' -- '.'Error: --'.$DB_OperationError);
}
private function FieldValuePair_ToString($FieldValueArray,$onlyValueString=false)
{
$FieldsAsString = "";
foreach ($FieldValueArray as $FieldName => $value) {
if($FieldsAsString != "")
$FieldsAsString .= ', ';
/* if(strpos($value, '+') > 0 || strpos($value, '-') > 0)
$FieldsAsString .= $FieldName." = ".$value;
*/
if(strpos($value,'\'') !== false || strpos($value,'\"') !== false) {
$value = addslashes($value);
}
if($onlyValueString){
if($value != 'now()')
$FieldsAsString .= "'".$value."'";
else
$FieldsAsString .= $value;
}
else{
if($value != 'now()')
$FieldsAsString .= $FieldName." = '".$value."'";
else
$FieldsAsString .= $FieldName." = ".$value;
}
}
return $FieldsAsString;
}
public function Prepare_Output($output, $output_Format, $keyField_Output = '')
{
$output_Format = strtolower($output_Format); // Convert output_Format to lowercase
if(!is_object($output))
return $output;
elseif($output->num_rows == 0)
return 0;
switch($output_Format)
{
case 'result':
return $output;
break;
case 'num_rows':
return $output->num_rows;
break;
case 'num_arr':
while ($row = $output->fetch_array(MYSQLI_NUM)) {
$output_arr[] = $row;
}
return $output_arr;
break;
case 'assoc':
default:
while ($row = $output->fetch_assoc()) {
if($keyField_Output != '' && isset($row[$keyField_Output])){
$output_arr[strval($row[$keyField_Output])] = $row;
}
else
$output_arr[] = $row;
}
return $output_arr;
break;
}
}
private function Prepare_Query($input_array, $prepare_For)
{
$Query = "";
switch($prepare_For)
{
case 'READ':
if($input_array['Fields'] == "" || $input_array['Fields'] == NULL || $input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "SELECT ";
$Query .= $input_array['Fields'];
$Query .= " FROM ";
$Query .= $input_array['Table'];
if(isset($input_array['clause']) && $input_array['clause'] != "" && $input_array['clause'] !== NULL)
{
$Query .= " WHERE ";
$Query .= $input_array['clause'];
}
if(isset($input_array['order']) && $input_array['order'] != "" && $input_array['order'] !== NULL)
{
$Query .= " ORDER BY ";
$Query .= $input_array['order'];
}
break;
case 'INSERT':
if($input_array['Fields'] == "" || $input_array['Fields'] == NULL || $input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "INSERT INTO ";
$Query .= $input_array['Table'];
$Query .= " SET ";
$Query .= $this->FieldValuePair_ToString($input_array['Fields']);
break;
case 'UPDATE':
if($input_array['Fields'] == "" || $input_array['Fields'] == NULL || $input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "UPDATE ";
$Query .= $input_array['Table'];
$Query .= " SET ";
$Query .= $this->FieldValuePair_ToString($input_array['Fields']);
if(isset($input_array['clause']) && $input_array['clause'] != "" && $input_array['clause'] !== NULL)
{
$Query .= " WHERE ";
$Query .= $input_array['clause'];
}
break;
case 'DELETE':
if($input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "DELETE FROM ";
$Query .= $input_array['Table']."";
if($input_array['clause'] != "" && $input_array['clause'] !== NULL)
{
$Query .= " WHERE ";
$Query .= $input_array['clause'];
}
break;
case 'INSERT_MR':
$vstring = ""; // Field String
if(is_array($input_array)) {
$tableName = $input_array['TABLE_NAME'];
$input_array = $input_array['FIELD_ARRAY'];
for($i = 0 ;$i < count($input_array); $i++) {
$vstring .= "(" . $this->FieldValuePair_ToString($input_array[$i],true) . ")";
if(! ($i == (count($input_array) - 1))) $vstring .= ",";
}
// Column String
$column_string = implode("," , array_keys($input_array[0])); // Get the column names
$Query = "INSERT INTO ".$tableName." (" . $column_string . ") VALUES ".$vstring.";"; // Form Query String
}
break;
case 'IMPORT_DB':
if(is_array($input_array)) {
$completePathOfSQLFile = "\"" . $input_array['COMPLETE_PATH'];
$Query = "mysql --user" . $this->userName . " --password " . $this->DatabaseName . " < " . $completePathOfSQLFile;
}
break;
case 'EXPORT_DB':
if(is_array($input_array)) {
$TableArray = $input_array['TABLE_LIST'];
$dumpFileName = $input_array['DUMP_FILE_NAME'];
$dQuery = "mysqldump -h ".$this->mysql_Host." --port=".$this->Port." --user=".$this->userName." --password=".$this->passWord;
$dumpFilePath = __DIR__;
$dumpFileName = $dumpFileName == "" ? time().'mysqlDump.sql': $dumpFileName;
if(($TableArray == null) || count($TableArray) == 0 ) {
// Export all tables
$Query = $dQuery . " --databases ".$this->DatabaseName." > ".$dumpFilePath."\\".$dumpFileName;
} else {
$tableNames = "";
// Export selective tables
foreach($TableArray as $k => $k_value) {
$tableNames .= " " . $$TableArray[$k];
}
$Query = $dQuery . " " . $this->DatabaseNames." " . $tableNames . " > \"" . $dumpFilePath."\\".$dumpFileName."\"";
}
}
break;
}
return $Query;
}
public function Read($input_array, $outputFormat, $DataType = "", $keyField_Output = '')
{
$Query = $this->Prepare_Query($input_array, 'READ');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = $this->Prepare_Output($result, $outputFormat, $keyField_Output);
if( ($DataType != "") && (strcasecmp(strtolower($DataType) , 'as_json') == 0) )
$output = json_encode($output);
}
}
return $output;
}
public function Insert($input_array)
{
$Query = $this->Prepare_Query($input_array, 'INSERT');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = mysqli_insert_id($this->connection);
if(!$output)
return true;
}
}
return $output;
}
public function Update($input_array)
{
$Query = $this->Prepare_Query($input_array, 'UPDATE');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = true;
}
}
return $output;
}
public function Delete($input_array)
{
$Query = $this->Prepare_Query($input_array, 'DELETE');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = true;
}
}
return $output;
}
public function Query($Query, $outputFormat = 'ASSOC', $DataType = "", $keyField_Output = '')
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = $this->Prepare_Output($result, $outputFormat, $keyField_Output);
if($DataType != "")
$output = json_encode($output);
}
return $output;
}
public function Export($ExportDBArray) {
$Query = $this->Prepare_Query($input_array, 'EXPORT_DB');
$op = '';
$REtVal = '';
$query = 'dir';
$resultQuery = exec($query,$op,$REtVal);
if($resultQuery) return true;
else return false;
}
public function Import($ImportDBArray) {
$Query = $this->Prepare_Query($ImportDBArray, 'IMPORT_DB');
$resultQuery = exec($Query);
}
public function InsertMR($multipleFieldsArray) {
$tableName = $multipleFieldsArray['TABLE_NAME'];
$listOfID = $multipleFieldsArray['ID_LIST'];
$FieldsArray = $multipleFieldsArray['FIELD_DETAILS'];
$input_array = array('FIELD_ARRAY' => $FieldsArray, 'TABLE_NAME' => $tableName);
$Query = $this->Prepare_Query($input_array, 'INSERT_MR');
$result = $this->connection->query($Query); // Run Query
$output = array();
if (!$result) {
$this->set_dbError($Query);
} else {
$insert_id = mysqli_insert_id($this->connection);
if($listOfID) {
for($i=0; $i<count($FieldsArray); $i++) {
$output[$i] = $insert_id;
$insert_id++;
}
} else {
$output[0] = $insert_id;
}
}
return $output;
}
public function closeConnection() {
if(isset($this->connection)) {
mysqli_close($this->connection);
}
}
};
?>
Can someone please help me, I get this fatal error message when I try to run the code in a browser. I have searched through various topics and couldn't find the answer. I have two very similar functions and only one of them is reporting an error. Function getById is working just fine, but function get reports an error. Here's my db.php file:
class DB {
private $db;
public $limit = 5;
public function __construct($config){
$this->connect($config);
}
private function connect($config){
try{
if ( !class_exists('Mongo')){
echo ("The MongoDB PECL extension has not been installed or enabled");
return false;
}
$connection= new MongoClient($config['connection_string'],array('username'=>$config['username'],'password'=>$config['password']));
return $this->db = $connection->selectDB($config['dbname']);
}catch(Exception $e) {
return false;
}
}
public function create($collection,$article){
$table = $this->db->selectCollection($collection);
return $result = $table->insert($article);
}
public function get($page,$collection){
$currentPage = $page;
$articlesPerPage = $this->limit;
//number of article to skip from beginning
$skip = ($currentPage - 1) * $articlesPerPage;
$table = $this->db->selectCollection($collection); **//here reports an error**
$cursor = $table->find();
//total number of articles in database
$totalArticles = $cursor->count();
//total number of pages to display
$totalPages = (int) ceil($totalArticles / $articlesPerPage);
$cursor->sort(array('saved_at' => -1))->skip($skip)->limit($articlesPerPage);
//$cursor = iterator_to_array($cursor);
$data=array($currentPage,$totalPages,$cursor);
return $data;
}
public function getById($id,$collection){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new MongoId($id);
}
$table = $this->db->selectCollection($collection);
$cursor = $table->find(array('_id' => $id));
$article = $cursor->getNext();
if (!$article ){
return false ;
}
return $article;
}
public function delete($id,$collection){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new \MongoId($id);
}
$table = $this->db->selectCollection($collection);
$result = $table->remove(array('_id'=>$id));
if (!$id){
return false;
}
return $result;
}
public function update($id,$collection,$article){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new \MongoId($id);
}
$table = $this->db->selectCollection($collection);
$result = $table->update(
array('_id' => new \MongoId($id)),
array('$set' => $article)
);
if (!$id){
return false;
}
return $result;
}
public function commentId($id,$collection,$comment){
$postCollection = $this->db->selectCollection($collection);
$post = $postCollection->findOne(array('_id' => new \MongoId($id)));
if (isset($post['comments'])) {
$comments = $post['comments'];
}else{
$comments = array();
}
array_push($comments, $comment);
return $postCollection->update(
array('_id' => new \MongoId($id)),
array('$set' => array('comments' => $comments))
);
}
}