Slim 3 Giving 404 when passing parameters

Hi Team,

Need your help i am very new for API world, recently I installed slim 3 along with php7 and Apache 2.6 via composer, Installation has done successfully, and i am able to create and run first Hello Program and other API where no parameter is required.

Working.
http://192.168.0.205/api/another.php/wines outcome received.
{“wine”:
[{“id”:“2”,“name”:“aaa”,“grapes”:“sss”,“country”:“cc”,“region”:“dd”,“year”:"2016-07-04

16:43:36",“description”:“eeee”},{“id”:“1”,“name”:“piper”,“grapes”:“green”,“country”:"(IN",“region”:“Delhi”,“year”:“2016-07-05
16:34:27”,“description”:"very old "}]}

Not Working ( but when i am passing parameters it start getting me 404 error pages.

http://192.168.0.205/api/another.php/wines/1 ( give 404 page) .

I have also check .htaccess option same situation with or without another.php file. this happen.

Need your input and help to fix his issue.

-------------------------------------------------------------another.php-------------------------------------------

<?php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; require 'slim/vendor/autoload.php'; require 'db.php'; $app = new \Slim\App; $app->get('/hello/{name}', function (Request $request, Response $response) { $name = $request->getAttribute('name'); $response->getBody()->write("Hello, $name"); return $response; }); $app->get('/wines/:id','getWine', function ($id) { print $id; }); $app->get('/wines', 'getWines'); //$app->get('/wines/:id', 'getWine'); $app->get('/wines/search/:query', 'findByName'); $app->post('/wines', 'addWine'); $app->put('/wines/:id', 'updateWine'); $app->delete('/wines/:id', 'deleteWine'); $app->run(); function getWines() { $sql = "select * FROM wine ORDER BY name"; try { $db = getConnection(); $stmt = $db->query($sql); $wines = $stmt->fetchAll(PDO::FETCH_OBJ); $db = null; echo '{"wine": ' . json_encode($wines) . '}'; } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; debug_print_backtrace(); } } function getWine($id) { $sql = "SELECT * FROM wine WHERE id=:id"; try { $db = getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("id", $id); $stmt->execute(); $wine = $stmt->fetchObject(); $db = null; echo json_encode($wine); } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; debug_print_backtrace(); } } function addWine() { $request = Slim::getInstance()->request(); $wine = json_decode($request->getBody()); $sql = "INSERT INTO wine (name, grapes, country, region, year, description) VALUES (:name, :grapes, :country, :region, :year, :description)"; try { $db = getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("name", $wine->name); $stmt->bindParam("grapes", $wine->grapes); $stmt->bindParam("country", $wine->country); $stmt->bindParam("region", $wine->region); $stmt->bindParam("year", $wine->year); $stmt->bindParam("description", $wine->description); $stmt->execute(); $wine->id = $db->lastInsertId(); $db = null; echo json_encode($wine); } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } } function updateWine($id) { $request = Slim::getInstance()->request(); $body = $request->getBody(); $wine = json_decode($body); $sql = "UPDATE wine SET name=:name, grapes=:grapes, country=:country, region=:region, year=:year, description=:description WHERE id=:id"; try { $db = getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("name", $wine->name); $stmt->bindParam("grapes", $wine->grapes); $stmt->bindParam("country", $wine->country); $stmt->bindParam("region", $wine->region); $stmt->bindParam("year", $wine->year); $stmt->bindParam("description", $wine->description); $stmt->bindParam("id", $id); $stmt->execute(); $db = null; echo json_encode($wine); } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } } function deleteWine($id) { $sql = "DELETE FROM wine WHERE id=:id"; try { $db = getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("id", $id); $stmt->execute(); $db = null; } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } } function findByName($query) { $sql = "SELECT * FROM wine WHERE UPPER(name) LIKE :query ORDER BY name"; try { $db = getConnection(); $stmt = $db->prepare($sql); $query = "%".$query."%"; $stmt->bindParam("query", $query); $stmt->execute(); $wines = $stmt->fetchAll(PDO::FETCH_OBJ); $db = null; echo '{"wine": ' . json_encode($wines) . '}'; } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } } function getConnection() { $dbhost="localhost"; $dbuser="root"; $dbpass=""; $dbname="api"; $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $dbh; } ?>

Regards
Anupam

Could you try:

$app->get('/wines/{id}','getWine', function ($id) {
    print $id;
}); 

Instead of:

$app->get('/wines/:id','getWine', function ($id) {
    print $id;
}); 

Placeholders have to start with { and end with }. There is more information on placeholders in routes in the docs.

Thanks for helping to fix issues i am facing, really appreciate.

Yes when i did changes as per your suggestion, i can able to fix 404 error however it now stuck on another error seems related to value of $id in sql query ( conversion issue)
“Catchable fatal error: Object of class Slim\Http\Request could not be converted to string in /var/www/html/slim/public/api/index.php on line 70”

if simple use
$sql = “SELECT * FROM wine WHERE name=’$id’”;

if i hardcore the value of name of below sql it api work with fix value as expected just for testing.
$sql = “SELECT * FROM wine WHERE name=‘1’”;

if
use $id = (int) $id;

showing same error but result come
$sql = “SELECT * FROM wine WHERE name=’$id’”;

Kindly suggest how to manage if parameter is int or string or any value just like in practical situation.

----------------------------------------------------------------------------code---------------------------------

$app->get(’/wines/{id}’, ‘getWine’, function ($id){
});

function getWine($id) {
//$id = (int) $id;
$sql = “SELECT * FROM wine WHERE name=’$id’”;

try {
    $db = getConnection();
   $stmt = $db->query($sql);
    $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
    $db = null;
    echo '{"wine": ' . json_encode($wines) . '}';

} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
    debug_print_backtrace();
}

}

Regards
Anupam

Infact if i use new get

$app->get(’/books/{one}/{two}’, function ($one, $two) {
echo "The first parameter is " . $one;
echo "The second parameter is " . $two;
});

it is also giving same error
Catchable fatal error: Object of class Slim\Http\Request could not be converted to string in /var/www/html/slim/public/api/index.php on line 37

The callback function in Slim 3 has the following signature:

function (Slim\Http\Request $request, Slim\Http\Response $response, array $args)

The placeholder values are stored in the $args argument. For example:

$app->get('/hello/{name}', function ($request, $response, $args) {
    echo "Hello, " . $args['name'];
});

We don’t support the string method of route middleware anymore ;(

If you want route middleware you use $route->add();

Example:

$app->get()->add(function ($req, $res, $next) {
     return $next($req, $res);
});

Thanks for your suggestion.

Now I am getting sql error, kindly guide me how to pass variable in getWine Function & in sql query ( what changes is required in function getWine & in $sql where id=$var1.

Will appreciate if you share me some doc for creating insert and other api, all reference available at internet are refer old version syntax.

Regards
Anupam

$app->get(’/books/{var1}/{var2}’,‘getWine’, function ($request, $response, $args) {
echo "Hello, " . $args[‘var1’] . ’ ‘. “and” .’&nbsp’. $args[‘var2’];
});

function getWine ($var1) {

$sql = "SELECT * FROM wine WHERE id=$var1";

try {
    $db = getConnection();
   $stmt = $db->query($sql);
    $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
    $db = null;
    echo '{"wine": ' . json_encode($wines) . '}';

} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
    debug_print_backtrace();
}

}
function getConnection() {
$dbhost=“localhost”;
$dbuser=“root”;
$dbpass="";
$dbname=“api”;
$dbh = new PDO(“mysql:host=$dbhost;dbname=$dbname”, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}

Hello Anupam,

You can find the documentation for Slim 3 at http://www.slimframework.com/docs/

The documentation contains a tutorial which includes database access: http://www.slimframework.com/docs/tutorial/first-app.html
The source code for the tutorial can be found at: https://github.com/slimphp/Tutorial-First-Application/tree/master/src

Thanks now able to call database call also. for get,post,delete,update ( slim 3 )


require ‘vendor/autoload.php’;
require_once ‘connection.php’;
/**

  • Step 2: Instantiate a Slim application
  • This example instantiates a Slim application using
  • its default settings. However, you will usually configure
  • your Slim application now by passing an associative array
  • of setting names and values into the application constructor.
    */
    $app = new Slim\App();

$app->group(’/login’, function () {

$this->get(’/wines/{name}/{anu}’,‘getWine’, function ($request, $response, $args) {});
$this->post(’/wines’,‘getWines’, function ($request,$response,$args){} );
$this->post(’/wines/search’,‘search’,function ($request,$response,$args){});
$this->post(’/wines_add’,‘addWine’,function ($request,$response,$args){});
$this->put(’/wines/{id}’, ‘updateWine’,function ($request,$response,$args){});
$this->delete(’/wines/{id}’, ‘deleteWine’,function ($request,$response,$args){});
$this->post(’/createstudent’,‘createstudent’, function ($request,$response,$args){} );

} );

// Run app
$app->run();

function getWine($request, $response, $args) {

$id=$args[‘name’];
// check for required params
//verifyRequiredParams(array(‘name’));

$sql = "SELECT *  FROM wine WHERE id=$id";

try {
   $db = getConnection();
   $stmt = $db->prepare($sql);
   $stmt->bindParam("id", $id);
   $stmt->execute();
   $wines = $stmt->fetchAll(PDO::FETCH_OBJ);

if($wines) {
#$wines1->response->setStatus(200);
#$wines1->response()->headers->set(‘Content-Type’, ‘application/json’);
echo json_encode($wines);
echo json_encode(array(“status” => “success”, “code” => 1));
$db = null;
} else {
throw new PDOException(‘No records found.’);
}
$db = null;
##### echo '{“wine”: ’ . json_encode($wines) . ‘}’;

} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
    debug_print_backtrace();
}

}

function getWines($request, $response, $args) {

$sql = "select * FROM wine ";
try {
    $db = getConnection();
$stmt = $db->prepare($sql);
$stmt->execute();
    $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
    $db = null;
    echo '{"wine": ' . json_encode($wines) . '}';
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}

}

function addWine($request, $response, $args) {
$value = json_decode($request->getBody());

$sql = "INSERT INTO wine (name, grapes, country, region, year, description) VALUES (:name, :grapes, :country, :region, :year, :description)";
try {
    $db = getConnection();
    $stmt = $db->prepare($sql);
    $stmt->bindParam("name", $value->name);
    $stmt->bindParam("grapes", $value->grapes);
    $stmt->bindParam("country", $value->country);
    $stmt->bindParam("region", $value->region);
    $stmt->bindParam("year", $value->year);
    $stmt->bindParam("description", $value->description);
    $stmt->execute();
    //$wine->id = $db->lastInsertId();
    //$db = null;
    echo json_encode($value);
    $db = null;
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}

}

function search($request, $response, $args) {
$value = json_decode($request->getBody());

$sql= "select * from wine where country=:name";
try {
    $db = getConnection();
    $stmt = $db->prepare($sql);
    $stmt->bindParam("name", $value->country);
    $stmt->execute();
    $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
    echo '{"wine": ' . json_encode($wines) . '}';
    $db = null;
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}

}

function updateWine($request, $response, $args) {
$id=$args[‘id’];
//echo “$id”;
// $body = $request->getBody();
// $wine = json_decode($body);
$value = json_decode($request->getBody());
#$data = $value->country;

  $sql = "UPDATE wine set  name=:data  WHERE id=$id";

// $sql = “select * from wine where name=:data”;
// $sql = “select * from wine where name=‘piper’”;
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(“data”, $value->country);
// $stmt->bindParam(“id”, $wine->id);
$stmt->execute();
// $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
echo '{“wine”: ’ . json_encode($value) . ‘}’;

    //$db = null;
    echo json_encode($value);
      $db = null;
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}

}

function deleteWine($request, $response, $args) {
$id=$args[‘id’];

$sql = "DELETE FROM wine WHERE id=$id";
try {
    $db = getConnection();
    $stmt = $db->prepare($sql);
    $stmt->bindParam("id", $id);
    $stmt->execute();
    $app->response->setStatus(200);
$app->response()->headers->set('Content-Type', 'application/json');
    echo json_encode(array("status" => "success", "code" => 1));
    $db = null;
} catch(PDOException $e) {

$app->response()->setStatus(404);
echo ‘{“error”:{“text”:’. $e->getMessage() .’}}’;
}
}

function validation($parameters)

#{

if ($_SERVER[‘REQUEST_METHOD’] == ‘PUT’) {

    //$app = \Slim\Slim::getInstance();

parse_str($app->request()->getBody(), $request_params);

}

#else if

#}

//function getConnection() {
// $dbhost=“localhost”;
// $dbuser=“root”;
// $dbpass="";
// $dbname=“api”;
// $dbh = new PDO(“mysql:host=$dbhost;dbname=$dbname”, $dbuser, $dbpass);
// $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// return $dbh;
//}
?>

----------------------------------------------connection.php-------------------------

<?php function getConnection() { $dbhost="localhost"; $dbuser="root"; $dbpass=""; $dbname="api"; $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); define('USER_CREATED_SUCCESSFULLY', 0); define('USER_CREATE_FAILED', 1); define('USER_ALREADY_EXISTED', 2); return $dbh; } ?>

Regards
Anupam