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.
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 used Php Slim Framework for my API. I install the Slim Framework to my web root directory on my server and copy the index.php file I coded.
Index.php:
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->get('/user/:id', 'getUser');
$app->run();
function getConnection() {
$dbhost="localhost";
$dbuser="";
$dbpass="";
$dbname="";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function getUsers() {
$sql = "select * FROM manga";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
}
catch(PDOException $e) {
echo json_encode($e->getMessage());
}
}
?>
I am getting 500 (Internal Server Error).
Edit: I changed "$app = new Slim();" to the "$app = new \Slim\Slim();" then receive the below error.
I am using EasyEngine(Nginx).
Edit-2:Now 500 Internal gone but another error showing.
XMLHttpRequest cannot load http://api.mangayurdu.com/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://deneme.mangayurdu.com' is therefore not allowed access.
Here is my code that getting JSON data:
.factory('MY', function($http){
var factory = {};
var url = 'http://api.mangayurdu.com/users?callback=JSON_CALLBACK';
factory.isimler = $http.get(url);
return factory;
})
From the posted code it looks like Slim can't find a function called getUser. getUsers() is defined in your code, but no getUser() function.
try putting this in the start of your PHP page
<?php header('Access-Control-Allow-Origin: *');?>
I am trying to get results from an API call using Slim connecting with MSSQLSERVER2012
the example used to work with MYSQL getconnection function (see below) but when I am trying to
connect with MsSQL server 2012 I am getting an error like "api call error "invalid data source name"
http://localhost/msapi/api.php/clients
1'api call error "invalid data source name"
require '/Slim/Slim.php';
$app = new Slim();
$app->get('/clients', 'getClients');
$app->run();
function getClients() {
$sql = "select * FROM clients";
try {
$db = getConnection();
$stmt = $db->query($sql);
$clients = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"client": ' . json_encode($clients) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function getConnection_MYSQL() {
$dbhost="SERVER";
$dbuser="USER";
$dbpass="PASSWORD";
$dbname="DB";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function getConnection() {
$dbhost="SERVER";
$dbuser="USER";
$dbpass="PASSWORD";
$dbname="DB";
$dbh = new PDO ("ADODB.Connection");
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$dbhost.";UID=".$dbuser.";PWD=".$dbpass.";DATABASE=".$dbname;
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->open($connStr); //Open the connection to the database
return $dbh;
}
the function getConnection_MYSQL() is an example that works.
But the getConnection() tryis to connect with MS SQL server ?
Do you see why I am getting an "invalid data source name" with the function getConnection()?
Since you didn't post an alternative DSN-string, I'm assuming you are using the one from your example and just replace host, username and password. This won't work.
When you are running your Slim-application on a windows host you can (and should) use Microsoft's SQL Server Driver for PHP (sqlsrv).
There are 2 versions sqlsrv.dll and pdo_sqlsrv.dll. When you want to reuse most of your code you should use the latter. This way you probably only have to modify your DSN (see php docs):
new PDO("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");
If you are using the first you have to update the way you connect to the db and create the query. You can read the Beginner's Guide to see a few examples that should make it easy.
If you are running not running your application on a Windows-machine you will probably have to set up ODBC and FreeTDS and then use PDO with an ODBC-DSN. From my experience this will be quite a lot of work, but there are a few good tutorials out there. Just google for "freetds sql server".
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.
This question already has an answer here:
How to use PDO connection in other classes?
(1 answer)
Closed 2 years ago.
Hello i am new to PDO with MYSQL, here are my two files
1) index.php
require_once 'prd.php';
try{
$db = new PDO ('mysql:host=xxxx;dbname=xxx;charset=utf8', 'xxx', 'xxxx');
echo 'connectd';
}catch(PDOException $conError){
echo 'failed to connect DB' . $conError->getMessage ();
}
$conn = new prdinfo();
$conn->con($db);
2) product.php
class prdinfo{function con($db){
try{
foreach($db->query("select * from products where vendor_id = 2" ) as $row){
$prod_id = $row ['product_id'];
echo '<br/>' . $prod_id;
}
}catch(PDOException $ex){
echo 'an error occured' . $ex->getMessage();
}
}
}
my problem is here i can pass the connection object to every file, but i have so many files to use database queries, so i need to pass the $bd to all the files. this is getting burden on the code. so is there any way to connect the database with PDO.
Thanks
pdo.php, taken from here. People often overlook many important connection options, so I had to write a dedicated article that explains how to connect with PDO properly
product.php
<?php
class prdinfo
{
function __construct($db)
{
$this->db = $db;
}
function getVendor($vendor)
{
$sql = "select * from products where vendor_id = ?";
$stm = $this->db->prepare($sql);
$stm->execute(array($vendor));
return $stm->fetchAll();
}
}
index.php
<?php
require 'pdo.php';
require 'product.php';
$info = new prdinfo($pdo);
$vendor = $info->getVendor(2);
foreach ($vendor as $row)
{
echo $row['product_id'];
}
It would be also a good idea to implement class autoloading instead of manually calling require.
The simplest way of doing it is to do the database connectivity in a separate file like "database.php and then you can include this file on every new page you are creating...eg if you are creating a page like "dothis.php". then at the top of your dothis.php page write a statement include_once ('/path/to/your/file/database.php');
then you can use your $db object in the whole file wherever you want.
What you can do is to create a PHP file, let's say 'pdoconn.php'. In that file, prepare that $db object. Finally, for each of your PHP files, just include pdoconn.php at first. So, while your PHP files are being loaded, they will firstly connect to MySQL and give you the $db object.