Undefined property: stdClass::$id error - php

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.

Related

PHP Method in Class not returning data from database

Ok this should be fairly simple.
I have a table which contains content of 3 different textboxes the method inside my class should get the content to insert into textboxes.
Example TextBoxes (TextArea) where content should be entered.
My Method
public function LoadBoxes(){
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$data[] = array('Low' => $box['boxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $data;
}//function
Here is my table (image below) so data / content from table should get inserted into the textboxes.
So when I do a test on content.php where I call the class method as such:
require_once('../classes/class.content.php');
$boxes = new Contents();
$boxes->LoadBoxes();
var_dump($boxes);
I get the following back:
Problem
As can be seen the array keys get returned however the data from database is not matched to array keys or returned by the method...I am stumped and have no idea what I am doing wrong here?
Any suggestions where I am going wrong? Could it be that I am not connecting to database correctly?
However if it was a database connection error I believe I would have received an error
Please keep in mind im a student and still learning.
UPDATE
Connection Schema
class Db {
private static $instance = NULL;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if (!isset(self::$instance)) {
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
self::$instance = new PDO('mysql:host=localhost;dbname=beta', 'root', '', $pdo_options);
}
return self::$instance;
}
}
UPDATE 2
I just did the following on a test.php page which returned correct results.
require('connection.php');
function LoadBoxes(){
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$box[] = array('Low' => $box['BoxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $box;
}//function
print_r(LoadBoxes());
?>
2 issues primary issues;
You're returning $data from the class but not populating a variable with the returned array.
You are var dumping the object itself.
This should work;
require_once('../classes/class.content.php');
$boxes = new Contents();
$data = $boxes->LoadBoxes();
var_dump($data);

PDOstatement::execute() expect parameter 1 to be array, string given in

Please help me to correct this code.
error at line
$stmt->execute($params = [], $query);
and when i open the file with dreamweaver every "$params=[]" is error.
-Databasse.php-
<?php
include_once('connection.php'); //my connection is here
class Database extends connection{
public function __construct(){
parent::__construct();
}
public function getRow($params = [], $query){
try {
$stmt = $this->datab->prepare($query);
$stmt->execute($params);
return $stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
public function getRows($query, $params = []){
try {
$stmt = $this->datab->prepare($query);
$stmt->execute($params);
return $stmt->fetchAll();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
this is half of the source code database.php
Need to see more of the code - what is your query string, what array w/ what values are you trying to feed into it?
Typically your query will have question marks ? or might have keywords with colons :mykeyword as place holders for values, and then your array holds the values that are "prepared" and executed.
$query="select name from users where name=? and passwordHash=?";
$res=$connection->prepare($query);
$res->execute(array(
"myuser",
"dd02c7c2232759874e1c205587017bed"),
);
// OR
$query="select name from users where name=:name and passwordHash=:passwordHash";
$res=$connection->prepare($query);
$res->execute(array(
":name" => "myuser",
":passwordHash" => "dd02c7c2232759874e1c205587017bed"),
);
This does the query preparation, escaping, etc. and the "myuser" value replaces the first question mark and the hash string replaces the second.

MySQL's session handler difficulties

Watching this online tutorial about MYSQL's session handler and got really confused about this part:
table_XXX == Table XXX;
col_XXX == Column XXX;
sid == Session id
Read method:
public function read($session_id)
{
$this->db->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
$this->db->beginTransaction();
/**
* the data is selected and no other ppl can interfere
* the writing process until COMMIT is reached
*/
$sql = "SELECT $this->col_expiry, $this->col_data
FROM $this->table_sess
WHERE $this->col_sid = :sid FOR UPDATE";
$selectStmt = $this->db->prepare($sql);
$selectStmt->bindParam(':sid', $session_id);
$selectStmt->execute();
$results = $selectStmt->fetch(\PDO::FETCH_ASSOC);
if ($results) {
if ($results[$this->col_expiry] < time()) {
// return empty if data out of date
return '';
}
return $results[$this->col_data];
}
return $this->initializeRecord($selectStmt);
}
Protected method:
protected function initializeRecord(\PDOStatement $selectStmt)
{
try {
$sql = "INSERT INTO $this->table_sess
($this->col_sid, $this->col_expiry, $this->col_data)
VALUES (:sid, :expiry, :data)";
$insertStmt = $this->db->prepare($sql);
$insertStmt->bindParam(':sid', $session_id);
$insertStmt->bindParam(':expiry', $this->expiry); // expiry is defined
$insertStmt->bindValue(':data', '');
$insertStmt->execute();
return '';
} catch(\PDOException $e) {
$this->db->rollBack();
throw $e;
}
}
Write method:
public function write($session_id, $data)
{
try {
$sql = "INSERT INTO $this->table_sess ($this->col_sid,
$this->col_expiry, $this->col_data)
VALUES (:sid, :expiry, :data)
ON DUPLICATE KEY UPDATE
$this->col_expiry = :expiry,
$this->col_data = :data";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':expiry', $this->expiry, \PDO::PARAM_INT);
$stmt->bindParam(':data', $data);
$stmt->bindParam(':sid', $session_id);
$stmt->execute();
return true;
} catch (\PDOException $e) {
if ($this->db->inTransaction()) {
$this->db->rollback();
}
throw $e;
}
}
In 'Protected method', line 8, there is a $session_id, and clearly no $session_id is passed to the protected method, so bindParam() for that line simply binded nothing?
So initializeRecord() simply initiated a row that has expiry time but nothing else? And then the sid and data is inserted after write method is called?
This is doing a lot of string-construction trickery with WHERE $this->col_sid = :sid and so forth, as it creates SQL statements.
You might try echoing or dumping those SQL statements to see what they contain right before you run ->execute() on them. That will help you troubleshoot.
It's pretty clear your protected method is missing $session_id. Is it possible there's a value for $this->sid you could use there?

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

MySQLi get last insert ID and pass it true function

In my I am trying to retrieve the last_insert (ID) from a query true calling a function here is where i call my function:
$lead = $_leadh->addLead($lead_data, $call_data['number'], $user);
$LeadID = $lead['id'];
I am not getting any result? This is my addLead function:
function addLead(array $lead_data, $number, $user) {
//check if lead with same number and name exist in db
if ($checker = >= 1)
{
//return lead id as existed
$data = $query->fetch_array(MYSQLI_ASSOC);
return array('id'=>$data['lead_id'], 'exists'=>true);
}
else
{
//insert new lead into db
if ($query = $this->QueryDB("INSERT", "INTO leads (lead_name)
VALUES ('".$this->EscapeString($lead_data['lead_name'])))
{
//return lead id as new
return array('id'=>$this->insert_id, 'exists'=>false);
}
else
{
//output error if insertion fail
return false;
}
}}
You are returning array from addLead function but while calling you are not getting in any variable:
$_leadh->addLead($lead_data, $call_data['number'], $user);
$LeadID = $lead['id'];
should be like below:
$lead = $_leadh->addLead($lead_data, $call_data['number'], $user);
$LeadID = $lead['id'];

Categories