PDO query using func_get_args(); is giving error message - php

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');

Related

Not able to get return output from PHP class

This is my code in my class
<?php
class PerClass
{
private $sql_connection = null;
private $localAf = '9929292F';
function __construct($env) {
// Nasty globals, sorry
global $_config;
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "kModule";
// Build sql connection
$this->sql_connection = new mysqli($host, $user, $pass, $db);
// Check connection
if ($this->sql_connection->connect_error) {
die("Connection failed: " . $this->sql_connection->connect_error);
}
}
public function getOrders($sSettingsId) {
$query = <<<SQL
SELECT * FROM `scrub_order_log` WHERE `scrub_settings_id` = {$sSettingsId} AND `order_date` BETWEEN (NOW() - INTERVAL (SELECT `c_h_days` FROM `scrub_settings` WHERE `id` = {$sSettingsId}) DAY) AND NOW() ORDER BY `order_date` DESC;
SQL;
$result = $this->sql_connection->query($query);
$resp = null;
while ($row = $result->fetch_assoc()) {
$resp[] = $row;
}
return $resp;
}
}
?>
I am trying to get the output as shown in code below
<?
$details = $PerClass->getOrders('1');
print_r($details);
?>
But unfortunately I am getting following erro
Fatal error: Call to a member function getOrders() on null in /home/domn/public_html/stage/stage_test.php on line 37
Tried different ways but I think I am doing something wrong
The code that calls the getOrders method is missing the object instantiation.
<?
// add this here
$PerClass = new PerClass();
$details = $PerClass->getOrders('1');
print_r($details);
?>
now, because the constructor method of your PerClass expects you to pass in a value as an argument, this is going to result in the following warning:
WARNING Missing argument 1 for PerClass::__construct()
In order to resolve this warning you have two options:
Pass the value of the $env parameter when you instantiate the object i.e. $PerClass = new PerClass('value_to_be_passed'); or
Get rid of the $env argument in your constructor since - from what I can see - it is not used anywhere i.e. from function __construct($env) { ... } to function __construct() { ... }.
See this link for an interested discussion about using global in PHP.

Undefined property: stdClass::$id error

I'm trying to add an imagename and imagepath records to a mysql database whenever i upload a new picture, however, I am getting the following errors:
undefined property: stdClass::$id in C:\Service\ChallengeService.php on line 184
undefined property: stdClass::$id in C:\Service\ChallengeService.php on line 188
I replicated a function which also saves images in the same fashion to the similar fields and i pretty much just reused the function so i don't know why its giving me an error.
This is the function that updates my database:
public function updateChallengeImage($challenge) {
try {
$query = "update challenges
set image = :image
,image_file_name = :image_file_name
where
id = :id";
$values = array(
":image" => $challenge->image,
":image_file_name" => $challenge->image_file_name,
":id" => $challenge->id
);
$stmt = $this->db->prepare($query);
$stmt->execute($values);
return $challenge->id;
} catch (PDOException $e) {
$this->logger->error("PDO: ".$e->getMessage(), ["class"=>get_class($this),"method"=>__METHOD__]);
return -1;
}
}
Why isn't the $id variable being passed on? I also have this warning popping up in my logs:
PHP:WARNING Creating default object from empty value in `C:\\classes\napify\Controller\ChallengesController.php on line 106`
However my controller function looks fine, its supposed to load the ID from the database:
public function saveChallengeImage($request, $response, $args) {
$files = $request->getUploadedFiles();
$data = $request->getParsedBody();
$valid = true;
if (!(Utils::isImage($files['image']->file))) {
$this->flash->addMessage('message', 'Las imagenes no deben superar los 700kb ');
$this->flash->addMessage('error', 1);
$valid = false;
}
if ($valid) {
$challenge = $this->ChallengeService->getChallenge(filter_var($data['challenge_id'], FILTER_SANITIZE_STRING));
$challenge->image_file_name = $files['image']->getClientFileName();
$challenge->image = $this->saveFile($files['image']);
$this->ChallengeService->updateChallengeImage($challenge);
$this->flash->addMessage('message', 'Se guardó la imagen.');
}
The getChallenge function that is being called on the controller.
public function getChallenge($id) {
try {
$query = "select
c.id
,c.title
,c.description
,c.active
,c.start_date
,c.end_date
,c.image
,c.image_file_name
,c.color1
,c.color2
,c.color3
,c.color4
from
challenges c
where
id = :id";
$values = array(
":id" => $id
);
$stmt = $this->db->prepare($query);
$stmt->execute($values);
$stmt->setFetchMode(PDO::FETCH_CLASS, 'napify\Model\Challenge');
return $stmt->fetch();
} catch (PDOException $e) {
$this->logger->error("PDO: ".$e->getMessage(), ["class"=>get_class($this),"method"=>__METHOD__]);
return null;
}
}
I am uncertain as to why its failing to either load the ID from the database or failing to update the database with the imagefile and imagename values. Any help that points me in the right direction or that can tell me where am i making mistakes is appreciated.

Call Mysql function from Slim Framework

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);
});

Can't pass mysqli object to class in PHP

So I'm working on a simple user class in php, which has a class variable which contains the mysqli object, however I keep getting the error:
Fatal error: Call to a member function real_escape_string() on a non-object in */classes/user.php on line X
I've checked everything, it should work, but it doesn't. Somehow. This is my code:
namespace bibliotheek;
class user
{
private $mysql;
private $logged_in = false;
private $user_data = null; //ARRAY: user_id, e-mail, password, bevoegdheid, naam, achternaam, adres, postcode, stad
function __construct(\mysqli $mysql, $salt)
{
$this->mysql = $mysql;
}
public function login($email, $pass, $hash = false)
{
$email = $this->mysql->real_escape_string($email);
if($hash == false)
$pass = sha1($this->salt.$pass);
$query = "SELECT *
FROM gebruikers
WHERE gebruikers.email = '$email' AND gebruikers.password = '$pass'";
$result = $this->mysql->query($query);
$user_data = $result->fetch_assoc();
if($user_data == null)
return;
$this->logged_in = true;
$this->user_data = $user_data;
$this->create_cookies($email, $pass);
}
}
And this is how the mysqli object gets passed to the class:
$mysql = new mysqli($cfg['mysql_server'], $cfg['username'], $cfg['password'], $cfg['database']);
$user = new bibliotheek\user($mysql, $cfg['salt']);
the mysql login data is correct, I've made sure of that.
I must be missing something really obvious here, but I just can't see it. Any help is greatly appreciated. Thanks!
And this is how it should be
error_reporting(E_ALL);
$mysql = new mysqli($cfg['mysql_server'], $cfg['username'], $cfg['password'], $cfg['database']);
if ( !$mysql )
{
throw new Exception(mysqli_connect_error()));
}
$user = new bibliotheek\user($mysql, $cfg['salt']);
I'm really f-ing stupid, I compacted my code a bit when I posted it on here and I left out this part:
$this->mysql = $mysql;
$this->mysql = $salt;
Kill me now.

PDO Problem -> Call to a member function on a non-object

I have been turning and twisting this to the best of my non-existing PDO knowledge, but still without any luck.
the code:
function write($id, $data) {
global $dbcon;
$id = mysql_real_escape_string($id);
$data = mysql_real_escape_string($data);
$sql = $dbcon->exec("INSERT INTO `sessions`
(`session_id`, `session_data`,
`session_expire`, `session_agent`,
`session_ip`, `session_referrer`)
VALUES
(\"".$id."\", \"".$data."\",
\"".time()."\",\"".($this->session_encryption($_SERVER['HTTP_USER_AGENT']))."\",
\"".($this->session_encryption($_SERVER['REMOTE_ADDR']))."\", \"".($this->session_encryption((isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_^~#&|=+;!,(){}[].?%*#'))))."\")
ON DUPLICATE KEY UPDATE
`session_data` = \"".$data."\",
`session_expire` = \"".time()."\"");
return true;
}
Give me the following error:
Fatal error: Call to a member function exec() on a non-object
on the
$sql = $dbcon->exec(
line.
I have been trying to solve this all evening, but without any luck.
This is my PDO connection script:
require_once(INC_PATH.'/config.php');
$dsn = "$db_type:host=$db_host;port=$db_port;dbname=$db_name;charset=$db_charset";
try{
$dbcon = new PDO($dsn, $db_user, $db_pass);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$dbcon = null; //Close database connection.
}
catch(PDOException $e){
echo $e->getMessage();
}
Hope one of you kind souls out there can help me, I would deeply appreciate it!
Thanks.
UPDATE:
I have a global.php file which looks like this:
//Load database
require_once(INC_PATH.'/database.php');
//Load session handler
require_once(INC_PATH.'/class_sessions.php');
$Sessions = new SessionManager();
session_start();
The database.php is included before the sessions class, and when I view the website, it does not give any errors on this part of the sessions class (which is before the write function:
function read($id) {
global $dbcon;
$data = '';
$id = mysql_real_escape_string($id);
$sql = $dbcon->prepare("SELECT
`session_data`
FROM
`sessions`
WHERE
`session_id` = '".$id."'");
$sql->execute();
$a = $sql->columnCount();
if($a > 0) {
$row = $sql->fetchObject();
$data = $row['session_data'];
}
return $data;
}
Are you sure your connection script is getting executed? Try checking if $dbcon is set. Also, you may be missing global $dbcon within the connection script.
By the way, since you're already using PDO, might I recommend you use placeholders in your query:
$sql = "INSERT INTO `sessions`
(`session_id`, `session_data`, `session_expire`,
`session_agent`, `session_ip`, `session_referrer`)
VALUES
(:session_id, :session_data, :session_expire,
:session_agent, :session_ip, :session_referrer)
ON DUPLICATE KEY UPDATE
`session_data` = :session_data,
`session_expire` = :session_expire";
$params = array(
':session_id' => $id,
':session_data' => $data,
':session_expire' => time(),
':session_agent' => $this->session_encryption($_SERVER['HTTP_USER_AGENT']),
':session_ip', => $this->session_encryption($_SERVER['REMOTE_ADDR']),
':session_referrer' => $this->session_encryption((isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_^~#&|=+;!,(){}[].?%*#';
);
$stmt = $dbcon->prepare($sql);
if ($stmt->execute($params) === FALSE) {
// handle error
}
First check that the global object is not being overwritten by another function. I strongly suggest you use Dependency injection instead of globals.
$Sessions = new SessionManager($dbcon);
And inside the Session Management class you can do something like
class SessionManager
{
protected $db;
public function __construct($db) { $this->db = $db; }
public function read($id)
{
$stmt = $this->db->prepare("SELECT session_data
FROM sessions
WHERE session_id = ?");
$stmt->execute(array($id));
return $stmt->fetchColumn();
}
}
And secondly, since you are using PDO, you dont need to call mysql_real_escape_string(), use prepared statements and placeholders :)

Categories