php error Trying to get property of non-object - php

I have an admission form which is getting value from database table. Scenario is I have list of courses a student select a course and I pass course ID in URL then use this code to get corresponding Course name in the field: (The form is designed in joomla using breezing forms.)
$this->execPieceByName('ff_InitLib');
$course_id= JRequest::getVar('CID');
global $database, $rec;
$database->setQuery("SELECT * FROM course_list WHERE record = '$course_id' AND name = 'CourseName'");
$row = $database->loadObjectList();
$rec = $row[0];
ff_setValue('ProsCourse', $rec->value);
Unfortunately I get this error:
* EXCEPTION CAUGHT BY FACILEFORMS *
PHP error level : E_NOTICE
PHP filename : /home/web10385/public_html/**/components/com_breezingforms/facileforms.process.php(1219) : eval()'d code
PHP linenumber : 7
Last known pos : Before form custom piece code at line 1
Error message : Undefined offset: 0
* EXCEPTION CAUGHT BY FACILEFORMS *
PHP error level : E_NOTICE
PHP filename : /home/web10385/public_html/**/components/com_breezingforms/facileforms.process.php(1219) : eval()'d code
PHP linenumber : 8
Last known pos : Before form custom piece code at line 1
Error message : Trying to get property of non-object
The above code is the before form piece.
Thanks

You are not constructing the database object....
You have declared $database but you haven't initialized it with an object...That's the problem..It seems you have forgotten it.
Since, before initializing it, it's a non-object type. And you have tried to use it two times, hence you got two errors.
global $database, $rec;
^^ uninitialized....
$database->setQuery("SELECT * FROM course_list WHERE record = '$course_id' AND
^^ but you are using it here....
$row = $database->loadObjectList(.....
^^ here....
From the information seen this is what may be the solution:
EDIT:
$database=JFactory::getDbo();

Here's what I have done:
In Form pieces > Before form add this script:
$this->execPieceByName('ff_InitLib');
$course_id= JRequest::getVar('CID');
//intialize BF utilities
$this->execPieceByName('ff_InitUtilities');
global $database, $rec;
$database = ff_select('SELECT * FROM course_list WHERE record = '.$course_id.' ');
$rec = $database[0];
Then add this to the VALUE field of the TEXT field (course name):
<?php global $rec; return $rec->name; ?>
That should do it.
Peace.

Related

How to iterate over php error and continue while loop?

I am using the following code to parse definitions from a remote website , according to the usernames in my database. I am using simple html dom parser.
//database connection
include 'db.php';
//display errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include 'simple_html_dom.php';
//select usernames order alphabetically
$row = mysqli_query($conn, "SELECT user_name FROM (
SELECT *
FROM store
ORDER BY user_id DESC)
AS store ORDER BY user_id ASC");
//echo out definitions of usernames
while($lastusers = mysqli_fetch_array($row)) {
echo '<br>' . $lastusers["user_name"];
echo '<br>Definition:<br>';
$html = file_get_html("https://www.merriam-webster.com/dictionary/" . $lastusers["user_name"]);
$title = $html->find("div.card-primary-content", 0)->innertext;
echo $title;
//save definitions to corresponding username
$save = mysqli_query($conn, 'UPDATE store
SET def = $title,
WHERE user_name = $lastusers["user_name"]'
)
}
My while loop will begin to generate the definitions per username , until certain pages are not found resulting in an error that stops the loop.
Warning:
file_get_contents(https://www.merriam-webster.com/dictionary/colourings):
failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in
/app/simple_html_dom.php on line 75 Fatal error: Call to a member
function find() on boolean in /app/test.php on line 18
My question is how to skip over the username that throws the error and continue the loop? Also because their are over 500 usernames , this operation is very intensive , so i'm saving the definitions , and would like to avoid the errors being saved to the database.
You can suppress the warning like shown in the following link
How can I handle the warning of file_get_contents() function in PHP?
Or an other alternative is to write a custom error handler. See this link
PHP: How to use set_error_handler() to properly deal with all errors except notices?

add mysql query to virtuemart

I'm new to virtuemart.
While trying to add hits to virtuemart products
I create new filed in "jjws5_virtuemart_products" in database and called it views.
Then I added my PHP code to the place I need it to appear in.
templates/mytemplate/html/com_virtuemart/productdetails/default.php:
<?php //views hits
mysql_query("UPDATE jjws5_virtuemart_products SET views=views+1 WHERE virtuemart_product_id = '$virtuemart_product_id'");
$views_hits = mysql_query("SELECT views FROM jjws5_virtuemart_products WHERE virtuemart_product_id = '$virtuemart_product_id'");
while($total_views = mysql_fetch_array($$views_hits)){
echo "Hits: ".$total_views['views'];
}
?>
However, it's not showing anything.
What should I do to show it?
You use a variable variable to fetch result (maybe only a typo).
Change:
while($total_views = mysql_fetch_array($$views_hits))
in:
while($total_views = mysql_fetch_array($views_hits))
And, in the future, remember to activate error checking in our php code:
error_reporting( E_ALL );
ini_set( 'display_error', 1 );
With error checking, our original code produce this error:
PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in (...)

Object of class mysqli could not be converted to string

I am getting this error from the following code:
function updateRank($master_list, $event_id)
{
$cnt_ml = count($master_list);
echo "count master list = $cnt_ml<br>";
$b=1;
for ($k=0; $k<$cnt_ml; $k++)
{
echo "master list element 1 - ".$master_list[1]."<br>";
$foo = $master_list[$k];
// Update each team in event_team table
$update = "UPDATE event_team
SET pool_rank = $b
WHERE event_id = $event_id
AND team_id = $foo";
mysqli_query($conn, $update);// or die ('Could not run insert in event_team table');
echo "|".$update."|<br>"; // Leave this line for debugging the sql query.
$b++;
}
}
Specifically "$foo" is throwing the error. The "master_list" array is being passed correctly. When running the code, $cnt_ml returns "5" (which is absolutely correct). The line with:
echo "master list element 1 - ".$master_list[1]."<br>";
Returns "54" (which is correct).
Since the script is successfully able to read the array elements and post them, why is the script throwing the error when I include it in the UPDATE? It is able to see the array data but choking when trying to use the data in the UPDATE.
Thanks in advance!
Variable $conn is not declared. Or it's declared globally and you forgot to add
global $conn;
in updateRank function

MySQL , PHP : Hide specific Value from table

I am working on a ' Show Online user' script where the script show everybody who is online.
Now i want to remve the entry which matches the session user name i.e "if (Online user = Session User name ) then do not display it , just like on facebook.com chat where your friends id is shown and not your own Id
my code is as follows :
<?php
mysql_connect("localhost","root","12345");
mysql_select_db("accounts");
$user = $_SESSION['user_name'];
$result = mysql_query("SELECT * FROM online * WHERE ($chat<>$user)");
while($row=mysql_fetch_array($result)) {
$chat=$row["emp_name"];
$chlk = ("<a href=javascript:void(0) onclick=javascript:chatWith('$chat')>$chat</a>");
$chs = ("<a>$chat</a>");
if ($chat <> $user) {
echo $chlk;
}
else {
echo $chs;
}
echo $chlk;
}
?>
I am getting the following error :
Notice: Undefined variable: chat in localhost/accounts/removeuser.php on line 7
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given localhost/accounts/removeuser.php on line 9
Any help is highly appreciated.
Correction in query.
"SELECT * FROM online WHERE ($chat<>$user)"
OR
Replace $chat in query with your table field name.
there is extra * before WHERE that is invalid.
and $chat is not defined in query.
<> is not PHP as far as I know. You need to use !==.
(and probably read up on some PHP basics...)

Notice: Undefined offset: 0 in

I am getting this PHP error, what does it mean?
Notice: Undefined offset: 0 in
C:\xampp\htdocs\mywebsite\reddit_vote_tut\src\votes.php on line 41
From this code:
<?php
include("config.php");
function getAllVotes($id)
{
$votes = array();
$q = "SELECT * FROM entries WHERE id = $id";
$r = mysql_query($q);
if(mysql_num_rows($r)==1)//id found in the table
{
$row = mysql_fetch_assoc($r);
$votes[0] = $row['votes_up'];
$votes[1] = $row['votes_down'];
}
return $votes;
}
function getEffectiveVotes($id)
{
$votes = getAllVotes($id);
$effectiveVote = $votes[0] - $votes[1]; //ERROR THROWN HERE
return $effectiveVote;
}
$id = $_POST['id'];
$action = $_POST['action'];
//get the current votes
$cur_votes = getAllVotes($id);
//ok, now update the votes
if($action=='vote_up') //voting up
{
$votes_up = $cur_votes[0]+1; //AND ERROR THROWN HERE
$q = "UPDATE threads SET votes_up = $votes_up WHERE id = $id";
}
elseif($action=='vote_down')
{
$votes_down = $cur_votes[1]+1;
$q = "UPDATE threads SET votes_down = $votes_down WHERE id = $id";
}
$r = mysql_query($q);
if($r)
{
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote." votes";
}
elseif(!$r) //voting failed
{
echo "Failed!";
}
?>
You are asking for the value at key 0 of $votes. It is an array that does not contain that key.
The array $votes is not set, so when PHP is trying to access the key 0 of the array, it encounters an undefined offset for [0] and [1] and throws the error.
If you have an array:
$votes = array('1','2','3');
We can now access:
$votes[0];
$votes[1];
$votes[2];
If we try and access:
$votes[3];
We will get the error "Notice: Undefined offset: 3"
first, check that the array actually exists, you could try something like
if (isset($votes)) {
// Do bad things to the votes array
}
This answer helped me https://stackoverflow.com/a/18880670/1821607
The reason of crush — index 0 wasn't set. Simple $array = $array + array(null) did the trick. Or you should check whether array element on index 0 is set via isset($array[0]). The second variant is the best approach for me.
Use print_r($votes); to inspect the array $votes, you will see that key 0 does not exist there. It will return NULL and throw that error.
getAllVotes() isn't returning an array with the indexes 0 or 1. Make sure it's returning the data you want by calling var_dump() on the result.
I encountered this as well and the solution is simple, dont hardcode the array index position in your code.
Instead of
$data[0]['somekey'] do
foreach($data as $data_item)
{
echo $data_item['somekey'];
} If there is an array or more you can perform your desired action inside the loop, but if it's undefined it will not bring an error. you can also add other checks on top of that.
You could also add a variable and increment it in a for in loop to limit your looping if you want only the first positions or something.
As explained it happens because there is no data in the $cur_votes[0] and hence it throws an error.
To ensure your code works fine, before performing "$votes_up = $cur_votes[0]+1;" echo the $cur_votes[0] value to see if there is any value stored or not.
Surely, there is no value stored.
function getEffectiveVotes($id)
According to the function header, there is only one parameter variable ($id).
Thus, on line 27, the votes[] array is undefined and out of scope. You need to add another
parameter value to the function header so that function getEffectiveVotes() knows to expect two parameters. I'm rusty, but something like this would work.
function getEffectiveVotes($id, $votes)
I'm not saying this is how it should be done, but you might want to research how PHP
passes its arrays and decide if you need to explicitly state to pass it by reference
function getEffectiveVotes($id &$votes) <---I forget, no time to look it up right now.
Lastly, call function getEffectiveVotes() with both arguments wherever it is supposed to be called.
Cheers.
As you might have already about knew the error. This is due to trying to access the empty array or trying to access the value of empty key of array. In my project, I am dealing with this error with counting the array and displaying result.
You can do it like this:
if(count($votes) == '0'){
echo 'Sorry, no votes are available at the moment.';
}
else{
//do the stuff with votes
}
count($votes) counts the $votes array. If it is equal to zero (0), you can display your custom message or redirect to certain page else you can do stuff with $votes. In this way you can remove the Notice: Undefined offset: 0 in notice in PHP.
If you leave out the brackets then PHP will assign the keys by default.
Try this:
$votes = $row['votes_up'];
$votes = $row['votes_down'];
In my case it was a simple type
$_SESSION['role' == 'ge']
I was missing the correct closing bracket
$_SESSION['role'] == 'ge'
If you are using dompdf/dompdf and error occure in vendor/dompdf/dompdf/src/Cellmap.php then
It looks like we're using the wrong frame id in the update_row_group method. Initial testing seems to confirm this. Though that may be because this is strictly a paged table issue and not too many of the documents in my test bed have paged tables.
Can you try changing line 800 to:
$r_rows = $this->_frames[$g_key]["rows"];
($g_key instead of $r_key)
https://github.com/dompdf/dompdf/issues/1295
Use mysql row instead
mysql_fetch_row($r)
Meanwhile consider using mysqli or PDO
?>
Try seeding data with command: php artisan db:seed.
its just a warning use:
error_reporting(0);
it shows when we do not initialize array and direct assigning value to indexes.
somefunction{
$raja[0]="this";
$raja[1]="that";
}
instead :
somefunction{
$raja=array(0=>'this',1='that');
//or
$raja=array("this","that");
}
it just notification, do not generate any output error or any unexpected output.

Categories