I have this php code. As you can see i query a mysql database through a function showallevents. I return a the $result to the $event variable. With the while loop i assign the values that i get from event to a response array and every time the loop happens the rows are stored in the data array. Surely i am failing somewhere because despite i am getting a correct number of responses all the values that i get at json are "null". Also it tells me something about JSONarray cannot be converted to jsonobject
if (isset($_POST['tag']) && $_POST['tag'] != '')
{
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'showallevents')
{
// Request type is show all events
// show all events
$event = $db->showallevents();
if ($event != false)
{
$data = array();
while($row = mysql_fetch_assoc($event))
{
$response["success"] = 1;
$response["uid"] = $event["uid"];
$response["event"]["date"] = $event["date"];
$response["event"]["hours"] = $event["hours"];
$response["event"]["store_name"] = $event["store_name"];
$response["event"]["event_information"] = $event["event_information"];
$response["event"]["event_type"] = $event["event_type"];
$response["event"]["Phone"] = $event["Phone"];
$response["event"]["address"] = $event["address"];
$response["event"]["created_at"] = $event["created_at"];
$response["event"]["updated_at"] = $event["updated_at"];
$data[]=$response;
}
echo json_encode($data);
}
else
{
// event not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Events not found";
echo json_encode($response);
}
}
else
{
echo "Access Denied";
}
}
?>
the DB_Functions.php
<?php
class DB_Functions
{
private $db;
//put your code here
// constructor
function __construct()
{
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct()
{
}
/**
* Select all events that are after yesterday.
*/
public function showallevents()
{
$result = mysql_query("SELECT * FROM events WHERE date >= CURDATE()");
return($result);
}
}
?>
ok the code that helped me put all data into an array was this
$data = array();
while($row = mysql_fetch_assoc($event))
{
$response["success"] = 1;
$response["event"]= $row;
$data[]=$response;
}
echo json_encode($data);
You've merged two independent pieces of code and wound up with a mess whose result is unclear.
You can create an associative array in two ways:
$array = (key=>value, key2=>value2);
You can also use:
$array[key]=value;
$array[key2]=value2;
Note that both 'key' and 'value' are simply variables; you can use strings there, or pass in a variable from someplace else.
When doing similar things, I use the following approach:
$response["success"] = 1;
$response["uid"] = $event["uid"];
$response["event"]["date"] = $event["date"];
$response["event"]["hours"] = $event["hours"];
$response["event"]["store_name"] = $event["store_name"];
$response["event"]["event_information"] = $event["event_information"];
$response["event"]["event_type"] = $event["event_type"];
$response["event"]["Phone"] = $event["Phone"];
$response["event"]["address"] = $event["address"];
$response["event"]["created_at"] = $event["created_at"];
$response["event"]["updated_at"] = $event["updated_at"];
$data[]=$response;
What is your $response variable?
In PHP to create associative arrays, you use => and not =
for example:
$array = ('key1' => 'value1', 'key2' => 'value2');
if you just want to return all the arrays, can you use mysql_fetch_assoc in stead of mysql_fetch_row?
if ($tag == 'showallevents')
{
// Request type is show all events
// show all events
$event = $db->showallevents();
if ($event != false)
{
$data = array();
while($row = mysql_fetch_assoc($event))
{
$data[] = $row;
echo json_encode($data);
}
else
{
// event not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Events not found";
echo json_encode($response);
}
}
else
{
echo "Access Denied";
}
}
?>
Related
I am modifying some code i had written for my by a developer who is no longer working with us, essentially the code pulls data from a web service and parses to an array, it then looks for keys within the array and publishes associated values to an HTML table, it all works fine when each of the entries exists in the data however the point of modifying the code if to return a generic value ("not submitted") if the value is not found in the array.
background info is helpful so the use case is:
Array is made up of the sales team, they each login to a website and submit their sales totals for the day, we interrogate the web service to return the data via a SOAP call which pulls the data into the code. The data is parsed and the values are represented in a table on a web page.
If a single sales team member does not submit data then the code fails to return any data.
I've been googling and hitting my pluralsight account to learn as much as i can about how this is done but i'm falling short.
class SalesResponseFactory
{
private $date;
//private $keyArray = ['KE', 'JY', 'OR', 'KR', 'SY', 'DB'];
public $responseData = [];
function __construct($date)
{
libxml_use_internal_errors(true);
$this->date = $date;
}
private function getResponseData($date)
{
....
}
private function parserToArray($data)
{
$data = substr($data, strpos($data, "<DataResult>"));
$data = substr($data, 0, strpos($data, "</DataResult>") + strlen("</DataResult>"));
$xml = simplexml_load_string($data);
if ($xml === false) {
throw new Exception("Invalid user credentials.");
}
$json = json_encode($xml);
$array = json_decode($json,TRUE);
if (empty($array['Results'])) {
throw new Exception("Holiday - No Sales Data Recorded");
}
return $array['Results']['Data'];
}
private function alignmentArray($sales)
{
if ($sales['Name'] == 'Market Code' || $sales['Name'] == 'Sales Volume' || $sales['Name'] == 'Turnover Volume' || $sales['Name'] == 'Date') {
if($sales['Name'] == 'Market Code') {
$this->responseData[$sales['Instrument']]['Market Code'] = $sales['Value'];
}
if($sales['Name'] == 'Sales Volume') {
$this->responseData[$sales['Instrument']]['Sales Volume'] = $sales['Value'];
}
if($sales['Name'] == 'Turnover Volume') {
$this->responseData[$sales['Instrument']]['Turnover Volume'] = $sales['Value'];
}
else {
$this->responseData[$sales['Instrument']]['Date'] = $sales['Value'];
}
}
}
public function parser()
{
try {
$salesArray = $this->getResponseData($this->date);
} catch (Exception $e) {
$response['status'] = 'error';
$response['message'] = $e->getMessage();
$response['results'] = '';
return json_encode($response);
}
foreach ($salesArray as $sales) {
$this->alignmentArray($sales);
}
$response['status'] = 'ok';
$response['message'] = 'success';
$response['results'] = [];
foreach ($this->responseData as $row) {
array_push($response['results'], $row);
}
return json_encode($response);
}
}
?>
i'd expect that null values should still be output but whats actually happening is that no data is being returned to the HTML table.
I have a database phpmyadmin, I created a class :
<?php
class Ticket
{
private $NumDossier = 0;
private $NomTicket ="";
private $Service = "" ;
private $Impact = 0;
private $Urgence = "";
private $DateOuverture = "";
public function __construct($p_NumDossier, $p_NomTicket,$p_Service,$p_Impact,$p_Urgence,$p_DateOuverture)
{
$this->NumDossier = $p_NumDossier;
$this->NomTicket = $p_NomTicket;
$this->Service = $p_Service;
$this->Impact = $p_Impact;
$this->Urgence = $p_Urgence;
$this->DateOuverture = $p_DateOuverture;
}
public function getNumDossier()
{
return $this->NumDossier;
}
public function getNomTicket()
{
return $this->NomTicket;
}
public function getService()
{
return $this->Service;
}
public function getImpact()
{
return $this->Impact;
}public function getUrgence()
{
return $this->Urgence;
}
public function getDateOuverture()
{
return $this->DateOuverture;
}
}
?>
For all row that my query return I want to create an object and add it to a collection.
My code :
$connexion = cnx();
if($connexion) {
$requete="SELECT * FROM ticket '";
$result = mysqli_query($connexion, $requete);
$result = mysqli_query($connexion, $requete);
$row = mysqli_fetch_assoc($result);
}
$test = new Ticket(0,"","",0,"","");
while($row) {
//create object for each line and add it to an collection
}
If you have a solution/lead me to this issue.
Thanks for read !
I have to assume that the beginning part of your code is correct, so I copied that. But I changed it further on. You want to retrieve multiple rows, so I put the mysqli_fetch_assoc inside the while loop. With each new row I create a new ticket and put it in a 'collection' array.
$connection = cnx();
if ($connexion) {
$query ="SELECT * FROM ticket";
$result = mysqli_query($connection, $query);
if ($result === false) die("The query [$query] could not be executed.");
$collection = [];
while($row = mysqli_fetch_assoc($result)) {
$collection[] = new Ticket($row["NumDossier"],
$row["NomTicket"],
$row["Service"],
$row["Impact"],
$row["Urgence"],
$row["DateOuverture"]);
}
echo "<pre>";
print_r($collection);
echo "</pre>";
}
So I used a simple array for the collection. I used the default numeric array indexing because I wouldn't know what to replace it with. $row["NomTicket"] seems a logical choice.
The script run good, but only when I fetching out the groups of the user, it's says:
SteamUser.php (132): Creating default object from empty value
function getProfileData() {
//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)) {
$this->steamID64 = (string)$parsedData->steamID64;
$this->steamID = (string)$parsedData->steamID;
$this->stateMessage = (string)$parsedData->stateMessage;
$this->visibilityState = (int)$parsedData->visibilityState;
$this->privacyState = (string)$parsedData->privacyState;
$this->avatarIcon = (string)$parsedData->avatarIcon;
$this->avatarMedium = (string)$parsedData->avatarMedium;
$this->avatarFull = (string)$parsedData->avatarFull;
$this->vacBanned = (int)$parsedData->vacBanned;
$this->tradeBanState = (string)$parsedData->tradeBanState;
$this->isLimitedAccount = (string)$parsedData->isLimitedAccount;
$this->onlineState = (string)$parsedData->onlineState;
$this->inGameServerIP = (string)$parsedData->inGameServerIP;
//If their account is public, get that info:
if($this->privacyState == "public") {
$this->customURL = (string)$parsedData->customURL;
$this->memberSince = (string)$parsedData->memberSince;
$this->steamRating = (float)$parsedData->steamRating;
$this->hoursPlayed2Wk = (float)$parsedData->hoursPlayed2Wk;
$this->headline = (string)$parsedData->headline;
$this->location = (string)$parsedData->location;
$this->realname = (string)$parsedData->realname;
$this->summary = (string)$parsedData->summary;
}
//If they're in a game, grab that info:
if($this->onlineState == "in-game") {
$this->inGameInfo = array();
$this->inGameInfo["gameName"] = (string)$parsedData->inGameInfo->gameName;
$this->inGameInfo["gameLink"] = (string)$parsedData->inGameInfo->gameLink;
$this->inGameInfo["gameIcon"] = (string)$parsedData->inGameInfo->gameIcon;
$this->inGameInfo["gameLogo"] = (string)$parsedData->inGameInfo->gameLogo;
$this->inGameInfo["gameLogoSmall"] = (string)$parsedData->inGameInfo->gameLogoSmall;
}
//Any weblinks listed in their profile:
if(!empty($parsedData->weblinks)) {
$this->weblinks = array();
$i = 0;
foreach ($parsedData->weblinks->weblink as $weblink) {
$this->weblinks[$i]->title = (string)$weblink->title;
$this->weblinks[$i]->link = (string)$weblink->link;
$i++;
}
}
if(!empty($parsedData->groups)) {
$this->groups = array();
$i = 0;
foreach ($parsedData->groups->group as $group) {
$this->groups[$i]->groupID64 = (string)$group->groupID64; // row 132 in script
$this->groups[$i]->groupName = (string)$group->groupName;
$this->groups[$i]->groupURL = (string)$group->groupURL;
$this->groups[$i]->headline = (string)$group->headline;
$this->groups[$i]->summary = (string)$group->summary;
$this->groups[$i]->avatarIcon = (string)$group->avatarIcon;
$this->groups[$i]->avatarMedium = (string)$group->avatarMedium;
$this->groups[$i]->avatarFull = (string)$group->avatarFull;
$this->groups[$i]->memberCount = (string)$group->memberCount;
$this->groups[$i]->membersInChat = (string)$group->membersInChat;
$this->groups[$i]->membersInGame = (string)$group->membersInGame;
$this->groups[$i]->membersOnline = (string)$group->membersOnline;
$i++;
}
}
}
}
.
.
.
I already tried to using associative arrays, but didn't work; maybe with doing it all new. -_-
So, I can't set error_reporting(0) or ini_set at all.
I also used new stdClass() as a try. But I didn't get this running too.
You create an array.
$this->groups = array();
But in this array you donot create any object. You just use this array's elements (thoes are not initialized) as objects. You should add this line before your 132. row.
$this->groups[$i] = new Group();
Or something similar.
If you do not have Group class you should try
$this->groups[$i] = new stdClass();
I'm trying to use heavy resource content loop operation with ZeroMQ (PHP-ZMQ) via tcp protocol.
I've got below code so far:
class SJB_Miscellaneous_SendNotifications extends SJB_Function
{
public function execute()
{
try{
set_time_limit(0);
$i18n = SJB_I18N::getInstance();
$lang = $i18n->getLanguageData($i18n->getCurrentLanguage());
$current_date = strftime($lang['date_format'], time());
// Send Search Notifications
$saved_searches = SJB_SavedSearches::getAutoNotifySavedSearches();
// echo "<pre>"; print_r($saved_searches); echo "</pre>"; exit;
$listing = new SJB_Listing();
$notified_saved_searches_sid = array();
$notificationsLimit = (int) SJB_Settings::getSettingByName('num_of_listings_sent_in_email_alerts');
/* ZeroMQ implementation */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, "MySock1");
$queue->connect("tcp://127.0.0.1:5555");
/* Assign socket 1 to the queue, send and receive */
$time = time();
$queue->send(json_encode($saved_searches));
// echo $queue->recv();
// exit;
$count = 1;
// array_shift($saved_searches);
$server = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP);
$server->bind("tcp://127.0.0.1:5555");
$msg = $server->recv();
$saved_searches = json_decode($msg, true);
// echo "<pre>"; var_dump($saved_searches); echo "</pre>";
// exit;
foreach ($saved_searches as $saved_search) {
$searcher = new SJB_ListingSearcher();
$listing->addActivationDateProperty();
$search_data = unserialize($saved_search['data']);
$search_data['active']['equal'] = 1;
$datearr = explode('-', $saved_search['last_send']);
$saved_search['last_send'] = strftime($lang['date_format'], mktime(0, 0, 0, $datearr[1], $datearr[2], $datearr[0]));
$search_data['activation_date']['not_less'] = $saved_search['last_send'];
$search_data['activation_date']['not_more'] = $current_date;
$listing_type_sid = 0;
if ($search_data['listing_type']['equal']) {
$listing_type_id = $search_data['listing_type']['equal'];
$listing_type_sid = SJB_ListingTypeManager::getListingTypeSIDByID($listing_type_id);
if (SJB_ListingTypeManager::getWaitApproveSettingByListingType($listing_type_sid))
$search_data['status']['equal'] = 'approved';
}
// echo "<pre>"; echo $saved_search['user_sid']; print_r($listing_type_id); echo "</pre>"; exit;
$id_alias_info = $listing->addIDProperty();
$username_alias_info = $listing->addUsernameProperty();
$listing_type_id_info = $listing->addListingTypeIDProperty();
$aliases = new SJB_PropertyAliases();
$aliases->addAlias($id_alias_info);
$aliases->addAlias($username_alias_info);
$aliases->addAlias($listing_type_id_info);
$search_data['access_type'] = array(
'accessible' => $saved_search['user_sid'],
);
$criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($search_data, $listing);
$searcher->found_object_sids = array();
$searcher->setLimit($notificationsLimit);
$sorting_fields = array('CityRegion' => 'ASC');
$found_listings_ids = $searcher->getObjectsSIDsByCriteria($criteria, $aliases, $sorting_fields);
// echo "<pre>"; var_dump($found_listings_ids); echo "</pre>";
if (count($found_listings_ids)) {
$saved_search['activation_date'] = $saved_search['last_send'];
if (SJB_Notifications::sendUserNewListingsFoundLetter($found_listings_ids, $saved_search['user_sid'], $saved_search, $listing_type_sid)) {
SJB_Statistics::addStatistics('sentAlert', $listing_type_sid, $saved_search['sid']);
SJB_DB::query('UPDATE `saved_searches` SET `last_send` = CURDATE() WHERE `sid` = ?n', $saved_search['sid']);
}
$notified_saved_searches_sid[] = $saved_search['sid'];
}
echo nl2br($count."\n");
$count++;
}
// To be entered from task_scheduler.php
$expired_contracts_id = null; $expired_listings_id = null;
$template_processor = SJB_System::getTemplateProcessor();
$template_processor->assign('expired_listings_id', null);
$template_processor->assign('deactivated_listings_id', null);
$template_processor->assign('expired_contracts_id', null);
$template_processor->assign('notified_saved_searches_id', $notified_saved_searches_sid);
$scheduler_log = $template_processor->fetch('task_scheduler_log.tpl');
if ($log_file = #fopen('task_scheduler.log', 'a+')) {
fwrite($log_file, $scheduler_log);
fclose($log_file);
}
SJB_DB::query('INSERT INTO `task_scheduler_log`
(`last_executed_date`, `notifieds_sent`, `expired_listings`, `expired_contracts`, `log_text`)
VALUES ( NOW(), ?n, ?n, ?n, ?s)',
count($notified_saved_searches_sid), count($expired_listings_id), count($expired_contracts_id), $scheduler_log);
} catch(Exception $e){
echo $e->getMessage();
}
}
} // END class SJB_Miscellaneous_SendNotifications extends SJB_Function
Is there a good way to utilise ZeroMQ for this type of operation where I want to free loop operations especially when it reaches $saved_searches foreach loop?
Im trying to make Cassandra run with PHP on Windows 7 at the moment.
I installed cassandra and thrift...
When I call the cassandra-test.php, I get the following error:
( ! ) Fatal error: Call to undefined method
CassandraClient::batch_insert() in
C:\xampp\htdocs\YiiPlayground\cassandra-test.php on line 75
Call Stack
# Time Memory Function Location
1 0.0014 337552 {main}( ) ..\cassandra-test.php:0
2 0.0138 776232 CassandraDB->InsertRecord(
) ..\cassandra-test.php:304
The cassandra-test.php looks as follows:
<?php
// CassandraDB version 0.1
// Software Projects Inc
// http://www.softwareprojects.com
//
// Includes
$GLOBALS['THRIFT_ROOT'] = 'C:/xampp/htdocs/Yii/kallaspriit-Cassandra-PHP-Client-Library/thrift';
//$GLOBALS['THRIFT_ROOT'] = realpath('E:/00-REGIESTART/Programme/Cassandra/thrift');
require_once $GLOBALS['THRIFT_ROOT'].'/packages/cassandra/Cassandra.php';
require_once $GLOBALS['THRIFT_ROOT'].'/packages/cassandra/cassandra_types.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php';
require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TFramedTransport.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';
class CassandraDB
{
// Internal variables
protected $socket;
protected $client;
protected $keyspace;
protected $transport;
protected $protocol;
protected $err_str = "";
protected $display_errors = 0;
protected $consistency = 1;
protected $parse_columns = 1;
// Functions
// Constructor - Connect to Cassandra via Thrift
function CassandraDB ($keyspace, $host = "127.0.0.1", $port = 9160)
{
// Initialize
$this->err_str = '';
try
{
// Store passed 'keyspace' in object
$this->keyspace = $keyspace;
// Make a connection to the Thrift interface to Cassandra
$this->socket = new TSocket($host, $port);
$this->transport = new TFramedTransport($this->socket, 1024, 1024);
$this->protocol = new TBinaryProtocolAccelerated($this->transport);
$this->client = new CassandraClient($this->protocol);
$this->transport->open();
}
catch (TException $tx)
{
// Error occured
$this->err_str = $tx->why;
$this->Debug($tx->why." ".$tx->getMessage());
}
}
// Insert Column into ColumnFamily
// (Equivalent to RDBMS Insert record to a table)
function InsertRecord ($table /* ColumnFamily */, $key /* ColumnFamily Key */, $record /* Columns */)
{
// Initialize
$this->err_str = '';
try
{
// Timestamp for update
$timestamp = time();
// Build batch mutation
$cfmap = array();
$cfmap[$table] = $this->array_to_supercolumns_or_columns($record, $timestamp);
// Insert
$this->client->batch_insert($this->keyspace, $key, $cfmap, $this->consistency);
// If we're up to here, all is well
$result = 1;
}
catch (TException $tx)
{
// Error occured
$result = 0;
$this->err_str = $tx->why;
$this->Debug($tx->why." ".$tx->getMessage());
}
// Return result
return $result;
}
// Insert SuperColumn into SuperColumnFamily
// (Equivalent to RDMBS Insert record to a "nested table")
function InsertRecordArray ($table /* SuperColumnFamily */, $key_parent /* Super CF */,
$record /* Columns */)
{
// Initialize
$err_str = '';
try
{
// Timestamp for update
$timestamp = time();
// Build batch mutation
$cfmap = array();
$cfmap[$table] = $this->array_to_supercolumns_or_columns($record, $timestamp);
// Insert
$this->client->batch_insert($this->keyspace, $key_parent, $cfmap, $this->consistency);
// If we're up to here, all is well
$result = 1;
}
catch (TException $tx)
{
// Error occured
$result = 0;
$this->err_str = $tx->why;
$this->Debug($tx->why." ".$tx->getMessage());
}
// Return result
return $result;
}
// Get record by key
function GetRecordByKey ($table /* ColumnFamily or SuperColumnFamily */, $key, $start_from="", $end_at="")
{
// Initialize
$err_str = '';
try
{
return $this->get($table, $key, NULL, $start_from, $end_at);
}
catch (TException $tx)
{
// Error occured
$this->err_str = $tx->why;
$this->Debug($tx->why." ".$tx->getMessage());
return array();
}
}
// Print debug message
function Debug ($str)
{
// If verbose is off, we're done
if (!$this->display_errors) return;
// Print
echo date("Y-m-d h:i:s")." CassandraDB ERROR: $str\r\n";
}
// Turn verbose debug on/off (Default is off)
function SetDisplayErrors($flag)
{
$this->display_errors = $flag;
}
// Set Consistency level (Default is 1)
function SetConsistency ($consistency)
{
$this->consistency = $consistency;
}
// Build cf array
function array_to_supercolumns_or_columns($array, $timestamp=null)
{
if(empty($timestamp)) $timestamp = time();
$ret = null;
foreach($array as $name => $value) {
$c_or_sc = new cassandra_ColumnOrSuperColumn();
if(is_array($value)) {
$c_or_sc->super_column = new cassandra_SuperColumn();
$c_or_sc->super_column->name = $this->unparse_column_name($name, true);
$c_or_sc->super_column->columns = $this->array_to_columns($value, $timestamp);
$c_or_sc->super_column->timestamp = $timestamp;
}
else
{
$c_or_sc = new cassandra_ColumnOrSuperColumn();
$c_or_sc->column = new cassandra_Column();
$c_or_sc->column->name = $this->unparse_column_name($name, true);
$c_or_sc->column->value = $value;
$c_or_sc->column->timestamp = $timestamp;
}
$ret[] = $c_or_sc;
}
return $ret;
}
// Parse column names for Cassandra
function parse_column_name($column_name, $is_column=true)
{
if(!$column_name) return NULL;
return $column_name;
}
// Unparse column names for Cassandra
function unparse_column_name($column_name, $is_column=true)
{
if(!$column_name) return NULL;
return $column_name;
}
// Convert supercolumns or columns into an array
function supercolumns_or_columns_to_array($array)
{
$ret = null;
for ($i=0; $i<count($array); $i++)
foreach ($array[$i] as $object)
{
if ($object)
{
// If supercolumn
if (isset($object->columns))
{
$record = array();
for ($j=0; $j<count($object->columns); $j++)
{
$column = $object->columns[$j];
$record[$column->name] = $column->value;
}
$ret[$object->name] = $record;
}
// (Otherwise - not supercolumn)
else
{
$ret[$object->name] = $object->value;
}
}
}
return $ret;
}
// Get record from Cassandra
function get($table, $key, $super_column=NULL, $slice_start="", $slice_finish="")
{
try
{
$column_parent = new cassandra_ColumnParent();
$column_parent->column_family = $table;
$column_parent->super_column = $this->unparse_column_name($super_column, false);
$slice_range = new cassandra_SliceRange();
$slice_range->start = $slice_start;
$slice_range->finish = $slice_finish;
$predicate = new cassandra_SlicePredicate();
$predicate->slice_range = $slice_range;
$resp = $this->client->get_slice($this->keyspace, $key, $column_parent, $predicate, $this->consistency);
return $this->supercolumns_or_columns_to_array($resp);
}
catch (TException $tx)
{
$this->Debug($tx->why." ".$tx->getMessage());
return array();
}
}
// Convert array to columns
function array_to_columns($array, $timestamp=null) {
if(empty($timestamp)) $timestamp = time();
$ret = null;
foreach($array as $name => $value) {
$column = new cassandra_Column();
$column->name = $this->unparse_column_name($name, false);
$column->value = $value;
$column->timestamp = $timestamp;
$ret[] = $column;
}
return $ret;
}
// Get error string
function ErrorStr()
{
return $this->err_str;
}
}
// Initialize Cassandra
$cassandra = new CassandraDB("SPI");
// Debug on
$cassandra->SetDisplayErrors(true);
// Insert record ("Columns" in Cassandra)
$record = array();
$record["name"] = "Mike Peters";
$record["email"] = "mike at softwareprojects.com";
if ($cassandra->InsertRecord('mytable', "Mike Peters", $record)) {
echo "Record (Columns) inserted successfully.\r\n";
}
// Print record
$record = $cassandra->GetRecordByKey('mytable', "Mike Peters");
print_r($record);
?>
Any ideas on this, how to fix this?
Thanks a lot!
You really don't want to do Thrift by hand if you can avoid it. Take a look at phpcassa library:
https://github.com/thobbs/phpcassa
Oh, and in the above, looks like you want 'batch_mutate' not 'batch_insert' on ln. 75. That method changed names in versions of cassandra > 0.6.x