Code:
<?php
if (isset($_REQUEST['g'])) {
if ($_REQUEST['g'] == "Set") {
$g = strtolower($_REQUEST['g'])."_title";
}else{
$g = strtolower($_REQUEST['g']);
}
$result1 = mysql_query("SELECT LEFT($g, 1) FROM cards GROUP BY $g ORDER BY $g ASC");
while ($row = mysql_fetch_array($result1)) {
?>
<?php echo substr($row[$g], 0, 1); ?>
<?php
}
}
?>
Error Message:
Notice: Undefined index: set_title in E:\xampp\htdocs\zipdown\include\sort.php on line 11
What am i missing?
Don't forget to escape the value of $g if it isn't known to be Set.
$g = mysql_real_escape_string($g);
Alias the column created by LEFT() as $g, enclosed in backticks:
$result1 = mysql_query("SELECT LEFT(`$g`, 1) AS `$g` FROM cards GROUP BY `$g` ORDER BY `$g` ASC");
//----------------------------------------^^^^^^^
Otherwise, the column name returned by your mysql_fetch_array() call is something like:
$row['LEFT(set_title,1)']
Note on security:
Given that your database must have a finite set of column names, it is advisable to use a whitelist against which you check the value of $g:
// Assuming your columns are named title, author, etc...
if (in_array($g, array('title','author','set_title','publisher','whatever'))) {
// do the rest of your work
}
else {
// Invalid value to $_REQUEST['g']
}
You should give an alias name for LEFT($g, 1), or the key name in result is just lkie LEFT(set_title, 1) if $g is set_title.
Your $g has the value of set_title and your $row does not have an element at that index.
To be more clear, $row['set_title'] does not exist.
If you ask for $row['set_title'] but there is no such key set_title available in $row, PHP will raise a notice to let you know that it couldn't find anything. It will return a null value.
This is a notice, not an error. Generally speaking, notices only show up when PHP is set up for development; for production sites, notices are usually turned off.
Check out the documentation here if you want to silence notices:
http://www.php.net/manual/en/function.error-reporting.php
http://www.php.net/manual/en/errorfunc.configuration.php
Related
When im trying to read some data from my data class i get a notice : undefined index.
Here is the script :
$data = $data_aanbieding->week_aanbieding($week, $jaar);
$productnaam = $html_entities->html_ent($data['p_productnaam']);
$verkoopprijs = $html_entities->html_ent($data['a_verkoopprijs']);
$aanbiedingsprijs = $html_entities->html_ent($data['a_aanbiedingsprijs']);
$hoeveelheid = $html_entities->html_ent($data['p_hoeveelheid']);
$eenheid = $html_entities->html_ent($data['p_eenheid']);
Those indexes i get the notice on, here the data class :
$result = $this->mysqli->query(
<<<EOT
SELECT
aanbiedingen.id as a_id,
aanbiedingen.product_id as a_product_id,
aanbiedingen.week as a_week,
aanbiedingen.jaar as a_jaar,
aanbiedingen.verkoopprijs as a_verkoopprijs,
aanbiedingen.aanbiedingsprijs as a_aanbiedingsprijs,
producten.product_id as p_id,
producten.productnaam as p_productnaam,
producten.hoeveelheid as p_hoeveelheid,
producten.eenheid as p_eenheid
FROM aanbiedingen
INNER JOIN producten ON producten.product_id = aanbiedingen.product_id
WHERE week={$week}
AND jaar={$jaar}
ORDER BY p_productnaam
EOT
);
if($result){
$waardes = array();
while ($row = $result->fetch_assoc()) {
$waardes[]=$row;
}
return $waardes;
}
It is simply a notice, meaning that one of your array keys (indexes) has not been defined. You can turn of notice reporting using the error_reporting() function or setting it in your php.ini file. You could also make sure that all the array records you're using actually have a value.
error_reporting(E_ALL & ~E_NOTICE); might do the trick (at the top of your script).
EDIT
Judging from your own reply, you should be looking at $data[0]['p...'] instead of just $data['p...]; the data you want seems to be stored inside a nested array, through which you should loop to access all the fetched $data records.
I have made this codes that registers the students using their learner id. And of course i wanted to make sure that there will be no duplication of learner id as students registered.These are my codes.
$select_query="select student_id from student_information where learner_id = '$learner_id'";
$result_set = mysql_query($select_query,$link_id);
if($row = mysql_fetch_array($result_set)){
$flag="exists";
header("location:Student_login.php?flag=$flag&student_id=$student_id");
die();
}
else{
/*
This block is used to insert the learners record in database
if the student_id is not yet registered in the database.
*/
mysql_query("SET AUTOCOMMIT = 0 ");
if(mysql_error() != null){
die(mysql_error());
}
Everytime there is a duplication of learner id. I am using this code on the other page for notifying me that the learner id exist already.
>This Learner Id( <?php $_GET['learner_id'] ?> ) already exists. Please try again with another Learner Id.</td>
The log in page give me notice
This Learner Id(Notice: Undefined index: learner_id in C:\xampp\htdocs\a\Student_login.php on line 61
) already exists. Please try again with another Learner Id.
How do i fix this one. Please advise.
In your first program where you get $learner_id. Are you declared or it is constant?
Did you use the below code above select statement.
$learner_id=$_GET['learner_id']
//or
$learner_id=$_POST['learner_id']
Considering it's a _GET, you can't be sure it's always there - unlike a constant.
if( array_key_exists('learner_id', $_GET) ) {
$_GET['learner_id'] = ctype_digit( (string) $_GET['learner_id']) ? (int) $_GET['learner_id'] : 0;
} else {
$_GET['learner_id'] = 0;
}
Check it exists
Check it doesn't contain any dodgy characters
If it does, reset the value to 0
If it doesn't exist, create it with a value of 0
0 value will of course fail - as you won't have index 0 in your database ;)
Tip: Never trust user input. Validate and sanitize data input ;)
Looking at your header, you're not including learner_id in the query string.
header("location:Student_login.php?flag=$flag&student_id=$student_id");
Change to;
header("location:Student_login.php?flag=$flag&learner_id=$student_id");
How are you getting this $learner_id (using GET or POST)?
//if
$learner_id=$_REQUEST['learner_id'];
$select_query="select student_id from student_information where learner_id = '$learner_id'";
$result_set = mysql_query($select_query,$link_id);
$num_rows = mysql_num_rows($result_set);
if($num_rows>0){
$row = mysql_fetch_array($result_set);
$flag="exists";
header("location:Student_login.php?flag=$flag&student_id=$student_id");
die();
}
else{
mysql_query("SET AUTOCOMMIT = 0 ");
if(mysql_error() != null){
die(mysql_error());
}
}
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'];
}
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.
I'm making a website using php and I'm having some trouble with an SQL query.
$dataArray = array();
$result = mysql_query("SELECT * FROM test WHERE web_id='$websiteID'")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$k = $row['kfoo'];
$v = $row['vbar'];
$dataArray[$k] = $v;
}
That's the code as it should be, however that causes the page to go blank (i.e. simply display all white). I've double checked and web_id is definitely the correct name and the correct case.
If I change web_id in the query to be, for instance, 'foo' (basically anything other than web_id), then the page will display, but with the error message "Unknown column 'foo' in 'where clause'".
Does anybody have any idea what could be causing this? Here's the code where I create the table test:
$dataDB = "CREATE TABLE test
(
data_id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(data_id),
web_id INT,
kfoo TEXT,
vbar TEXT
)";
mysql_query($dataDB,$con);
Update
Based on some of the answers here, I removed the quotes from around $websiteID and displayed errors using
error_reporting(E_ALL);
ini_set('display_errors', 1);
This displayed a lot of errors, including a syntax error earlier on that I've now fixed on. However, many errors remain and they don't make much sense to me. Here's the full code for my method:
function getOutputSQL($websiteID,$userInput) {
$result = mysql_query("SELECT * FROM websites WHERE websiteID=$websiteID")
or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$url = $row['url'];
$exp = $row['exp'];
$output= $row['textPrint'];
$endUrlStart = $row['outUrlStart'];
$endUrlEnd = $row['outURLEnd'];
$image = $row['image'];
$print = $row['print'];
$post = $row['post'];
$dataSource = $row['dataSource'];
$dataSourceName = $row['dataSourceName'];
}
// construct array of data names and values
$dataArray = array();
$result = mysql_query("SELECT * FROM test WHERE web_id=$websiteID")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$k = $row['kfoo'];
$v = $row['vbar'];
$dataArray[$k] = $v;
}
// construct array of expressions and replacements
$result = mysql_query("SELECT * FROM regex WHERE web_id=$websiteID");
$expArray = array();
while ($row = mysql_fetch_array($result)) {
$e = $row['ex'];
$r = $row['re'];
$expArray[$e] = $r;
}
return getOutput($userInput,$url,$exp,$output,$endUrlStart,
$endUrlEnd,$dataSource,$dataSourceName,$post,$image,$print,
$expArray,$dataArray);
}
The errors I'm getting are all like this -
Notice: Undefined variable: output in /home/daniel/web/resultsTest.php on line 113"
That repeats several times for url, exp, output, endUrlStart, endUrlEnd, dataSource, dataSourceName, post, image and print Line 113 is the large return line.
The thing is, as far as I can tell these variables are defined, and I know the table isn't empty, because I can display it on another page.
Solved
Sorted. The problem was actually in another part of my code - I was calling getOutputSQL incorrectly, but I've fixed it now!
I expect that your actual code actually does out put anything, If this is all the code you have it makes sence nothing is outputted since you don't when there is no error (no echo's or prints are templates or anything)
Also make sure you set both error_reporting and display_errors are set. You can do this from the top of your script using
error_reporting(E_ALL);
ini_set('display_errors', 1);
That way uou'll see all errors.
EDIT
PHP has multiple types of errors, including fatal errors, warnings and notices. Notices tell you when your using undefined variables or deprecated functions, you can pretty much ignore them. You can change the setting so you won't see them using:
error_reporting(E_ALL ^ E_NOTICE);
Then you will only see real errors (warnings and fatal errors).
More Edit
Then those variables are truly unset, try something like this before you call getOutput():
echo "<pre>";
var_dump($userInput);
var_dump($url);
//etc.
echo "</pre>";
and see if the variables are really set.
In general a blank page in php indicates disabled error notifications. At first you should enable them via .htaccess or php.ini.
BTW: As far as I know integers shouldn't be quoted in SQL.
Try this instead:
$dataArray = array();
if(is_numeric($websiteID){
$result = mysql_query("SELECT * FROM test WHERE web_id=$websiteID") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$k = $row['kfoo'];
$v = $row['vbar'];
$dataArray[$k] = $v;
}
}
Notice I removed the '' around the websiteID variable. This means mysql won't treat it as a string but as an int, which is what you specified in the mysql table creation. I also check to see if the websiteID is a number. If it is not, then there is no point in doing the sql query, as you will get zero results. This protects against sql injections.
Variables you define inside loops are destroyed at the end of the loop. That means the output variable you create in the first while loop does not exist after the loop. You should define them outside the while loop and then set the values inside the loop:
function getOutputSQL($websiteID,$userInput) {
$result = mysql_query("SELECT * FROM websites WHERE websiteID=$websiteID")
or die(mysql_error());
$url = "";
$exp = "";
$output = "";
//... etc for all the other variables you need in the function at the end.
while ($row = mysql_fetch_array($result)){
$url = $row['url'];
$exp = $row['exp'];
$output= $row['textPrint'];
$endUrlStart = $row['outUrlStart'];
$endUrlEnd = $row['outURLEnd'];
$image = $row['image'];
$print = $row['print'];
$post = $row['post'];
$dataSource = $row['dataSource'];
$dataSourceName = $row['dataSourceName'];
}
// the rest of your function...