Handling $resource request from PHP backend using SLIM - php

I'm having problems accessing my PHP backend from AngularJS.
I have followed:
http://coenraets.org/blog/2012/02/sample-application-with-angular-js/
Routing with AngularJS and Slim PHP
Some other's too but those are similar. I've tackled the problem for a few days now and still can't get it working.
First way to call my php script
app.controller('PhoneDetailCtrl',function($scope, $modal, $resource) {
var request_Id = 1;
var Request = $resource('http://mobiiltelefonid24.ee/api/kasutatud_telefonid/'+request_Id);
$scope.request = Request.get();} //this way I get code 200 but 119 empty chars.. So I figure routing should be correct?
Second way I tried
app.controller('PhoneDetailCtrl',function($scope, $modal, Service) {
$scope.request = Service.get({id:1});} //this gives me code 200 but 119 empty chars...
app.service('Service', function ($resource) {
return $resource('api/kasutatud_telefonid/:id', {}, {
update: {method:'PUT'}
});});
PHP code (using mysql db)
require 'Slim/Slim.php';
$app = new Slim();
$app->get('/', 'getPopularPhones');
$app->get('/uued_telefonid','getNewPhones');
$app->get('/kasutatud_telefonid','getUsedPhones');
$app->get('/uued_telefonid/:id', 'getPhoneDesc');
$app->get('/kasutatud_telefonid/:id', 'getPhoneDesc');
$app->run();
/*Other get methods are exactly the same but with different name*/
function getPhoneDesc($id) {
$sql = "SELECT * FROM Phone";
try {
$db = getConnection();
$stmt = $db->query($sql);
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($wines);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
getConnection() is implemented as shown in wine app tutorial. There is one row in db that has 21 colums so it should return something. Also tried to pass string $wine="teststring" but that also arrived as jibbrjabbre.
Is routing wrong or is there problems with querying from db? (I can query just fine from phpMyAdmin). Out of ideas...

Solved! Slim was falsely configured and meekroDB worked just fine (Thanks mainguy). On top of that there were some issues on webhosts side.

Related

why am I unable to connect to the database?

I decided to practice for the first time the Slim framework and I am not using MAMP or XAMPP, but instead the php -S. So in the process I was trying to figure out how to create a database.
I decided to use SQLite to quickly create a database via command line. I believe I successfully created the tables and inserted data.
I tried to access it via my post.php file:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
// Get All Posts
$app->get('/api/posts', function(Request $request, Response $response){
$sql = "SELECT * FROM posts";
try{
// Get Database Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->query($sql);
$posts = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($posts);
} catch(PDOException $e ){
echo '{"error": {"text":'.$e->getMessage().'}}';
}
});
Unfortunately, in the browser I am getting this error:
{"error": {"text":SQLSTATE[HY000] [2002] No such file or directory}}
I am not sure if the problem is that I need to create the user and grant user privileges in SQLite or something else I may not be aware of. I have never worked with SQLite inside of the Slim Framework. Any direction will be much appreciated.

Does Laravel 5.3019 database Transaction method work?

I've use Larvel 5.0 with Database transaction all the method in my previous web application it work as well and we are really love it because this application help me much more than our estimated
so we have create another webs application by using this newest version of this framework and used the same Database structure but finaly it would not work for me and another one to.
I have as more peoples and post on some toturial website for asking any belp but not yet get any solution so I record this video for sure about this case.
Issue: My issue I've disabled (//commit()) method all data still can insert into Database.
final function Add()
{
if ($this->request->isMethod('post')) {
//No you will see this method use with Try Catch and testing again
//DB::beginTransaction(); // Ihave testing with outside of try and inside again
Try{
DB::beginTransaction();
$cats = new Cat();
$catD = new CategoryDescriptions();
$cats->parent_id = $this->request->input('category_id');
$cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
if (($res['result'] = $cats->save())== true) {
$catD->category_id = $cats->id;
$catD->language_id = 1;
$catD->name = $this->request->input('en_name');
if (($res['result'] = $catD->save()) === true) {
$catD2 = new CategoryDescriptions();
$catD2->category_id = $cats->id;
$catD2->language_id = 2;
$catD2->name = $this->request->input('kh_name');
$res['result'] = $catD2->save();
}
}
if(!empty($res)) {
//DB::commit();
}
return [$res,($res['result'] = $catD->save())];
}catch(\Exception $e){ // I have already try to use Exception $e without backslash
DB::rollback();
}
}
$cat = Cat::with(['CategoryDescriptions', 'children'])->where('status', 1)->get();
return view('admin.categories.add', ['cat' => $cat]);
}
You can check on my video to see that .
Check on my video
I don't know why your code did not work. But you can try with this code I think it's will work. Laravel transaction documentation
try{
DB::transaction(function)use(/*your variables*/){
// your code
});
}catch(\PDOException $exception){
//debug
}
If any exception occurs it will automatically rollback. If you want manual rollback then inside transaction you can throw a manual exception based on your logic.

Is this right way to use php oop and mysqli?

I am not very experienced in php oop. Moreover, when mysqli comes with php oop, it make me more confused about using it in best efficient way. Anyway, first look at my connection class:
<?php
//connectionclass.php
class connection{
public $conn;
public $warn;
public $err;
function __construct(){
$this->connect();
}
private function connect(){
$this->conn = # new mysqli('localhost', 'sever_user', 'user_password');
if ($this->conn->connect_error) {
$this->conn = FALSE;
$this->warn = '<br />Failed to connect database! Please try again later';
}
}
public function get_data($qry){
$result = $this->conn->query($qry);
if($result->num_rows>=1){
return $result;
}else{
$this->err = $this->conn->error;
return FALSE;
}
$result->free();
}
public function post_data($qry){
$this->conn->query($qry);
if($this->conn->affected_rows>=1){
return TRUE;
}else{
$this->err = $this->conn->error;
return FALSE;
}
}
}
?>
Now please structure of a php page which uses mysql database to store and get data:
<?php
//login.php
include('/include/connectionclass.php');
$db = new connection();
$query = "SELECT * FROM USERS WHERE user_country='India'";
$data = $db->get_data($query);
if($data){
while($row=$data->fetch_assoc()){
echo 'User Name: ':.$row["user_name"].' Age: '.$row["age"];
}
}
?>
So my login.php uses connection class to get data about users. All the things are running well. But one things made me confused. In connectionclass.php $this->conn is itself an object as it calls new mysqli. So this is an object inside another object $db. Moreover, When I am using $data = $db->get_data($query);, a result set is created inside object $db by method get_data, then this result set is copied into a variable $data inside login.php page.
So according to me, actually two result sets/data sets are creating here, one inside db object and one inside login page. Is it right way to use mysqli and php to get dataset from mysql database? Will it use more memory and server resources when the dataset is larger (when have to get large amount of data for many users)?
If it is not right way, please explain your points and please give me code which can be used efficiently for php oop and mysqli.

SLIM Application error. Code 8: Array to string conversion

I'm currently working in a mobile application (Front-end) which brings some data through a Php Slim backend from a MySQL database using PDO. This (Back-end) was developed by a team mate and works like a charm on his computer.
There's a GET route which is supposed to return some JSON data:
$app->get('/users', function () {
require_once 'controllers/User.php';
$user = new User();
$user->setJsonMode(true);
$user->setJoin('default');
$user->setSelect('user_id, user.role_id, role, name,
userName, email, picture, user.last_update');
echo $user->select();
});
The 'User' Controller as all of them, inherit from 'CtrlDB' controller.
If I try to access 'api/users' I get:
Type: ErrorException
Code: 8
Message: Array to string conversion
File: /home/shy-n/projects/tienda/api/controllers/CtrlDB.php
Line: 32
The line 32 is located at the CtrlDB constructor:
public function __construct($table,$fields,$idProperty,$relations) {
$dsn = DB_ENGINE.':host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8';
try {
$this->db = new PDO($dsn, DB_USERNAME, DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
$response = $this->response("error","Connection failed: " . $e->getMessage(),null);
echo $response;
exit;
}
$this->table = $table;
$this->idProperty = $idProperty;
$this->fields = $fields;
$this->relations = $relations;
$this->start = 0;
$this->limit = 25;
$this->select = "`".implode("`, `",$fields)."`";
}
In "echo $response" I get the error, and I have no clue what's going on.
He uses WAMP server with php 5.5.12
I'm using Arch Linux 64 Bits with LAMP with php 5.6.5. I have enabled both extensions
mysqli.so and pdo_mysql.so in my php.ini file.
I have imported the database used with phpmyAdmin, containing the same registers as my friend in the back-end.
In spite of all of this, he can get the JSON data accessing the /users route, but I can't.
Thanks in advance for your help.
instead of
echo $response;
try
echo json_encode($response);
you shouldn't be echoing out arrays

WSO2AS Soapcall of service returns null

I'm developing a web-app, which needs data from a database.
For the communication with the db I use WSO2AS.
I made a database and linked that to the data service created, when i test the service in the admin panel of WSO2, I get the data needed from the database.
The data service I created is called TestService.
Now I want to have the same response in my php template as well, using this code.
<?php
try {
$client = new SoapClient('http://192.168.178.12:9763/services/TestService?wsdl');
$result = $client->__soapCall('greet');
printf("Result = %s\r\n", $result->return);
} catch (Exception $e) {
printf("Message = %s\r\n",$e->__toString());
}
?>
But this gives NULL, when I try to dump the $result.
When I try to execute an example WSO2 created, I do get the right result. While the soapcall code is the same, only the service name is different.
<?php
try {
$client = new SoapClient('http://192.168.178.12:9763/services/HelloService?wsdl');
$result = $client->__soapCall('greet', array(array('name' => 'Sam')));
printf("Result = %s\r\n", $result->return);
} catch (Exception $e) {
printf("Message = %s\r\n",$e->__toString());
}
?>
This code returns "Hello Sam !!!".
So I wonder what I did wrong, I personally think I made a mistake in implementing the service itself, but can't find it.
If any more information is needed feel free to ask, hope someone can help me with this.
Thanks in advance!
Apparently you need to have arguments in your soapcall.
After calling this __soapCall('greet', array());
It gave the proper response.

Categories