I am using the Google API to add rows to a Google Sheet. This is all working well, but the new rows are being added to the end (using the append method).
I would like to insert the row at the top, below the heading, in my case Row 2.
This is my working code for adding to the end. How can I specify where I want to insert the row at a given position.
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $CredentialFile);
$client = new \Google_Client;
$client->useApplicationDefaultCredentials();
$client->setApplicationName("MyApp");
$client->setScopes(['https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds']);
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
$accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];
ServiceRequestFactory::setInstance(new DefaultServiceRequest($accessToken));
$SheetId = "MySheetId";
$service = new \Google_Service_Sheets($client);
$sheet = $service->spreadsheets->get($SheetId);
$sheets = $sheet->getSheets();
$SheetTitle = $sheets[0]->properties->title;
$range = "{$SheetTitle}!A:D";
$values = [];
$row = [];
$row[] = "Tom";
$row[] = "Thumb";
$row[] = "tomthumb";
$row[] = "tom#thumb.com"
$values[] = $row;
$body = new \Google_Service_Sheets_ValueRange([
'values' => $values
]);
$params = [
'valueInputOption' => "RAW"
];
$result = $service->spreadsheets_values->append($SheetId, $range, $body, $params);
You are using values.append which by definition appends values to the first empty row
If you want to insert your values in a range that is not the first empty row of the sheet, you need to use instead the method values.batchUpdate
Sample:
$range="Sheet1!A2:D2";
$values = array(
array(
"Tom", "Thumb", "tomthumb", "tom#thumb.com"
)
);
$data = array();
$data[] = new Google_Service_Sheets_ValueRange(array(
'range' => $range,
'values' => $values
)
);
$body = new Google_Service_Sheets_BatchUpdateValuesRequest(array(
'valueInputOption' => 'RAW',
'data' => $data
)
);
$result = $service->spreadsheets_values->batchUpdate($SheetId, $body);
UPDATE
I you want to insert a row with with data rather than pasting data into an already existing row - you need to create the additional row first.
This can be done with a InsertDimensionRequest.
Sample:
$request = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
'requests' => array(
'insertDimension' => array(
'range' => array(
"startIndex": 1,
"endIndex": 2,
"dimension": "ROWS",
"sheetId": 0
)
)
)
));
$request->setRequests($body);
$result = $service->spreadsheets->batchUpdate($SheetId, $request);
Related
I saw the similar questions, but it has not helped me. I am trying to fetch message. I need full message with all parts, headers, attachments.
$fetchQuery = new Horde_Imap_Client_Fetch_Query();
$fetchQuery->fullText();
/** #var Horde_Imap_Client_Fetch_Results $mail */
$results = $client->fetch('INBOX', $fetchQuery, ['ids' => new Horde_Imap_Client_Ids(11632)]);
var_dump($results->first()->getEnvelope()->subject);
I tried a lot of variants. But I can't get any info about message. The subject is empty string. I am sure, such mail with that uid exists, I got this uid with Horde also.
Try the code mentioned below. $results array has all the items you need.
$uids = new \Horde_Imap_Client_Ids($thread_uids);
$query = new \Horde_Imap_Client_Fetch_Query();
$query->envelope();
$query->structure();
$messages = $oClient->fetch($mailbox, $query, array('ids' => $uids));
$results = [];
foreach($messages as $message){
$envelope = $message->getEnvelope();
$structure = $message->getStructure();
$msghdr = new StdClass;
$msghdr->recipients = $envelope->to->bare_addresses;
$msghdr->senders = $envelope->from->bare_addresses;
$msghdr->cc = $envelope->cc->bare_addresses;
$msghdr->bcc = $envelope->bcc->bare_addresses;
$msghdr->subject = $envelope->subject;
$msghdr->timestamp = $envelope->date->getTimestamp();
$query = new Horde_Imap_Client_Fetch_Query();
$query->fullText();
$typemap = $structure->contentTypeMap();
foreach ($typemap as $part => $type) {
// The body of the part - attempt to decode it on the server.
$query->bodyPart($part, array(
'decode' => true,
'peek' => true,
));
$query->bodyPartSize($part);
}
$id = new Horde_Imap_Client_Ids($message->getUid());
$messagedata = $oClient->fetch($mailbox, $query, array('ids' => $id))->first();
$msgdata = new StdClass;
$msgdata->id = $id;
$msgdata->contentplain = '';
$msgdata->contenthtml = '';
$msgdata->attachments = array(
'inline' => array(),
'attachment' => array(),
);
$plainpartid = $structure->findBody('plain');
$htmlpartid = $structure->findBody('html');
foreach ($typemap as $part => $type) {
// Get the message data from the body part, and combine it with the structure to give a fully-formed output.
$stream = $messagedata->getBodyPart($part, true);
$partdata = $structure->getPart($part);
$partdata->setContents($stream, array('usestream' => true));
if ($part == $plainpartid) {
$msgdata->contentplain = $partdata->getContents();
} else if ($part == $htmlpartid) {
$msgdata->contenthtml = $partdata->getContents();
} else if ($filename = $partdata->getName($part)) {
$disposition = $partdata->getDisposition();
$disposition = ($disposition == 'inline') ? 'inline' : 'attachment';
$attachment = new StdClass;
$attachment->name = $filename;
$attachment->type = $partdata->getType();
$attachment->content = $partdata->getContents();
$attachment->size = strlen($attachment->content);
$msgdata->attachments[$disposition][] = $attachment;
}
}
$data = [
'uid' => implode("",$id->ids),
'from' => implode(",",$msghdr->senders),
'cc' => implode(",",$msghdr->cc),
'bcc' => implode(",",$msghdr->bcc),
'to' => implode(",",$msghdr->recipients),
'date' => $msghdr->timestamp,
'subject' => $envelope->subject,
'hasAttachments' => $structure->getDisposition(),
'folder' => $mailbox,
'messageId' => $envelope->message_id,
'attachment' => $msgdata->attachments
];
$data['body'] = empty($msgdata->contenthtml) ? $msgdata->contenttext: $msgdata->contenthtml;
array_push($results,$data);
}
$fetchQuery = new Horde_Imap_Client_Fetch_Query();
$fetchQuery->fullText();
/** #var Horde_Imap_Client_Fetch_Results $mail */
$results = $client->fetch('INBOX', $fetchQuery, ['ids' => new Horde_Imap_Client_Ids(11632)]);
var_dump($results->first()->getFullMsg());
Anyone know how to get the colorId from google calendar events? I search a lot on web for that and I didn´t find anything that works. I need help.
My code works good but regarding the colorId always receive NULL.
I know we have the $cal->colors->get() method but it's not quite what I want. I want the colors of each the events.
Here is my code:
$client = new Google_Client();
$client->setApplicationName("Ware");
$client->setDeveloperKey('CalendarKey');
$cal = new Google_Service_Calendar($client);
$params = array(
'singleEvents' => true,
'orderBy' => 'startTime'
);
$events = $cal->events->listEvents($calendarId, $params);
$calTimeZone = $events->timeZone;
$events = $cal->events->instances($calendarId, "eventId");
date_default_timezone_set($calTimeZone);
$jsonEvents = json_encode($events->getItems());
$outerArray = array();
$innerArray = array();
foreach ($events->getItems() as $event) {
$date = $event->start->date;
if (!isset($date)) {
$date = $event->start->dateTime;
}
$endDate = $event->end->dateTime;
if (!isset($endDate)) {
$endDate = $event->end->date;
}
$array = array(
"title" => $event->summary,
"description" => $event->description,
"id" => $event->id,
"location" => $event->location,
"start" => $date,
"end" => $endDate,
"colorId" => $event->colorId
);
array_push($outerArray, $array);
}
echo json_encode($outerArray);
The "colorId" => $event->colorId is always NULL.
Public calendar is ON and I have the rights "Make changes and manage sharing".
How can fix that help?
Thanks
I have a mongo collection and I'd like to obtain all the document whose names start with a given letter on PHP. My code:
$letter = "c";
$client = new MongoDB\Client();
$pme = $client->selectCollection("belgium", "pme");
$regex = new MongoDB\BSON\Regex ("^$letter", "i");
$query = array('name' => $regex); // 1
$query = array('name' => $regex, array( 'sort' => array( 'OrderBy' => 1 ) )); // 2
$query = new MongoDB\Driver\Query( array('name' => $regex), array( 'sort' => array( 'OrderBy' => 1 ) ) ); // 3
$cursor = $pme->find($query);
Whe I use query 1. I got all documents starting with letter c but not ordered. When I use query 2, I got nothing. And finally when I use query 3 I get almost every document, not just those starting with with 'c'. What I am doing wrong here?
In mongo method sort should be applied on cursor obtained by find:
$letter = "c";
$client = new MongoDB\Client();
$pme = $client->selectCollection("belgium", "pme");
$regex = new MongoDB\BSON\Regex ("^$letter", "i");
$query = array('name' => $regex);
// sort by field `name` happens here
$options = array("sort" => array("name" => 1), );
$cursor = $pme->find($query, $options);
I am trying to extract data from mysql database into a datatable using ajax, and php.
The code for my response.php file is below:
<?php
$result = mysql_query("select * from orders");
while ($row = mysql_fetch_array($result)) {
$data = array(
array(
'Name' => $row['jobnumber'],
'Empid' => $row['ID'],
'Salary' => $row['product']
)
);
}
$results = array(
"sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData" => $data
);
/*while($row = $result->fetch_array(MYSQLI_ASSOC)){
$results["data"][] = $row ;
}*/
echo json_encode($results);
?>
Why is this only returning one result in my front end table?
http://orca.awaluminium.com/test.php
link above shows table.
You're replacing value of $data instead of pushing new rows in an array.
Change the following line.
$data = array(
array(
'Name'=>$row['jobnumber'],
'Empid'=>$row['ID'], 'Salary'=>$row['product']
)
);
To
$data[] = array(
'Name'=>$row['jobnumber'],
'Empid'=>$row['ID'], 'Salary'=>$row['product']
);
Also put $data=array(); before string while() looop.
You have to do foreach
while ($row = mysql_fetch_array($result)){
foreach($row as $a)
{$data[] = array(
array('Name'=>$a['jobnumber'], 'Empid'=>$a['ID'], 'Salary'=>$a['product']),
);
}
}
i'm trying to get the best practice to manipulate my array to get a json in a format similar to this one (better to work with charts)
{
"serieMonth":["Aug-12","Sep-12","Oct-12","Nov-12","Dec-12","Jan-13","Feb-13"],
"serieCA":[4214,10119,13325,12818,7177,20628,7664],
"serieAdwordsCA":[0,0,0,0,0,310,332],
"serieBooking":[10,28,46,34,17,51,16],
"serieAdwords":[0,0,0,0,0,1,1],
"serieTotalBooking":[10,28,46,34,17,52,17],
"serieCartRepartition":[421,361,290,377,422,397,451],
"serieTotalCart":[421,361,290,377,422,397,451]
}
Actually my output looks like this :
[
{"date_year":"2012","date_month":"08","ad_cost":"0.0","ad_clicks":"0"},
{"date_year":"2012","date_month":"09","ad_cost":"0.0","ad_clicks":"0"},
{"date_year":"2012","date_month":"10","ad_cost":"0.0","ad_clicks":"0"},
{"date_year":"2012","date_month":"11","ad_cost":"0.0","ad_clicks":"0"},
{"date_year":"2012","date_month":"12","ad_cost":"44.9","ad_clicks":"43"},
{"date_year":"2013","date_month":"01","ad_cost":"297.56","ad_clicks":"462"},
{"date_year":"2013","date_month":"02","ad_cost":"82.5","ad_clicks":"103"}
]
And I'm using javascript to change it :
var xAxisLabels = new Array(),
adClicks = new Array(),
adCost = new Array();
$.each(data, function(i,v) {
xAxisLabels.push(v["date_month"]+'/'+v["date_year"]);
adCost.push(parseInt(v["ad_cost"]));
adClicks.push(parseInt(v["ad_clicks"]));
});
I'm looking for the best way to do it in php since I get this data by the google api, here is my php.
// dimensions
$dimensions = 'ga:year,ga:month';
$_params[] = 'date_year';
$_params[] = 'date_month';
// metrics
$metrics = 'ga:adCost,ga:adClicks';
$_params[] = 'ad_cost';
$_params[] = 'ad_clicks';
$response = $service->data_ga->get('ga:' . $projectId, $from, $to, $metrics, array('dimensions' => $dimensions));
$analyticsStats = array();
foreach ($response['rows'] as $row) {
$dataRow = array();
foreach ($_params as $colNr => $column) {
$dataRow[$column] = $row[$colNr];
}
array_push($analyticsStats, $dataRow);
}
You can build an array of arrays then add items the the sub-arrays in a loop:
$output = array(
"serieMonth" => array(),
"serieCA" => array(),
"serieAdwordsCA" => array(),
"serieBooking" => array(),
"serieAdwords" => array(),
"serieTotalBooking" => array(),
"serieCartRepartition" => array(),
"serieTotalCart" => array()
);
foreach($response["rows"] as $row) {
$output["serieMonth"][] = date("Y-M", strtotime("{$row['date_year']}-{$row['date_month']}-01"));
$output["serieCA"][] = $row["ad_cost"];
$output["serieAdwordsCA"][] = $row["ad_clicks"];
// etc...
}
echo json_encode($output);