Reputation: 339
I'm currently using the Doctrine DBAL version 2.5 inside of Silex 1.3 to make REST calls to MySQL DB. I manage to get my GET / GET/{id} and DELETE/{id} working fairly easily but I can't seem to get my POST/PUT to work.
Here is the fallowing code
$app->post('/student', function($firstName, $lastName) use($app) {
$sql = "INSERT INTO tbl_students (firstName, lastName)
VALUES (:firstName, :lastName)";
$student = $app['db']->prepare($sql);
$student->bindValue(':firstName', $firstName, PDO::PARAM_STR);
$student->bindValue(':lastName', $lastName, PDO::PARAM_STR);
$student->execute();
return "insert successful";
});
$app->put('/student/{id}', function($id, $firstName, $lastName) use($app){
$sql = "UPDATE tbl_students
SET firstName = :firstName, lastName = :lastName
WHERE id = :id";
$student = $app['db']->prepare($sql);
$student->bindValue(':id', $id, PDO::PARAM_INT);
$student->bindValue(':firstName', $firstName, PDO::PARAM_STR);
$student->bindValue(':lastName', $lastName, PDO::PARAM_STR);
$student->execute();
return "student succesfully updated";
});
If I hard code default values, it works perfectly fine as well as using bindParam() and using my own values.
I keep getting this error message after my curl dumps everything back at me
<span class="exception_message">Controller "Closure" requires that you provide a value for the "$firstName" argument (because there is no default value or because there is a non optional argument after this one).</span>
Here are the fallowing curl commands I have used
curl -X POST -d "firstName=First123&lastName=Last456" URL/student
curl -X POST -d '{"firstName":"First123","lastName":"Last456"}' URL/student --header "Content-Type:application/json"
curl -X POST -d "firstName=First123&lastName=Last456" URL/student --header "Content-Type:text/html"
Upvotes: 0
Views: 264
Reputation: 4265
Silex will not automatically create parameters for your methods corresponding to your post variables. You have to get them from the request object as @Artamiel suggested.
See http://silex.sensiolabs.org/doc/usage.html#example-post-route.
The updated code for your post operation should be like this:
$app->post('/student', function(Request $request) use($app) {
$firstName = $request->get('firstName');
$lastName = $request->get('lastName');
$sql = "INSERT INTO tbl_students (firstName, lastName)
VALUES (:firstName, :lastName)";
$student = $app['db']->prepare($sql);
$student->bindValue(':firstName', $firstName, PDO::PARAM_STR);
$student->bindValue(':lastName', $lastName, PDO::PARAM_STR);
$student->execute();
return "insert successful";
});
Upvotes: 1