Getting Error: Trying to get property of non-object in - php

I am getting this Trying to get property of non-object in at if ($fetch_size_id->num_rows > 0) and at else if ($fetch_size_id->num_rows == 0).
Can't figure out what is causing it.
The if conditions don't work as well...
When I var_dump($fetch_size_id) I get bool(false).
$fetch_size_id = $conn->query("
SELECT
`sizes`.`size_id`,
`sizes`.`width`,
`sizes`.`ratio`,
`sizes`.`construction`,
`sizes`.`diameter`
FROM `sizes`
WHERE
`sizes`.`width` = '".$conn->real_escape_string($row['5'])."'
AND `sizes`.`ratio` = '".$conn->real_escape_string($row['6'])."'
AND `sizes`.`construction` = '".$conn->real_escape_string($construction)."'
AND `sizes`.`diameter` = '".$conn->real_escape_string($row['7'])."
");
if ($fetch_size_id->num_rows > 0) {
$fetch_size_id = $fetch_size_id->fetch_object();
$temp_size_id = $fetch_size_id->size_id;
} else if ($fetch_size_id->num_rows == 0) {
//create new
} else {
//error
}
Am I overlooking something?

You are not checking variable $fetch_size_id
if (isset ($fetch_size_id){
if ($fetch_size_id->num_rows) {
$fetch_size_id = $fetch_size_id->fetch_object();
$temp_size_id = $fetch_size_id->size_id;
} else{
//create new
}
} else {
//error
}

Related

Why do I get undefined index error on my PHP function code

I even tried using "isset", but sadly it is not working.
function pageBanner($args=NULL){
if(!$args['title']){
$args['title']=get_the_title();
}
if (!$args['subtitle']){
$args['subtitle'] = get_field('page_banner_subtitle');
}
if (!$args['photo']){
if (get_field('page_banner_background_image')){
$args['photo'] = get_field('page_banner_background_image')['sizes']['pageBanner'];
}
else {
$args['photo']=get_theme_file_uri('images/pages.jpg');
}
}?>
I didn't know the problem on my if(!$args['title']){
$args['title']=get_the_title(); it is working, but the subtitle and photo are undefined index.
Try something like this:
function pageBanner($args = null)
{
if ($args === null) {
$args = [];
}
if (!isset($args['title'])) {
$args['title'] = get_the_title();
}
if (!isset($args['subtitle'])) {
$args['subtitle'] = get_field('page_banner_subtitle');
}
if (!isset($args['photo'])) {
$field = get_field('page_banner_background_image');
if ($field && isset($field['sizes']['pageBanner'])) {
$args['photo'] = $field['sizes']['pageBanner'];
} else {
$args['photo'] = get_theme_file_uri('images/pages.jpg');
}
}
}

Codeigniter blank page - Severity: Compile Error

I have codeigniter application which working well in justhost. I am trying to transfer it to bigrock host. But in new host its not working I can only see blank page with 500 error,no error logs in cpanel. Followed many solution in stackoverflow but couldn't fix(innitioally i thought its .htaccess problem), and now I tried define environment variable to development, I can see php error which says as below
A PHP Error was encountered
Severity: Compile Error
Message: Can't use method return value in write context
Filename: models/Home_model.php
Line Number: 77
Backtrace:
Home model screen shot
login function which is in home model:
public function login($data) {
if(filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$res = $data['email'];
}
else {
$settings = get_setting();
$pre = $settings->id_prefix;
$res = trim($data['email'],$pre);
}
$this->db->select('*');
$this->db->from('users');
$this->db->join('profiles', 'profiles.email = users.email','left');
$this->db->where('user_status','1');
$this->db->where('users.email', $res);
$this->db->or_where('matrimony_id',$res);
$chk_qry = $this->db->get();
//$chk_qry = $query->row();
//echo $this->db->last_query();die;
if ($chk_qry->num_rows() == 1) {
$pass = $this->encrypt->decode($chk_qry->row()->password);
if($data['password'] == $pass) {
$this->db->where('user_id', $chk_qry->row()->user_id);
$usr_qry = $this->db->get('profiles');
if(!empty($usr_qry->result())) {
if($usr_qry->result()[0]->profile_status != 2) {
if($usr_qry->result()[0]->profile_status != 4) {
if($usr_qry->result()[0]->profile_approval == 1) {
$status = 1;
$this->session->set_userdata('logged_in',$usr_qry->result()[0]);
$data1['date_time'] = date('Y-m-d H:i:s', time());
//$data1['user_id']=$usr_qry->result()[0]->user_id;
$data1['matrimony_id']=$usr_qry->result()[0]->matrimony_id;
$query = $this->db->where('matrimony_id',$data1['matrimony_id']);
$query = $this->db->get('active_members');
if ($query->num_rows() > 0){
$this->db->where('matrimony_id',$data1['matrimony_id']);
$this->db->update('active_members',$data1);
} else {
$this->db->insert('active_members', $data1);
}
} else { $status = 2; } // Profile Not Approved
} else { $status = 7; } // Profile Deactivated
} else { $status = 5; } // Profile Deleted or Banned
} else { $status = 6; } // No Accounts Found
} else { $status = 3; } // Ivalid Password
} else { $status = 4; } // Email not exist
return $status;
}
I wonder how this same script working fine in justhost.
Solved problem!!! silly me,
Updated php version from 5.4 to 5.6

PHP Shopping Cart

I am trying to add a product to my shopping cart.
I am getting an error saying:
Warning: Invalid argument supplied for foreach() in
It is telling me I am getting an error for the following code:
function isInCart($id) {
if (!empty($_SESSION['sess_uid']['cart'])) {
foreach ($_SESSION['sess_uid']['cart'] as $report) {
if ($report['reportID'] == $id) {
// Report ID found in Cart
return true;
}
}
// Looped through cart, ID not found
return false;
} else {
// Cart empty
return false;
}
}
The particular line from the above that is flagging the error is:
foreach ($_SESSION['sess_uid']['cart'] as $report) {
I am also getting the following error message:
Fatal error: Only variables can be passed by reference in
The code this relates to is the following:
function addToCart($id) {
$report = getReportByID($id);
$author = $report['userID'];
if (!empty($report)) {
// Got the report
if (!empty($_SESSION['sess_uid']['cart'])) {
if (!isInCart($id) && !isOwner($author) && !hasPurchased($id)) {
array_push($_SESSION['sess_uid']['cart'], $report);
return true;
} else {
return false;
}
} else {
$_SESSION['sess_uid']['cart'] = array();
if (!isInCart($id) && !isOwner($author) && !hasPurchased($id)) {
array_push($_SESSION['sess_uid']['cart'], $report);
return true;
} else {
return false;
}
}
} else {
// Unable to get report by ID
return false;
}
}
The particular line of code from the above that is flagging the error is:
array_push($_SESSION['sess_uid']['cart'], $report);
The code below is what gets my reports to populate the store
<?php
function getReportByID($id) {
$conn = new mysqli(localhost, root, DBPASS, DBNAME);
$sql = "SELECT * FROM reports WHERE reportID = '" . $conn->real_escape_string($id)."';";
// Performs the $sql query on the server
$report = $conn->query($sql);
return $report->fetch_array(MYSQLI_ASSOC);
}
?>
Any help would be greatly appreciated.
Thanks
i think this wil help:
it typcast your session as an array so even when the session is empty you dont get an error
foreach ((array)$_SESSION['sess_uid']['cart'] as $report) {
let me know if this fix the error?

GET Multiple MySQL Rows, Form PHP Variables, and Put Into Json Encoded Array

I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}

retrieving Message from a json array

I want to check the username availability while users register. I am working on the front end. The backend code was given to me.
These are the php code in signup.php
if (isset($_GET['chkusername']))
JSON_username_avail($_GET['chkusername']);
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username, $ret));
die();
}
function validate_username($username, & $retval_arr) {
if ($username == NULL)
$retval_arr['E_UserName'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['E_UserName'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['E_UserName'] = "USERNAME_EXISTS";
return $retval_arr;
}
function username_validation($user) {
$username = str_split($user);
foreach($username as $i) {
$i = ord($i);
if ($i >= 48 and $i <= 57)
continue;
if ($i >= 65 and $i <= 90)
continue;
if ($i >= 97 and $i <= 122)
continue;
return FALSE;
}
return TRUE;
}
function data_not_exists($table, $field, $data, $CSense = FALSE) {
$conn = connect_db();
$data = filter_var($data, FILTER_SANITIZE_STRING);
if ($CSense == TRUE)
$sql = "SELECT * FROM ".$table.
" WHERE ".$field.
"='".$data.
"'";
else
$sql = "SELECT * FROM ".$table.
" WHERE upper(".$field.
")='".$data.
"'";
$result = mysqli_query($conn, $sql);
switch ($result - > num_rows) {
case 0:
return TRUE;
break;
case 1:
return FALSE;
break;
default:
die("500 Internal Server Error: 122");
} //switch
}
Now I dont know that much of php. I created a javascript function to send the username to the signup.php page for validation.
Here is my function
function submit_form() {
var u = document.getElementById("username").value;
$.post("signup.php", {
"chkusername": u
},
function (data) {
var x = data; //here i dont know how to get the return string. Whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS.
}, "json");
}
here i am getting the value of x as [object Object].
But i need to store the return message in variable x. I want to know whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS. Kindly help me with that.
The username is POSTed but in the PHP you try to access it with $_GET, change to:
if (isset($_POST['chkusername']))
JSON_username_avail($_POST['chkusername']);
Also your validation logic doesn't look right, what if the username is valid and available? I would add an else clause and set a success variable:
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username));
die();
}
function validate_username($username) {
$retval_arr = array('success' => false, 'message' => '');
if ($username == NULL)
$retval_arr['message'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['message'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['msessage'] = "USERNAME_EXISTS";
else
$retval_arr['success'] = true;
return $retval_arr;
}
and the ajax:
if(!data.success){
console.log(data.message);
} else {
// valid and available
}
Try,
function(data){
var x = data.E_UserName;
}, "json");
also change your request to GET as per MrCode's answer
function submit_form() {
var u = document.getElementById("username").value;
$.get("signup.php", {
"chkusername": u
},
function (data) {
var x = data.E_UserName
}, "json");
}

Categories