Notice: Undefined offset: 0 in - php

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.

Related

How to loop through a fetched query in PHP using mysql

I have a PHP class where I am initializing an array retrieved from database in the constructor:
class TableClass{
public function __construct($con, $id){
$this->con = $con;
$query = mysqli_query($this->con, "SELECT * FROM table1 WHERE id='$id'");
$this->table_result= mysqli_fetch_array($query);
}
}
I have different functions that I want to use the array without having to fetch again. I just want to loop through the results and make some calculations.
I tried the following syntax:
public function getNumberOfComments(){
for ($i = 0; $i < count($this->table_result); $i++) {
$comment= $this->table_result[$i]['comment'];
}
}
I am getting an error:
Illegal string offset "comment"
What is the correct syntax?
You are fetching one row from the result set:
$this->table_result= mysqli_fetch_array($query);
Assuming that the id is the primary key, you will have 0 or 1 rows in your result set, so if a row is found, you can access the fields directly without using a loop:
$comment= $this->table_result['comment'];
Illegal string offset "comment" is telling you that the value of $this->table_result[$i] is not an array, and therefore does not contain an element named comment.
The problem is possibly being caused by the code in the constructor failing to work properly; you don't have any error checking in there, so if it fails, it won't tell you about it.
Add some error checking in the constructor, find out why it's failing, and fix it.

PHP echo fails to give output when a longer string is echoed

I am implementing keyword search in PHP. When no. of results from DB are greater than 264 PHP echo fails to give any output. Any idea what might be the problem here?
// my algo is -
$result = mysql_query(searchQueryString) or die(mysql_error());
$row = mysql_fetch_assoc($result);
//Create a $json_array of required values
$str_to_print = json_encode($json_array);
echo $str_to_print;//this gives empty output when no. of rows from DB > 264
//Everything else is working properlycode here
Please excuse this, I wanted to comment but am unable to due to rep.
I used this statement: print json_encode(array(1, 2, 3, 4, 5)); and got the result of: [1,2,3,4,5].
Either your result from the mysql_query is wrong, or something else is.
Just noticed, you are using this line of code:
$str_to_print = json_encode($json_array);
But where is $json_array set? Is it set at all or are you passing a null pointer to the function? Error: Notice: Undefined variable: json_array

PHP Notice: Undefined index

I'm getting "PHP Notice: Undefined index: company" when I run a script, this is the part that is going bad, how can I fix it ?
while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
$numer = $row['fonefull'];
$sql = "SELECT company FROM numeros.portados WHERE number = '$numer' LIMIT 1";
$result = $conn->query($sql);
echo $sql;
$operadoraResult = $consulta->fetch(PDO::FETCH_ASSOC);
if(is_array($operadoraResult))
$resultcompany = $operadoraResult['company'];
Thanks
$operadoraResult can be an empty array if there's no company with the given number.
So there won't be an index 'company'.
Try
if(!empty($operadoraResult))
Notices are kinda like warnings saying "Hey, this isn't going to cause an issue that will break anything by itself, but you might be making an assumption about a variable that is not true"
Like you may assume that a value actually exists at that index, but if the index doesn't exist you're actually getting back NULL.
You can change whether or not notices are displayed by changing the level of error reporting for php. You can do this by either editing the value of display_errors in your php.ini file or you can change in during runtime using the error_reporting function.
In this specific case its letting you know that in this line:
$resultcompany = $operadoraResult['company'];
you are trying to access an element in the array $operadoraResult at the index 'company', but there is no index that exists at 'company'.
The array $operadoraResult does not have an element with the key company.
What happens if you change:
$result = $conn->query($sql);
echo $sql;
$operadoraResult = $consulta->fetch(PDO::FETCH_ASSOC);
if(is_array($operadoraResult))
$resultcompany = $operadoraResult['company'];
into this:
foreach ($conn->query($sql) as $operadoraResult)
{
if(is_array($operadoraResult))
$resultcompany = $operadoraResult['company'];
}

Displaying one record at a time in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does the PHP error message “Notice: Use of undefined constant” mean?
I am trying to display one (record) question at a time in the same page. I put a condition at the beginning of the code to check if this is the first time the page loads, if it is, then display the first record. Otherwise, go to the "else" statement where the second record will be displayed. Every time a record is displayed, the counter increases by one ($i++). Also, I saved all the retrieved records in an array and reading the records one at a time from this array.
I don't know why I am getting errors here like the the following:
(1) Use of undefined constant i - assumed 'i'
(2) Undefined index: i
Does anyone know how to fix this problem?
Here is my code:
<?php
$f_name = $_SESSION['first_name'];
$l_name = $_SESSION['last_name'];
$arr_rows;
$i;
if (!isset($_POST['next']))
{ //if form is not submitted,
$command2 = "SELECT user_id FROM user_info WHERE user_info.first_name = '$f_name'
and user_info.last_name = '$l_name'";
$command1 = "SELECT * FROM topics, documents WHERE topics.topic_id =documents.topic_id";
$i=0; // Counter for the number of documents per topic
$userid = mysql_query($command2);
$results = mysql_query($command1);
$num=mysql_numrows($results);
//////////////
$arr_rows = array();
while( $row = mysql_fetch_array( $results ) )
$arr_rows[] = $row;
$arr = mysql_fetch_row($userid);
$id_user = $arr[0];
echo $f_name;
$relevancy = "This is the first time to load this page";
$f1=$arr_rows[i]['topic_name'];
$f1_topic_description=$arr_rows[i]['topic_descrip'];
$f1_doc_content=$arr_rows[i]['doc_content'];
++$i;
}
else
{ //otherwise,
$relevancy = $_POST['RadioGroup1'];
$f1=$arr_rows[i]['topic_name'];
$f1_topic_description=$arr_rows[i]['topic_descrip'];
$f1_doc_content=$arr_rows[i]['doc_content'];
++$i;
}
?>
$f1=$arr_rows[i]['topic_name'];
$f1_topic_description=$arr_rows[i]['topic_descrip'];
$f1_doc_content=$arr_rows[i]['doc_content'];
should be
$f1=$arr_rows[$i]['topic_name'];
$f1_topic_description=$arr_rows[$i]['topic_descrip'];
$f1_doc_content=$arr_rows[$i]['doc_content'];
You were missing the dollar sign on the variable "i".
PHP doesn't store your variables over to the next request.
You can add the counter information ($i) either to a session variable, cookie, or request parameter. Otherwise your $i will always start again from zero.
When using "i" to specify an index in your arrays, you are missing the $. For example:
$f1=$arr_rows[i]['topic_name'];
$f1_topic_description=$arr_rows[i]['topic_descrip'];
$f1_doc_content=$arr_rows[i]['doc_content'];
should read
$f1=$arr_rows[$i]['topic_name'];
$f1_topic_description=$arr_rows[$i]['topic_descrip'];
$f1_doc_content=$arr_rows[$i]['doc_content'];
You missing the $ before the variable name. Check through your code and replace i with $i.
The error is here I think... replace i with $i so you're actually calling your variable
$f1=$arr_rows[$i]['topic_name'];
$f1_topic_description=$arr_rows[$i]['topic_descrip'];
$f1_doc_content=$arr_rows[$i]['doc_content'];

unserialize problem

I have another problem with my scripy now I have made it more advance, first off the count function doesnt work properly and it gives this error.
Warning: array_push() [function.array-push]: First argument should be an array in C:\wamp\www\social\add.php on line 42
Here is my script:
$query = mysql_query("SELECT friends FROM users WHERE id='$myid'");
$friends = mysql_fetch_array($query);
$friends2 = unserialize($friends['friends']);
if (count($friends2) == 0) {
//option 1
$friends2 = array($id);
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");
}else{
//option 2
array_push($friends2, $id);
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");
It seems that $friends2 is not an array. Use the var_dump($friends2) function to see its value.
If you run this code right after having created the database but before putting any data in there, "unserialize($friends['friends']);" returns something other than an array. Probably an empty string. So in option 2, you may want to do something like this before array_push:
if (!is_array($friends2)) {
$friends2 = array();
}
This way, if the person has no friends by this point (sad.. but you'll fix it by pushing a new friend to them), an empty friends list gets initialized.
Plus, any time you see two identical lines of code in different parts of the "if" condition...
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");
That's a signal that you should restructure your code so that you'd only have one copy of these lines.
This may not sound helpful, but your database design is quite stange.
Why is $friends2 not an array? Try to print_r () $friends after fetching an array to see if you actually get what you want from database in the first place.
Also, your count check is redundant. To add to an array, just go $friens2[] = $id; If $friends2 were empty, it will just make a new array of 1 element ($id), otherwise it will add it.
Your question contains the answer: unserialize($friends['friends']) seem to return non-array and count($friends2) is not zero - this can happen, for example, if number passed. Have you tried to examine the $friends['friends'] data? Simplest way would be to make additional check is_array($friends2)

Categories