Im trying to create a rest api in slim.php. What i want is actually just two function. one for retrieving all records from a table as JSON. and one for retrieving a record by its ID.
This far my index/api file looks like this below. Now how do i connects do the database? How do i return it as json?
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get(
'/',
function () {
echo "hola!";
}
);
$app->run();
I have manage to get something going. I get the result back, but not as pure json. I can't see it as son in the console. Even tjo it gets written out in the browser. Current code:
$app->get('/', function () {
$db = connect_db();
$result = $db->query( 'SELECT * FROM test;' );
while ( $row = $result->fetch_array(MYSQLI_ASSOC)){
$data[] = $row;
}
echo json_encode($data);
});
A restfull route will look something like :
api/resources // to get all records
api/resources/{id} // to get a specific record
If you're using MVC architecture then in your controller you'll have two methods, one to get all records and the other to get a specific record. I'm not sure which interface Slim implements to connect to database but you can google it.
to return your result as json, you can use PHP's built-in function json_encode :
// $result = SQL query
return json_encode($result);
And I think you should think about paginating your recovered data, because returning a big number of data as json is not a good practice.
Good luck.
Related
I am using the icontact php api. I want to get the last contact who entered the list so in the icontact api php I have this:
<php
public function getContacts() {
// Make the call and return the data
return $this->makeCall("/a/{$this->setAccountId()} /c/{$this->setClientFolderId()}/contacts?listId=49626&status=total&createDate=2015-02-16&createDateSearchType=gt", 'GET');
}
?>
than I use this to call it:
<?php
$oiContact = iContactApi::getInstance();
try {
var_dump($oiContact->getContacts());
} catch (Exception $oException) { // Catch any exceptions
var_dump($oiContact->getErrors());
}
$obj = $oiContact->getLastResponse();
$data = json_decode($obj,TRUE);
echo $data['contacts'][0]['email'];
echo $data['contacts'][0]['commitmentscore'];
echo $data['contacts'][0]['firstName'];
echo $data['contacts'][0]['phone'];
?>
It keeps giving me the same contact it is because the 0 in the echo but how can I make that a variable or an if condition just not sure how
paste bins with full code
http://pastebin.com/SBf73UNb //call
http://pastebin.com/CuGcCvU1 //api
This worked
/contacts?listId=49626&orderby=createDate:desc&limit=1", 'GET');
Got it from this page
http://www.icontact.com/developerportal/documentation/advanced-users/
I think you can use orderby option,
check this link
sample they used
Get all contacts on a list ordered by First Name GET https://app.sandbox.icontact.com/icp/a/<accountId>/c/<clientFolderId>/contacts?orderby=firstName
Instead of firstname you can use date, something like normal SQL query doing then fetch only first contact.
Also the return data will be always array so you have to run within a foreach for iterate the data.
Hope it helps.
I'm working on a project and I would like know which is the best way for show the data after having insert a record on the database having an complex structure html between use the structure in php or jQuery and why?.
Example of scenario:
I'm building a system of posts and comments. When the user write the post and publish it an call ajax trigger the function php and it insert the information on the database. until here all ok, but then I have to display the message insert on the wall of the user, so which the best way for display that post insert?
There are so many different way, but which is the best keeping attention on speed, security, and compatibility?
some example, suggest are welcome:
<script> // default example of call ajax
$.ajax({
type: "POST",
url: 'http://localhost/ajax_ouput_post',
dataType: 'json',
data: { id_user : 1, title : "Hello everyone", content : "Good morning" },
success: function(html) {
// output under php example
},
error: function(){
alert('Error on ajax call');
}
});
</script>
1- I create the template for the output in php.
<?php
function ajax_output_post() {
$title = $_POST['title'];
$content = $_POST['content'];
$id_user = $_POST['id_user'];
// all the check for the input
$query = // insert data on mysql #return id_post;
$select_last_post_mysql = // select the last query from the db using id_user and id_post
foreach ($select_last_post_mysql as $post) {
$template = // html structure;
$template .= // continue html structure;
if ($post->photo == 1) {
$template .= // <div>photo user</div>
}
$template .= // ecc...
}
echo json_encode(array('template' => $template));
}
?>
jquery output
<script>
$(#wall).append(html.template);
</script>
php second example with output jQuery template
<?php
function ajax_output_post() {
$title = $_POST['title'];
$content = $_POST['content'];
$id_user = $_POST['id_user'];
// all the check for the input
$query = // insert data on mysql #return id_post;
$select_last_post_mysql = // select the last query from the db using id_user and id_post
foreach ($select_last_post_mysql as $post) {
$title_json = $post->title;
$content_json = $post->content;
if ($post->photo == 1) {
$photo_user_json = $post->photo_user;
} else {
$photo_user_json = "";
}
$id_post = $post->id_post;
}
echo json_encode(array('title' => $title_json, 'content' => $content_json, 'id_post' => $id_post));
}
?>
jquery
<script>
// in jquery
var Template = {
main_container: "<div class='post_container' data-post='" + html.id_post + "'>",
title: "<div class='title'>" + html.title + "</div>",
content: "<div class='content'>" + html.content + "</div>",
close_main: "</div>",
run: function() {
return Template.main_container + Template.content + Template.close_main;
}
};
$('#wall').append(Template.run());
</script>
Well, there is not really a 'best' way to do this, it always depends on the concrete situation.
In your case you could:
simply attach the user post to the DOM via javascript, without knowing whether it was inserted to the database or not (because you have all data of the post at client side available, you do not need to select it again)
attach the user post by javascript (like in the point above) after you know it was inserted (in the success handler, but still no data in response from php)
I would recommend not to select the inserted data again anyway, except you need an auto generated value like id or inserted-timestamp, instead you could simply return the values of the request in your response after the insert.
Hope this helps.
There are a few ways to accomplish this, and there are tradeoffs to be made for each of them.
The simplest way to accomplish this is to retain the user input in javascript as answered by Nico above. The pro for this method is it is very simple to accomplish and move on to other problems and due to this simplicity, has few moving parts to be misused. The major con for this method is that it means the frontend is making blind assumptions about what is going on when the backend logic processes the data, which presents the risk of misinforming the user about what happened if the backend silently fails, and this sort of bug is often difficult to catch until it bites someone and they complain. This is probably your best answer for simple use cases, but if you intend to scale it or introduce significant complexity this makes the likelihood of bugs high and should be replaced.
As per your given example, you seem to be on this frame of thought already. So to address each of your given concerns, first I would say that compatibility is best addressed by being generally unopinionated. This is appropriate for a library meant to be used for general consumption, but is not necessarily preferable for a private project or internal business logic, which require opinion to execute a specific desired result. The major caveat in terms of compatibility is that templating is handled by the frontend at least as often as the backend. It may in some cases be done in ReactJS or Angular, or it may be done on the backend by Twig, or any number of other things. If you want wide compatibility, then this should have some configuration for whether to pass response in raw format or accompanied by a template. In the case of private business logic or an app you are building with a specific purpose, the underlying point is to accomplish a specific result, and either using the existing templating structure of the system or picking one and sticking to it is preferable so you are focusing on the end goal and not getting distracted. But either way a github library author and a app developer would likely solve this same problem in completely different ways, and neither of them are wrong.
In terms of security, the typical concerns all apply. Individual approach is mostly arbitrary, provided you cover these bases if user input is being output, entered into template content, or stored in a database.
In terms of speed, the javascript DOM option is always going to be the fastest. However you can make it almost as fast depending how much tolerance for optimization you have. You could perhaps use client side storage to cache unmodified templates client side, and just use a hash of the template content as its identifying key so it automatically flushes when you change the template on the server. If you then send the key to the server and it matches, you don't need to serve the template in the response body because the client already has the correct one. If the template hash on the backend is different, you serve the new one, bust the storage cache for that template and replace the key and value with the new one. This will make the template body, which is almost certainly the longest part of the response, only need to be sent when changes are made. You would need to inject the values into the static template clientside to do it this way, and still obtain those from the server on each request. On the backend, you do not want to make a separate SELECT statement. You want to store the values in an array and just return those if your INSERT query is successful, like maybe something like this:
<?php
// List of keys that MUST be present for the query to succeed. Don't bother calling the db if any of these did not come in the request.
$expected_keys = [
'id_user',
'title',
'content' // add whatever else has to be passed
];
// key/val for db insert
$vals = [];
try {
// verify expected keys are provided
foreach ( $expected_keys as $k => $expected ) {
if !(array_key_exists ( $expected, $_POST ) ) {
// not a valid post, return an error
throw new \InvalidArgumentException( sprintf( 'Expected field [%1$s] was not provided. ', $expected ) );
}
// retain the field in $vals for insert
$vals[ $expected ] = $_POST[$expected];
}
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
];
$pdo = new \PDO($dsn, "username", "password", $options);
$stmt = $pdo->prepare(
'INSERT INTO `myTable` ( `:' .
implode( '`, `:', array_keys( $vals ) ) .
'` ) VALUES (' .
implode( '", ":', $vals ) .
');'
);
$stmt->execute( $vals );
$stmt = null;
}
// User error
catch \InvalidArgumentException $e {
// return 400 Bad Request and $e->getMessage() as the error message
}
// Server error
catch \Exception $e {
// log or whatever and return a 500 error
}
// return success with whatever you need to send back from $vals or $_POST
I am using the "elastica" php client for ElasticSearch.
I'm a bit new to OO-programming, especially in php.
However, I have managed to search my elasticsearch server using the elastica php client and store the response in an "Elastica_ResultSet" object. I have had no luck accessing the contents of that object whatsoever.
I would like to be able to list the total number of results, find an elasticsearch record id of a result and get the full content of an elasticsearch record for that result.
The Elastica class reference can be found here http://ruflin.github.com/Elastica/api/index.html , although I don't know what to do with it.
Here is the php code I have been using to get this far:
<?php
function __autoload_elastica ($class) {
$path = str_replace('_', '/', $class);
if (file_exists('extentions/' . $path . '.php')) {
require_once('extentions/' . $path . '.php');
//echo "$path EXISTS!!!";
}
}
spl_autoload_register('__autoload_elastica');
// New ES Client
$client = new Elastica_Client();
// Set Index
$index = $client->getIndex('test1');
// Set Document Type
$type = $index->getType('user');
// Perform Search
$resultSet = $index->search('halo');
?>
So basicaly you can use var_export to output your resultset
But in general the elastica search returns a Elastica_ResultSet object which has several attributes you can use like count, totalHits facets and so on.
and also holds an array of Elastica_Result objects these can be accessed either by calling the Elastica_ResultSet getResults() method or by using the current() and next() methods or by simply using the php foreach function
The Elastica_Result the data of the results and also has several methods you can use.
getId(), getVersion(), getData() and so on.
// Set Document Type
$type = $index->getType('user');
// Perform Search
$resultSet = $index->search('halo');
// Get IDs
$resultIDs = array();
foreach($resultSet as $result){
$resultIDs[] = $result->getId();
}
I would like to let you know something that was a bit hard for me to get.
The query and the sorting of results
// Set the query terms for your search
$queryTerm = new Elastica_Query_Terms();
$queryTerm->setTerms('user', array("test", "test1"));
// Create the sorting array
$sort = array("user" => array("order" => "desc"));
// Create the query
$query = Elastica_Query::create($queryTerm);
// Set the sorting to the query
$query->setSort($sort);
// Perform the search
$resultSet = $index->search($query);
Hope this helps
After a couple of months OO practise, it seemed performing a simple var_dump($resultSet) would have provided me with the structure and contents of the returned object... can't believe that nobody made any suggestions for such a basic question ;)
hi i am useing zend Gdata Library for youtube videos i am trying to show more then 20 videos or i can set how much videos i want to show but i found no options
$yt = new Zend_Gdata_YouTube();
$videoFeed = $yt->getUserFavorites('liz');
is there a way to get more then 20 videos or less Zend Gdata default is 20
you can view here
http://framework.zend.com/manual/en/zend.gdata.youtube.html
After some more research I think I found some solution.
Check there http://code.google.com/apis/youtube/2.0/developers_guide_php.html#Pagination
You should write recursive function loop trough video feed pages. For my app it was something like this (method in class):
<?php
//...
protected function build_favs_html($videos) {
//just saving html here. Mind the .= operator.
// I think you'll be doing this in some other way
$this->_html_response .= View::factory('videos')
->set('videos', $videos)
->set('type', 'load_favs');
// See whether we have another set of results
try {
$videos = $videos->getNextFeed();
}
catch (Zend_Gdata_App_Exception $e) {
//break function execution if there are no more result sets
return null;
}
//if there are result sets we continue calling same function on and on
$this->build_favs_html($videos);
}
I'm not sure if this can be done when requesting user favorites, as I've never used that feature, but when requesting videos via search terms you can set the results number via the setMaxResults method. You might be able to work this in with your user favorites request.
Here's a snippet of code we use:
$yt = new Zend_Gdata_YouTube();
$yt->setMajorProtocolVersion(2);
$query = $yt->newVideoQuery();
$query->setOrderBy('viewCount');
$query->setSafeSearch('strict');
$query->setFormat($searchFormat);
$query->setVideoQuery($searchTerms);
$query->setMaxResults($limit); // number of returned results set here
$query->setStartIndex($offset);
$results = $yt->getVideoFeed($query->getQueryUrl(2));
I'm creating a CMS for my client to work with his photographs and to sell them on his site. For the CMS end as well as the front end, which both will be all AJAX, it'd be nice to get a JSON feed setup so that I can just use the same feed to generate new "pages" and "views" with JS.
So this example feed would have like {[name:'A Photo',description:'lorem ipsum...'],[...]} and then with jQuery or JS i can create a table of all his photographs, pages, etc. How can I set this up for myself?
Should I just create a PHP file that gets all the data from the MongoDB put's it in an array than convert the array to JSON?
$cursor = $this->collection->find($params);
$return = array();
$i=0;
while( $cursor->hasNext() )
{
$return[$i] = $cursor->getNext();
// key() function returns the records '_id'
$return[$i++]['_id'] = $cursor->key();
}
return json_encode($return);
That is how I return JSON frrom Mongo.
I did it this way:
$cursor = $collection->find($params);
if($cursor->hasNext())
{
return json_encode(iterator_to_array($cursor));
}
If you need the _ids, check this answer to see why you're not getting them:
MongoDB PHP: How do I get ObjectId with a JSON feed? (it's blank)
This is what I do :
$data = json_decode(json_encode(iterator_to_array($cursor, true)));
this way I make sure I have an array of objects that you can properly call :
foreach($data as $doc){
echo 'title:'.$doc->title.'<br>';
}