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
Related
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::listDatabases()
this error keep showing when i wanted to use the administration command for mongodb using php. I do not know whats the problem here and someone with kind soul please help me. The following codes is what i have tried which cause that error.
<?php
$client = new MongoDB\Driver\Manager( 'mongodb+srv://'.$_ENV['MDB_USER'].':'.$_ENV['MDB_PASS'].'#'.$_ENV['ATLAS_CLUSTER_SRV'].'/test'
);
try{
$dbs = $client->listDatabases();
echo '<pre>';
print_r($dbs);
echo '</pre>';
// Or Nothing if you just wanna check for errors
}
catch(Exception $e){
echo "Unable to connect to Database at the moment ! ";
exit();
}
$colecciones = $client->listCollections();
foreach ($colecciones as $col) {
echo $col->getName();
}
?>
these two are the refereces that i used but is not working for me
Get collections in mongodb with PHP
Is there a way to test MongoDB connection in PHP?
what i am trying to do here is to make sure that my database connection is successful and also list out the collection name of my mongodb database.`
You are trying to call an undefined method in the MongoDB\Driver\Manager class
You can see the list of methods and functions here
https://www.php.net/manual/en/class.mongodb-driver-manager.php
In addition please follow all the listed function and methods in php mongodb driver.
Try to use this to query data from the database:
$manager = new MongoDB\Driver\Manager('mongodb+srv://'.$_ENV['MDB_USER'].':'.$_ENV['MDB_PASS'].'#'.$_ENV['ATLAS_CLUSTER_SRV'].'/test'
);
$filter = [];
$option = [];
$read = new MongoDB\Driver\Query($filter, $option);
$query = $mongo->executeQuery(‘db.Collection_Name’ $read);
$exportQuery = $query->toArray();
var_dump($exportQuery);
I need to turn an array into an XML file.
I have the following code:
<?php
$nouser = 'There is no user with that ID in the database.';
try {
$handler = new PDO('sqlite:Ebsco.db');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = '';
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
};
$query = $handler->query('SELEcT * FROM Users WHERE ID='.$name);
$User = $query->fetch(PDO::FETCH_ASSOC);
if ($User) {
$Serializer = &new XML_Serializer();
$XML = $Serializer->serialize($User);
print_r($XML);
print_r($Serializer);
}
else {
echo $nouser;
}
}
catch (PDOException $e) {
echo $nouser;
die();
}
?>
The code works fine for retrieving the array and passing it back to the html as an array, but I am having issues with the PEAR XML_SERIALIZER.
I have downloaded the files and placed them in the php/pear/xml folder (except for "package" which I left in the main pear folder, as I have no idea what it is meant to do), and checked the phpinfo() to make sure the include_path leads to php/pear.
However, when I add the XML_SERIALIZER, I get the following error:
Fatal error: Class 'XML_Serializer' not found in...
I am new to PEAR so I'm not sure if I installed everything correctly (other than putting the files in the library, is there anything else I need to do?), or if this is caused by another issue.
Thanx
You need to include the file manually, there is no autoloading with PEAR1 packages except you do that yourself.
require_once 'XML/Serializer.php';
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.
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.
It was always working for me but this time it's not.
conect.ini
conn = "mysql:host=localhost; dbname=%dbname%"
user = "root"
pass = "%passwd%"
conn1 = "mysql:host=%myRealHostAddr%; dbname=%dbname%"
user1 = "%user%"
pass1 = "%passwd%"
pdo
class prepeared {
const LOG = "lock/loginsStat.log";
private $_db;
private $dbc;
function __construct(){
$this->dbc = parse_ini_file($_SERVER["DOCUMENT_ROOT"]."/hours/lock/conect.ini");
try{
$this->_db = new PDO($this->dbc["conn"], $this->dbc["user"], $this->dbc["pass"]);
}catch(PDOException $e){
echo $e->getMessage();
}
}
etc....
Vars %var% are real values just changed them for this post.
Vars with 1 are working at the hosting just fine (without 1, it was added only for a local testing). When I take it to a local machine for some testing I'm adding this 1 to disable them and making a new vars for a local settings.
The error that I see now it's
invalid data source name
Any ideas why? I know that this configuration was working just fine when I used it couple weeks ago so I suspect there is no errors here. Probably I'm wrong...
Get rid of catch(PDOException $e){ echo $e->getMessage();} stuff in order to get full and useful error message instead of that stub you have at the moment.
var_dump($this->dbc); also helps a lot.