PHP Slim post route to MySql not working - php

After following this tutorial: I now have a Slim environment. I can get my data from MySql, but I just can't post. I have tried something like this:
...
$app->post('/someRoute', function (Request $request, Response $response){
$sql = "INSERT INTO someTable(firstName, lastName)
VALUES(:FN, :LN)";
$db = $this->get(Connection::class);
$stmt = $db->prepare($sql);
//$rows = $db->table('someTable')->get();
$stmt->bindParam(':FN', $request->getParam('FN'));
$stmt->bindParam(':LN', $request->getParam('LN'));
$stmt->execute();
});
This does not work, but I can't see where the error might be because I don't know how to debug a POST function with HTML/PHP. My app send's the parameters to the function just fine. I don't have a lot of experience with server-side programming, so any help would be appreciated. Thanks.

If you are using the PDO class, you can "TryCatch" it:
try
{
// Your code
}
catch (PDOException $e)
{
// Error Message
print_r($e->getMessage());
}

I needed to use a query builder instead of my own SQL statements. Sorted

Related

API doesn't allow text

I've just created a simple API for a CAD/MDT I'm working on, I've managed to get it to show the correct information when I do /citations/userid/1. This will then display all the correct values from the SQL database however, if I do /citations/issued_by/kevingorman1000 it will just throw an error. I can't tell what the error is as I'm using Slim php and can't seem to get the errors to display.
Any ideas why it isn't working ? I've added my code below..
$app->get('/citation/issuedby/{issued_by}', function(Request $request, Response $response){
$issued_by = $request->getAttribute('issued_by');
$sql = "SELECT * FROM ncic_citations WHERE issuedby = $issuedby";
try{
// Get DB Object
$db = new db();
// Call Connection to DB
$db = $db->connect();
$stmt = $db->query($sql);
$issby = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($issby);
} catch(PDOExecption $e) {
echo '{"error"} : {"text": '.$e->getMessage().'}';
}});
Any ideas why this is the case? Does it only allow getting via number or do I need too do something else? First time using this and kinda new to PHP as well.
Thanks for any help.
Your problem is called SQL injection. You can solve it by using prepared statements. Never escape the values with quotes or anything else, as others might have suggested.
$sql = "SELECT * FROM ncic_citations WHERE issuedby = ? ";
$stmt = $db->prepare($sql);
$stmt->execute([$issuedby]);
$issby = $stmt->fetchAll(PDO::FETCH_OBJ);
For a good tutorial on PDO and prepared statements I recommend: https://phpdelusions.net/pdo
It's because SQL error (missing quotes around string).
You try to send query
$sql = "SELECT * FROM ncic_citations WHERE issuedby = kevingorman1000";
Correct query has to be
$sql = "SELECT * FROM ncic_citations WHERE issuedby = 'kevingorman1000'";

A stored procedure that doesn't work in my PHP code but it works with a SQL Client

I'm working on a business monitor (a pannel that presents some metrics).
To get that data I do a sql request. By the way, I used a stored procedure.
My code is :
public function execErrorWarnLogs($id){
try {
$sql = "exec [BUSINESS_MONITOR_LOGS] #id='".$id."'";
$req = $this->_bdd->prepare($sql);
$req->execute();
$res = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
return $res;
} catch (Exception $e) {
echo $e->getMessage();
}
}
When I'm trying to get some data indexed by $id, I get some troubles. I got an array that has null values... However, if I execute that stored procedure with an SQL client I get results.
Is that already happened to someone here ? Can someone explain me why I get that ?
If you want more information, please let me know.
Thanks.
Is $id an integer or a string?
Try using bound parameter instead. This is a example how it is working perfectly in my code:
public function execErrorWarnLogs($id){
try {
$sql = "exec BUSINESS_MONITOR_LOGS #id=:id";
$req = $this->_bdd->prepare($sql);
$req->execute([
'id' => $id
]);
$res = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
return $res;
} catch (Exception $e) {
echo $e->getMessage();
}
}
You should use parameters for security reasons, too!
Two site notes:
If you do string interpolation you don't need to prepare the statement. Then you could just do:
$req = $this->_bdd->query($sql);
$res = $req->fetchAll(PDO::FETCH_ASSOC);
But the recommendet approach (for security) is to provide values as bound parameters and prepare the query.
As far as I know, you don't need $req->closeCursor() if you use Microsofts latest pdo driver for MSSQL. Whether you need closeCursor depends on the driver you use.
My stored procedure :
CREATE PROCEDURE BUSINESS_MONITOR #id VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT e.METRIC_NAME, e.METRIC_VALUE
FROM MONITOR_EVENTS e
WHERE e.MAIN_ID = #id
END
There are two more possible reasons:
Encoding issue
I would assume, that you have an encoding issue. If $id contains chars, that are out of the ascii-range, and you have another encoding, this could cause the query to fail. So check the encoding of $id and of you db connection
Whitespaces in $id
Maybe you have whitespaces in you id.

Error getting data using PDO and PHP

I'm developing a web based software that uses MySQL and PHP on the backend.
I'm trying to obtain data with a complex query and in the end I just obtain the query.
function consulttimes(){
$pdo = connect();
try{
$consult = $pdo->prepare("SELECT credentials.realname, timestamp_greenhouse.* FROM times.credentials, times.timestamp_greenhouse WHERE timestamp_greenhouse.id = credentials.id;");
$consult->execute();
$consult->fetch(PDO::FETCH_ASSOC);
echo json_encode($consult);
//file_put_contents('times.json', $json);
}
catch(PDOException $e) {
echo $e -> getMessage();
}
}
I have all the databases and the query works perfectly on phpmyadmin.
Can someone help me with this?
Cheers!
I'm trying to obtain data with a complex query and in the end I just obtain the query.
The problem is because of this line,
echo json_encode($consult);
$consult is a PDOStatement object returned from the prepared statement. I believe you're trying to encode the row obtained from ->fetch(PDO::FETCH_ASSOC) method.
So first fetch the row from the result set, store it in a variable and then apply json_encode on it, like this:
// your code
$consult->execute();
$result = $consult->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);

JSON response not as expected using php

I know this is probably a really simple question, but I can't find an answer for this issue, maybe because it is a really basic php programming question. This is my function using PDO (php):
<?php
function getAllUsers(){
try {
$conn = getConnection(); //connects to database, no explanation needed... uses PDO
$dbh = $conn->prepare("SELECT * FROM User;");
$dbh->execute();
$users = $dbh->fetchAll(); //<---this is maybe the error
$conn = null;
return $users;
}catch (PDOException $ex){
echo "Error: ".$ex->getMessage();
}
} ?>
And when i consume the API that i'm implementing, i use this other PHP script (using slim framework, still pretty understandable)
<?php
$app->get("/user",function() use($app){
$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$result = getAllUsers(); //call to my function getAllUsers
$app->response->body(json_encode($result));
});
?>
It works fine, but the results that I get are these:
[{"idUser":"1","0":"1","userName":"asdasd","1":"asdasd","userPass":"password","2":"password"},{"idUser":"2","0":"2","userName":"2312","1":"2312","userPass":"password","2":"password"}]
And I think that the repeated values "0":"1" , "1":"asdasd" , "2":"password"should not be there, but i can't figure out how to get only the data that i want and not the repeated values. Any help would be very appreciated
I'm not using PDO, but "common" mysql queries and there is the same...you get doubled your values. One array is associative and other indexed (0,1,2). And there is option to pass ("MYSQL_ASSOC" if I recall well) to get only associative array, without indexed one. There must be some similar option with PDO.
$dbh->fetchAll(PDO::FETCH_ASSOC);
http://php.net/manual/en/pdostatement.fetchall.php

how to see the query processed with php PDO? !

I'm preparing my sql statements and binding parameters to it and if something goes wrong i catch them in a catch block. But, i want to see which query i processed. So i extended the PDO class (found it on the internet , not exactly sure what i'm doing or where the ATTR_STATEMENT_CLASS is really for. So this is the code of the extention:
class PDOTester extends PDO {
public function __construct($dsn, $username = null, $password = null, $driver_options = array()) {
parent::__construct($dsn, $username, $password, $driver_options);
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatementTester', array($this)));
}
}
class PDOStatementTester extends PDOStatement {
protected $connection;
protected function __construct(PDO $connection)
{
$this->connection = $connection;
}
public function execute() {
try {
parent::execute();
} catch (PDOException $e) {
$e->errorInfo[3] = $this->queryString;
echo '<pre>';
var_dump($this);
var_dump($this->connection);
echo '</pre>';
throw $e;
}
}
}
But, here comes the problem, i used named parameters to bind values to it, but when i see the SQl query then i see the named parameters and not the values!
For example, i use it like:
try {
$sql = "INSERT INTO table (column1, column2) VALUES (:column1, :column2)";
$stmt = $db->preapre($sql);
$stmt->bindParam(':column1', $column1, PDO::PARAM_STR);
$stmt->bindParam(':column2', $column2, PDO::PARAM_INT);
$stmt->execute();
} catch (PDOException $e) {
echo $e->errorInfo[3];
}
But then i see as values :column1, :column2, instead of the actual variables!
Can please someone help me out (for example provide a better modification of the extension i use)?
PHP Version 5.2.17, MySQL version 5.0.92
As far as I know, there is no way to see the actual query when using prepared statements
Your best option would be to turn MySQL's general log option.
Run the following in MySQL terminal (or any other preferred program / app you use to control MySQL)
SET GLOBAL general_log = ON;
SET GLOBAL general_log_file = 'path_to_file.log';
Run your query, inspect the file.
They really didn't need to extend the PDO class to do what they did. Simply create a new instance then add (or remove) that attribute after creation rather than during.
That being said, there's a built-in way of outputting the debug information regarding a statement, and that's using PDOStatement->debugDumpParams. This won't let you see the compiled version (that's done database-side for databases that support it) but it will let you see both the query and that bound parameters easily.
A note of caution, don't enable this on a live system. It could give attackers of your website a big clue into how your system is set up and what they can do it take over (and destroy or otherwise ruin).

Categories