Error getting data using PDO and PHP - 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);

Related

Calling mssql stored procedure using pdo sqlsrv drivers with multi queries inside procedure

I'm facing the problem while calling stored procedure by using sqlsrv drivers in laravel. Inside procedure there are multiple queries with combination of select and insert. I unable to share code here as its privacy issue.
So can any one please share the code which can work with laravel to call mssql procedure with multiple result row set.
Thanks in advance!!
MS SQL Server supports stored procedures that can return more than one result set. With PHP and PDO you can retrieve these result sets with PDOStatement::nextRowset() method. It is important to note, that if you have output parameters in your stored procedure, you need to fetch all result sets to get the output values.
If Laravel do not support nextRowset(), you may try to get the underlying PDO instance using the getPdo() method on a connection instance and use this instance for statement execution:
<?php
...
$pdo = DB::connection()->getPdo();
try {
$sql = "{CALL usp_TestProcedure(?)}";
$param = 'ParamValue';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(1, $param);
$stmt->execute();
do {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row, true);
echo '<br>';
}
} while ($stmt->nextRowset());
} catch( PDOException $e ) {
die( "Error executing query" );
}
...
?>

How to iterate over multiple result sets of a custom query?

I have a stored procedure in my mysql database which returns multiple query result sets.
I want to access these results in my cakephp(V3.4) project using following code statements.
$db = ConnectionManager::get('default');
$stmt = $db->execute("call mydatasp($paramlist)");
$result = array();
try{
do
{
$rowset = $stmt->fetchAll('assoc');
$result[]=$rowset;
} while($stmt->nextRowset());
}
catch(Exception $e){}
After execution of this code block, I m getting error as
[Cake\Error\FatalErrorException] Call to undefined method Cake\Database\Log\LoggingStatement::nextRowset()
How can I access these multiple query resultsets?

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.

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

prepared parameterized query with PDO

New to this new and secure way of handling SQL's in PHP and MySql driven web based application, to secure the code from SQL injections. I am planning to start using mysqli with PDO. Can anyone please outline how should i get started and proceed.
Any reference to any article will also be helpful.
Thanks in advance.
To create the connection
try {
$db = new PDO("mysql:dbname=".DB_NAME.";host=".DB_HOST,DB_USER,DB_PWD);
} catch (PDOException $e) {
die("Database Connection Failed: " . $e->getMessage());
}
Then to prepare a statement
$prep = $db->prepare("SELECT * FROM `users` WHERE userid = ':id'");
As you can see, you label each parameter you'd like by prefixing any string with ':'. Then all you do is pass an array mapping the parameter (:id) to the value when you execute.
if (!$prep->execute(array(":id" => $userinput))) {
$error = $prep->errorInfo();
echo "Error: {$error[2]}"; // element 2 has the string text of the error
} else {
while ($row = $prep->fetch(PDO::FETCH_ASSOC)) { // check the documentation for the other options here
// do stuff, $row is an associative array, the keys are the field names
}
}
Instead of PDO::FETCH_ASSOC with the "fetch" function, there are various other ways to get your data. You can use fetchAll to get an array of ALL the results at once instead of just going row by row. Or you can get the array of information as a 0-indexed array, or you can even fetch the results directly into a class instance (if the field names line up with the properties of the class.)
All the documentation of PDO can be found here: PHP.net PDO Manual

Categories