I'm trying to call a function I created in MySQL using the Slim framework.
This is my function in DBHandler.php:
public function validarSincronismo($pCnpj, $pLogin, $pImei){
$stmt = $this->conn->prepare("SELECT sincronizar(?,?,?)");
$stmt->bind_param("sss", $pCnpj, $pLogin, $pImei);
$result = $stmt->execute();
$stmt->close();
return $result;
}
And this is the function in my index.php:
$app->post('/validar', function() use ($app) {
$db = new DbHandler();
$cnpj = $app->request->post('cnpj');
$login = $app->request->post('login');
$imei = $app->request->post('imei');
$msg = $db->validarSincronismo($cnpj, $login, $imei);
$response["error"] = false;
$response["message"] = $msg;
echoRespnse(201, $response);
});
And I'm getting the following error in phperror.log:
[17-Sep-2015 21:12:37 UTC] PHP Fatal error: Call to a member function execute() on boolean in C:\MAMP\htdocs\test\include\DbHandler.php on line 69
I tried using CALL sincronizar(?,?,?); But it doesn't execute the SQL function.
Thanks #GustavoStraube and #NorbertvanNobelen for taking the time and looking into my question! I was able to call my SQL function using SELECT sincronizar(). The problem was that I had created the function in the wrong database. My bad! :/
So my final and working code looks as follows:
Function in DBHandler.php
public function validarSincronismo($pCnpj, $pLogin, $pImei){
$stmt = $this->conn->prepare("SELECT sincronizar(?,?,?)");
$stmt->bind_param("sss", $pCnpj, $pLogin, $pImei);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
// Returns a message
return $result;
}
Function in index.php
$app->post('/validar', function() use ($app) {
$db = new DbHandler();
$cnpj = $app->request->post('cnpj');
$login = $app->request->post('login');
$imei = $app->request->post('imei');
$msg = $db->validarSincronismo($cnpj, $login, $imei);
$response["error"] = false;
$response["message"] = $msg;
echoResponse(201, $response);
});
Related
I'm very new to PHP and Slim Framework which helps creating APIs.
Everything is ok If i query db inside $app->post or get. But I want to separate it to normal function. It will help when I need to use it later in other APIs.
I tried to call this
$app->get('/search/[{phone}]', function($request, $response, $args) use ($app){
$token = $response->getHeader('token');
// $phone = $args['phone'];
if (isTokenValid($token)){
return $this->response->withJson("valid");
}
return $this->response->withJson("invalid");
});
My isTokenValid() function
function isTokenValid($token){
$sql = 'SELECT id FROM users WHERE token = :token';
$s = $app->db->prepare($sql); //<< this line 25
$s->bindParam(':token', $token);
if ($s->execute()){
if($sth->rowCount() > 0){
return true;
}
}
return false;
}
But I get 500 Internal Server Error
Type: Error
Message: Call to a member function prepare() on null
File: /Applications/MAMP/htdocs/aigoido/src/functions.php
Line: 25
How to call it outside $app? Thanks.
You want to create a dependency injection container for your database connection and pass that object in as the function parameter rather than app object. This makes the db connection reusable throughout your app.
https://www.slimframework.com/docs/concepts/di.html
Also, you can return $response rather than $this->response.
$c = $app->getContainer();
$c['db'] = function() {
return new DB($host,$user,$pass,$name);
};
$app->post('/search/[{phone}]', function($request, $response, $args) use ($c) {
$token = $response->getHeader('token');
// $phone = $args['phone'];
if (isTokenValid($c->db,$token)){
return $response->withJson("valid");
}
return $response->withJson("invalid");
});
function isTokenValid($db, $token){
$sql = 'SELECT id FROM users WHERE token = :token';
$s = $db->prepare($sql);
$s->bindParam(':token', $token);
if ($s->execute()){
if($sth->rowCount() > 0){
return true;
}
}
return false;
}
Pass $app to your function as parameter. The function has it own context so $app is not available without that.
function isTokenValid($token, $app){
$sql = 'SELECT id FROM users WHERE token = :token';
$s = $app->db->prepare($sql); //<< this line 25
$s->bindParam(':token', $token);
if ($s->execute()){
if($sth->rowCount() > 0){
return true;
}
}
return false;
}
An example of one of my queries...
public function db_query_select($query, $params, $param_types){
$dbc = $this->dbConnect();
if($stmt = $dbc->prepare($query)){
//prepared.
//move the types to the front of the param array
array_unshift($params, $param_types);
//call the bind param function with the parameters passed in by reference
//bind_param only allows by reference.
call_user_func_array(array($stmt, "bind_param"), $this->paramsToRefs($params));
//binded.
//attempt to execute the sql statement.
if ($stmt->execute()){
$result = $stmt->get_result();
$stmt->close();
$dbc->close();
return $result;
}
}
//must have failed...
return NULL;
}
how can I change stmt get_result(); to something that is accepted by shared servers/hosts without the native driver... mysqlnd.
Anyone know? without changing all of my functions that use this database function.
Thanks.
UPDATED:::: Thanks to #your common sense, See Answer.
I believe this is what I was after. Hope it helps anyone that was having the same problem as myself. PDO vs MySQLi, seems simpler... no user call func or anything like that.
DB HANDLER:
private function dbConnect(){
$config = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/NTConfig.ini');
try {
$dbc = new PDO('mysql:host='.$config['DB_HOST'].';dbname='.$config['DB_DATABASE'].'', $config['DB_USER'], $config['DB_PASSWORD']);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
return $dbc;
}
public function db_query_select($query, $params){
$dbc = $this->dbConnect();
if($stmt = $dbc->prepare($query)){
//prepared.
//attempt to execute the sql statement.
if ($stmt->execute($params)){
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
//$stmt->close();
//$dbc->close();
return $result;
}
}
//must have failed...
return NULL;
}
Outside the DBHANDLER
$query = "SELECT error_desc FROM nt_errors WHERE error_code = :ERROR_CODE LIMIT 1";
//array: holds parameters for the query.
$params = array(
':ERROR_CODE' => $code
);
$result = $db->db_query_select($query, $params);
if ($result == NULL){
$errorText = 'ERROR: Failed to retrieve error';
}
else{
//var_dump($result);
$errorText = $result['error_desc'];
PDO is not only much more user friendly than mysqli but also doesn't have any of such a nasty drawbacks. So I strongly suggest to use PDO instead of mysqli.
With DO, the function you're after should be as simple as this
function run($sql, $args = NULL)
{
$pdo = ...;//your means of getting the connection variable
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
After gettin the function's result, you can chain a fetch method to its call, fetchColumn() in your case.
Given your code is mostly procedural, let me suggest you a very simple PDO wrapper I wrote. So the full code would be:
$sql = "SELECT error_desc FROM nt_errors WHERE error_code = ?";
$errorText = DB::run($sql,[$code])->fetchColumn();
if (!$errorText){
$errorText = 'ERROR: Failed to retrieve error';
}
Here DB class is a better replacement of your dbConnect() function, and run() method is a replacement for db_query_select() that actually can be used for any query type, including insert, update or anything.
I have a another php file that has the function to connect to the database (does so successfully) and also a function getEvent that contains the sql statement.
The code below successfully retrieves one data row from the database but i need it to return all data from the table.
<?php
// include db connect class
require_once 'include/DB_Functions.php';
// connecting to db
$db = new DB_Functions();
// array for JSON response
$response = array();
// get all events from events table
$event = $db->getEvent();
// check for empty result
if($event !=FALSE){
$response["error"]=FALSE;
$response["uuid"] = $event["eventID"];
$response["eventdetails"]["title"] = $event["title"];
echo json_encode($response);
}else{
$response["error"]=TRUE;
$response["error_msg"] = "No events to display";
echo json_encode($response);
}
?>
the getEvent method
public function getEvent(){
$stmt= $this->conn->prepare("SELECT * from eventdetails");
$stmt->execute();
$event= $stmt->store_result();
if ($stmt->execute()) {
$event = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $event;
} else {
// events dont existed
$stmt->close();
return null;
}
If youwant to return an array containing all the results from a query then use the fetchAll() method of the PDOStatement Class
public function getEvent(){
$stmt = $this->conn->prepare("SELECT * from eventdetails");
$stmt->execute();
$events = $stmt->fetchAll();
return $events;
}
I am trying to create a login/register feature on my android app. One of my files contains a two functions that are being used by register and login. I keep getting an error, the same error when I try to do both. I am getting this error from my error_log file and I have tried google for a while now and can't seem to find a solution to my particular issue. The error I get is:
Call to a member function fetch_assoc() on a non-object in DB_Functions.php
and the parts I get the error are here:
Login:
public function getUserByEmailAndPassword($email, $password) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc(); <----THIS LINE
$stmt->close();
return $user;
} else {
return NULL;
}
}
Register:
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc(); <----AND THIS LINE
$stmt->close();
return $user;
} else {
return false;
}
I'm trying to create a function where I can simply do <?php echo $user_args['user_id']; ?> to call a variable. If a user is logged in I can use this format. I can't get this function working in PDO though.
I'm getting this error message:
Notice: Undefined variable: db in /Applications/XAMPP/xamppfiles/htdocs/app/user/func/user.func.php on line 35
Fatal error: Call to a member function prepare() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/app/user/func/user.func.php on line 35
This is the function I'm trying to do:
$db = new PDO("mysql:host=$servername; dbname=$database", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function user_args() {
$user_id = $_SESSION['user_id'];
$args = func_get_args();
$fields = implode(', ', $args);
$query = $db->prepare("SELECT * FROM users WHERE user_id = :user_id");
$query->bindParam(':user_id', $user_id);
if($query->execute()) {
$query_success = $query->fetch(PDO::FETCH_ASSOC);
foreach($args as $arg) {
$args[$arg] = stripslashes($query_success[$arg]);
}
return $args;
}
}
$user_args = user_args('user_id',
'username',
'email',
'password');
echo $user_args['user_id']; // <- The function isn't working so I can't do this
What's wrong in my code that's making this not work? Thanks!
$db is missing inside the function
function user_args($db) {
// ...
}
also add $db in the function call:
$user_args = user_args($db, 'user_id',
'username',
'email',
'password');