SQL Syntax and Columns using PHP - php

(This is called via PHP) I have the following:
"SELECT name FROM user WHERE uid IN (SELECT uid1 FROM friend WHERE uid2={$user})"
The SQL executes perfectly fine, however, the result is an array where the key is "name". I would like each result's key to be the respective uid in user that was searched to pull that name.
Example:
How it is right now
If the name was "Bob" and his uid was "12345", I would like the return array to be - [name] => Bob.
How I would like it to be
If the name was "Bob" and his uid was "12345", I would like the return array to be - [12345] => Bob.
EDIT (as per the comment request):
$fql = "SELECT pic FROM user WHERE uid IN (SELECT uid1 FROM friend WHERE uid2={$user})";
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$result = $facebook->api($param);

$newResult = array();
foreach ($result as $entry)
{
$newResult[$entry['uid']] = $entry['name'];
}

Related

How to encode an array of data and save to a pivot table laravel

All I want here is to be able to save all the ID's of services into the pivot table associated with the given keywords/tags but at the moment all it does is that it takes the last ID of the created object and saves into the pivot table with different keywords. let's say for example I enter [id1 => service1, id2 => service2] and [id1 = > keyword1, id2 => keyword2, id3 => keyword3] instead of it saving only id2 of service2 and all the keywords I want it to save all the Ids of all of the services and the keywords. I hope it makes sense
foreach($params['service'] as $key => $value){
$service = Service::firstOrNew(['service' => $value, 'price' => $params['price'][$key], 'business_id' => $params['business_id']]);
$service->service = $value;
$service->price = $params['price'][$key];
$service->business_id = $params['business_id'];
$service->save();
}
foreach($params['keywords'] as $keyword){
$cleaned_keyword = self::cleanKeywords($keyword);
$newKeyword = Keyword::firstOrNew(['keyword' => $cleaned_keyword]);
$newKeyword->keyword = $cleaned_keyword;
$newKeyword->save();
$service->keywords()->syncWithoutDetaching([$newKeyword->id => ['business_id' => $params['business_id']]]);
}
This is something I would expect but it is tricky because a single or 2 services for example can have multiple keywords. NOTE: I had manually changed these values in the database
These are the results from a dd($params)
Based on the dd($params).attached is the result,only
"service" => array:2[
1 => "Mobile development"
]
was saved in the pivot table and got assigned all the keywords
Please correct me if this is a good approach, I managed to solve this by having an inner loop.
foreach($params['service'] as $key => $value) {
$service = Service::firstOrNew(['service' => $value, 'price' => $params['price'][$key], 'business_id' => $params['business_id']]);
$service->service = $value;
$service->price = $params['price'][$key];
$service->business_id = $params['business_id'];
$service->save();
foreach($params['keywords'] as $keyword) {
$cleaned_keyword = self::cleanKeywords($keyword);
$newKeyword = Keyword::firstOrNew(['keyword' => $cleaned_keyword]);
$newKeyword->keyword = $cleaned_keyword;
$newKeyword->save();
$service->keywords()->syncWithoutDetaching([$newKeyword->id => ['business_id' => $params['business_id']]]);
}
}

PDO: group a property instead of duplicate lines

Good morning,
I have a request that return me several information for a reservation and each reservation can be linked to several room.
Is it possible to have an array of room instead of duplicate the line each time they are multiple rooms for a reservation.
What I want:
[
idReservation1 => [
"client_name" => "kévin titi",
"checkin" => "2017-08-08",
"d_checkout" => "2017-08-10",
"email" => "titi#gmail.com",
room_id => [1,2,3,9]//here I want an array
],
idReservation2 => [
"client_name" => "firstname lastname",
"checkin" => "2017-08-18",
"d_checkout" => "2017-08-20",
"email" => "toto#gmail.com",
"room_id" => [1,12,13,9]//here I want an array
]
]
if the idReservation is not the key does not matter, the important here is to have an array for room_id
I have looked all PDO fetch modes but they don't seems to match to my problem.
My request:
$prep = $this->pdo->prepare("
SELECT re.id as resId, re.client_name, re.d_checkin, re.d_checkout, re.mail, ro_re.room_id as room
FROM Reservation re
JOIN Room_Reservation ro_re ON ro_re.reservation_id = re.id
WHERE re.confirmed = false
");
Thanks
Assuming that you are working with MySql: the solution using GROUP_CONCAT function(to group room ids for each reservation):
$stmt = $this->pdo->prepare("
SELECT
re.id as resId, re.client_name, re.d_checkin, re.d_checkout, re.mail,
GROUP_CONCAT(ro_re.room_id SEPARATOR ',') AS room_ids
FROM
Reservation re
INNER JOIN Room_Reservation ro_re ON ro_re.reservation_id = re.id
WHERE re.confirmed = false
GROUP BY re.id
");
$stmt->execute();
// `room_ids` column will contain a string like "1,2,3,9"
$result = [];
foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
$row['room_ids'] = explode(',', $row['room_ids']); // converting string with room ids into array
$result[] = $row;
}

retrieving data from two tables into multidimensional array api json response

I am learning Api development where i want to retrieve data from two tables
First table (items) contains:
id, feed_id, title, author, content
Second table (feeds):
feed_id,title,url
I want to get Json response like:
{
- stories :
[
id
feed_id {
title,
url
}
title
author
]
}
My PHP function to retrieve story biased on id is like:
$app->get('/stories/:id', 'authenticate', function($story_id) {
$response = array();
$result = Database::get('db')->table('items')
->eq('rowid', $story_id)
->findOne();
//$response["error"] = false;
if ($result != NULL) {
$response['stories'] = array(
'id' => $result["id"],
'feed_id' => $result["feed_id"],
'title' => $result["title"],
'isBreaking' => $result['isBreaking'],
'author' => $result['author'],
'updated' => $result["updated"],
'url' => $result['url'],
'content' => $result["content"]);
echoRespnse(200, $response);
}
else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
The result i get is like:
{
- "stories": [
{
id
feed_id
title
url
}
]
}
How can i retrieve data from the second tablet (feeds) biased on feed_id and get the data into sub array?
as #MikeBrant mentioned you have to use join between two tables to retrieve correct data. the plain query will be something like this:
select items.id, items.title, items.author, items.content, feeds., feeds.title as feed_title, feeds.url from items left join feeds on items.feed_id = feeds.feed_id
and then change your $response['stories'] like this:
$response['stories'] = array(
'id' => $result["id"],
'feed_id' => array(
'title' => $result["feed_title"],
'url' => $result["url"]
),
'title' => $result["title"],
.
.
.
);
you get the idea :)

Querying for keywords in photos using DynamoDB and PHP

Requirement: I'm storing photos in S3 and want the user to be able to lookup all photos that contain a keyword they type in on a webpage.
My solution: I have created 2 tables:
tblPhotos:
Primary Key=HashKey: PhotoID
Fields:
PhotoID,
S3Location
tblKeywords:
Primary Key=HashKey (HashID) and RangeKey (Keyword)
Fields:
HashID (always set to 1),
Keyword (one big string; the keyword followed by PhotoID)
S3Location
I'm using the following php code to find all records that have my keyword in it:
$table_name = 'tblKeywords';
$keywordresponse = $dynamodb->query(array(
'TableName' => $table_name,
'HashKeyValue' => array(AmazonDynamoDB::TYPE_STRING => '1'),
'RangeKeyCondition' => array(
'ComparisonOperator' => AmazonDynamoDB::CONDITION_BEGINS_WITH,
'AttributeValueList' => array(
array(AmazonDynamoDB::TYPE_STRING => $_GET['sSearch'])
),
)
));
if ($keywordresponse->isOK())
{
foreach ($keywordresponse->body->Items as $item)
{
$aaData[] = array(
'Keyword' => (string) $item->Keyword->{AmazonDynamoDB::TYPE_STRING},
'S3Location' => (string) $item->S3Location->{AmazonDynamoDB::TYPE_STRING}
);
}
echo json_encode(array('keywordstatus' => 1, 'aaData' => $aaData));
}
else
{
echo json_encode(array('keywordstatus' => 0));
}
As you can see I'm passing sSearch as the keyword to filter results on. My question is, do you know a better way to achieve this filtering of records using DynamoDB query? I'm trying to avoid a scan as its very inefficient, although my solution above whilst it works doesn't seem particularly elegant!
If your primary goal is to be able to return all the photos for a given key word I think the following schema would make more sense:
HashKey = Keyword
RangeKey = PhotoID
Additional possible fields: S3Name (if it is not the same as PhotoID)

How To Fetch Facebook Activity Feed of A Particular User

Do any one know how to fetch activity feed of an user who is associated with an app id ?
I am able to fetch the list of users who are associated with an app id by using this code
<?php
require "facebook.php";
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
$user = $facebook->getUser();
if ($user) {
try {
$result = $facebook->api(array(
"method" => "fql.query",
"query" => "SELECT uid, name, pic_square, activities FROM user
WHERE uid IN (SELECT uid1 FROM friend WHERE uid2 = me()) and is_app_user"
));
echo "<pre>";
print_r($result);
?>
Output
Array
(
[0] => Array
(
[uid] => 14529121124
[name] => Saurabh
[pic_square] => http://profile.ak.fbcdn.net/hprofile-ak-ash4/187195_1452918224_6692287_q.jpg
[activities] =>
)
[1] => Array
(
[uid] => 100000565666371
[name] => Abhijeet
[pic_square] => http://profile.ak.fbcdn.net/hprofile-ak-prn1/157718_100000289210371_1409561577_q.jpg
[activities] =>
)
)
Now i just want to fetch activity feed of these 2 users (User Id: 14529121124 , 100000565666371) individually who are associated with this (54975723243503) app_id.
Use graph API : https://developers.facebook.com/docs/reference/api/user/
Search for "feed" in that page
You need to query the FQL stream table or the Graph API feed object:
Since you're working with FQL, I'll give an example using FQL. I did some quick testing, and the stream table doesn't allow you to use the IN keyword to select streams from multiple sources, so you'll need to make two separate calls, first to get the user_ids, second to get the stream.
Try this:
$queries = array();
$i = 0;
foreach ($result as $item) {
$queries['user_stream'.$i] =>
"SELECT source_id, created_time, message, attachment FROM stream
WHERE source_id = " . $item['uid'];
$i++;
}
$result2 = $facebook->api(array(
"method" => "fql.multiquery",
"queries" => json_encode($queries)
));

Categories