PHP - Uncaught Error: Call to a member function *() on boolean - php

I have a sql request in PHP, the result of this query is put in class variable
But when tis request return no result, I would like have a null value in variable, for the moment I have a false boolean returned.
Could you help me ?
Thank you
<?php
class test
{
const table_name = 'test_table';
protected $Id;
protected $Nom;
public static function byId($id)
{
$values = array
(
':Id' => $id,
);
$sql = 'SELECT *FROM '.self::table_name.' WHERE Id=:Id';
$QueryPrep = self::getInstance()->prepare($sql);
if(empty($param))
{
$resultQuery = $QueryPrep->execute();
}
else
{
$resultQuery = $QueryPrep->execute($values);
}
if ($resultQuery !=false)
{
$res = $resultQuery->fetchObject(__CLASS__);
return $res;
}
else
{
return false;
}
}
public function get_Id()
{
return $this->Id;
}
}
$cmd_device_id = null;
$cmdDeviceObject = new test();
$cmd_device = $cmdDeviceObject->byId(999);
$cmd_device_id = $cmd_device->get_Id();
echo "cmd_device_id = ".var_dump($cmd_device_id);
?>

This return null if the $res has no result.
if ($resultQuery !=false)
{
$res = $resultQuery->fetchObject(__CLASS__);
return $res ?? null;
}

Related

Passing array of Objects in php 7.3

Hi there still new to PHP and struggling with something really basic and it's frustrating me cause I can't see the error. I have read the PHP manual on passing array of objects.
class Customer{
public $companyId;
public $customerId;
public $name;
public function __construct($companyId,$customerId,$name)
{
$this->companyId = $companyId;
$this->customerId = $customerId;
$this->name = $name;
}
}
class CustomersDB
{
...
/**
* #return Customer[]
*/
public function getCustomers($search_str): array {
$resultObj = array();
$result = NULL;
try {
if (! $this->db) {
die('Database handle not defined') ;
}
if ($search_str && ! empty($search_str)) {
$result = $this->ListCustomers(Utils::COMPANY_ID, $search_str, $this->db);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$_tmp = new Customer($row['CompanyID'],
$row['CustomerID'],
$row['CustomerName']);
// $resultObj.push($_tmp);
$resultObj[] = $_tmp;
}
}
} catch (Exception $e) {
// echo Utils::logMsgtoWeb($e->getTraceAsString());
} finally {
$result = NULL;
}
return $resultObj;
}
}
use Respect\Rest\Routable;
class Customers implements Routable {
/**
*
* Can pass in a partial string to search for a customer
* or pass in an ID for a specific match.
*/
public function get($searchStr){
// header('Content-type: application/json');
$result = $this->custdb.getCustomers($searchStr); // ERRORS HERE
if ($result && ! empty($result)) {
return json_encode( $result);
} else {
return NULL;
}
}
}
I get this error: PHP Recoverable fatal error: Object of class Scheduler\db\CustomersDB could not be converted to string in Customers.php.
Any help would be appreciated.

PHP object is not being created

I have received the following error:"Fatal error: Call to a member function session_type() on a non-object".
Supposedly I'm not creating an object in the variable "$tabsessiontype2". I don't see the reason why the object isn't created. Thanks for you help.
Here is my TeacherController.php
if(isset($_POST['search']) && $_POST['sessiontype_name']){
$tabsessiontype2=Db::getInstance()->select_session_type2($_POST['sessiontype_name']);
if($tabsessiontype2->session_type()=='X'){
$view='teacher.php';
}
elseif($tabsessiontype2->session_type()=='XO'){
$view='teacherxo.php';
}
elseif($tabsessiontype2->session_type()=='note'){
$view='teachernote.php';
}
}
This is the function I call:
public function select_session_type2($name_session_type) {
$query = "SELECT * FROM session_types WHERE session_types.name_session_type='$name_session_type'";
$result = $this->_db->query($query);
$tableau = array();
if ($result->rowcount()!=0) {
while ($row = $result->fetch()) {
$tableau[] = new Sessiontype($row->code_session_type,$row->name_session_type,$row->quarter_session_type,$row->code_lesson,$row->session_type);
}
}
return $tableau;
}
Here is the SessionType class:
class SessionType{
private $_code_session_type;
private $_name_session_type;
private $_quarter_session_type;
private $_code_lesson;
private $_session_type;
public function __construct($code_session_type,$name_session_type, $quarter_session_type, $code_lesson,$session_type){
$this->_code_session_type = $code_session_type;
$this->_name_session_type = $name_session_type;
$this->_quarter_session_type = $quarter_session_type;
$this->_code_lesson = $code_lesson;
$this->_session_type = $session_type;
}
public function code_session_type(){
return $this->_code_session_type;
}
public function name_session_type(){
return $this->_name_session_type;
}
public function quarter_session_type(){
return $this->_lastname;
}
public function code_lesson(){
return $this->_email_student;
}
public function session_type(){
return $this->_session_type;
}
}
It looks like the function select_session_type2 is returning an array:
$tableau = array();
if ($result->rowcount()!=0) {
while ($row = $result->fetch()) {
$tableau[] = new Sessiontype($row->code_session_type,$row->name_session_type,$row->quarter_session_type,$row->code_lesson,$row->session_type);
}
}
return $tableau;
and you are expecting an object:
$tabsessiontype2=Db::getInstance()->select_session_type2($_POST['sessiontype_name']);
if($tabsessiontype2->session_type()=='X'){
$view='teacher.php';
}

Get PDO lastInsertId() after method called

In my code I use methods to insert data to MySQL database. The method then return either true or false.
If the method return true I would like to use lastInsertId() to run a second method.
Like
if($db->insertMethod($data)){
$lastId = $db->lastInsertId();
$db->secondInsertMethod($lastId, $data2)
}
db.class.php
public function insertMethod($data) {
$db = new DB();
$insert = //Run SQL insert
if($insert > 0 ) {
return true;
}else{
return false;
}
}
public function lastInsertId() {
return $this->pdo->lastInsertId();
}
In this case $db->lastInsertId(); will return 0. One workaround would be to have insertMethod to return this instead of just true but there must another way as well?
Edited!
the solution is correct
The data2 is linked to the data ?
you can also make :
public function insertMethod($data, $data2) {
$db = new DB();
$insert = //Run SQL insert
if($insert > 0 ) {
$this->insertMethod(this->lastInsertId(), $data2);
return true;
} else {
return false;
}
}
or if data2 is linked to the data
public function insertMethod($data) {
$db = new DB();
$insert = //Run SQL insert
if($insert > 0 ) {
$data2 = // get data2
$this->insertMethod(this->lastInsertId(), $data2);
return true;
} else {
return false;
}
}
public function insertMethod($id, $data) {
// your code...
}
or
public function insertMethod($data, $id = null) {
$db = new DB();
if($id == null)
// code to insert without id
else {
$insert = //Run SQL insert
if($insert > 0 ) {
$data2 = // get data2
$this->insertMethod($data2, this->lastInsertId());
}
}
}
The solutions are correct. For you to see who you think is the most appropriate in your situation.

Load specific data from array

So i have this class for loading data from my MySQL database :
class Db {
protected static $connection;
public function connect() {
if(!isset(static::$connection)) {
$config = parse_ini_file('config.ini');
static::$connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
}
if(static::$connection === false) {
return false;
}
return static::$connection;
}
public function query($query) {
return $this->connect()->query($query);
}
public function select($query) {
$rows = array();
$result = $this->query($query);
if($result === false) {
return false;
}
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function error() {
return $this->connect()->error;
}
public function quote($value) {
return "'" . $this->connect()->real_escape_string($value) . "'";
}
}
I use that class like this :
$db = new Db();
$rows = $db -> select("SELECT name, shortlink FROM `test` WHERE id=3");
It gives me an array with the data.
The problem is that i want to pull out specific data, for example the shortlink field.
How do i do that? I have tried echo $rows['shortlink'], but that gives me the following error :
Undefined index: shortlink
So how do I print specific data?
Your returned $rows columns is an array of associative arrays, to pull out shortlink data returned from the query you have to do something like this:
foreach($rows as $row) {
echo $row['shortlink'];
}

Undefined Offset: 0 - Codeigniter

When I send a Request to this Page including POST-DATA ({"bot_hw_id":"2147483647"}), i get the following error:
<p>Severity: Notice</p>
<p>Message: Undefined offset: 0</p>
<p>Filename: models/prometheus_model.php</p>
<p>Line Number: 26</p>
My Code:
Controller(update_bot function):
[code]public function update_bot()
{
$bot_data = json_decode($this->input->post('bot_data'));
$to_update = array(
'bot_last_update' => time(),
'bot_ip' => $_SERVER['REMOTE_ADDR'],
'bot_port' => $_SERVER['REMOTE_PORT']
);
$bot_data = $this->prometheus_model->get_bot_data_by_hw_id(/*$bot_data->{'bot_hw_id'}*/$bot_data->{'bot_hw_id'});
//echo $bot_data['bot_id'];
print_r($bot_data);
$this->prometheus_model->update('bots', array('bot_id' => $bot_data['bot_id']), $to_update);
//var_dump($bot_data);
}
Model(prometheus_model):
<?php
class Prometheus_model extends CI_Model {
var $tables = array(
'bots' => 'bots'
);
function __construct() {
parent::__construct();
}
public function tablename($table = NULL) {
if(! isset($table)) return FALSE;
return $this->tables[$table];
}
public function get($table, $where = array(), $single = FALSE, $order = NULL) {
$this->db->where($where);
if(isset($order)) {
$this->db->order_by($order);
}
$q = $this->db->get_where($this->tablename($table),$where);
$result = $q->result_array();
if($single) {
return $result[0];
}
return $result;
}
public function update($table, $where = array(), $data) {
$this->db->update($this->tablename($table),$data,$where);
return $this->db->affected_rows();
}
public function insert($table, $data) {
$this->db->insert($this->tablename($table),$data);
return $this->db->insert_id();
}
public function delete($table, $where = array()) {
$this->db->delete($this->tablename($table),$where);
return $this->db->affected_rows();
}
public function explicit($query) {
$q = $this->db->query($query);
if(is_object($q)) {
return $q->result_array();
} else {
return $q;
}
}
public function num_rows($table, $where = NULL) {
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
public function get_bot_data_by_hw_id($bot_hw_id) {
$q = $this->get('bots', array('bot_hw_id' => $bot_hw_id), TRUE);
return $q;
}
}
?>;
How can i fix this error?
First, I should mention that it's not absolutely a good and safe idea to query user input exactly without any process (as we see in your code). It's better to have different models at least for each table.
Anyway...
This way your function will be corrected:
public function get($table, $where = array(), $single = FALSE, $order = NULL) {
$this->db->where($where);
if(isset($order)) {
$this->db->order_by($order);
}
$q = $this->db->get_where($this->tablename($table),$where);
$result = $q->result_array();
// You should use $q->num_rows() to detect the number of returned rows
if($q->num_rows() == 1) {
// Return the first row:
return $result[0];
}
return $result;
}
It returns the first row when there is only one, and brings an array when $q->num_rows() is not equal to 1.
Hope it helps

Categories