index error in database reading PHP script [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
So Im back with another php error, that I cant solve. But Im getting better:)
I have created a simple script that stores images in a database, I have no problems to store the file, but when Im reading the file i get an index error. It says
Notice: Undefined index: id in C:\wamp\www\gallery2\show.php on line
13
I cant really get what the problem is since Im thinking that everything is correct !?
the code for showing the images are
<?php
$username = "root";
$password = "";
$host = "localhost";
$database = "guestbook";
#mysql_connect($host, $username, $password) or die("Can not connect to database: ".mysql_error());
#mysql_select_db($database) or die("Can not select the database: ".mysql_error());
$id = $_GET['id'];
if(!isset($id) || empty($id)){
die("Please select your image!");
}else{
$query = mysql_query("SELECT * FROM tbl_images WHERE id='".$id."'");
$row = mysql_fetch_array($query);
$content = $row['image'];
header('Content-type: image/jpg');
echo $content;
}
?>

You are trying to access $_GET['id']. However, if no argument id is present in the querystring of the request, the index id will not be available in the $_GET superglobal. That's why you receive the notice.
So you should be doing something like this:
$id = !empty( $_GET[ 'id' ] ) ? $_GET[ 'id' ] : null;

It is telling you the value id does not exist in the $_GET array. Does the URL you are accessing have a ?id=something on it?

The variable...
$_GET['id'];
...doesn't contain a value, therefore it is not defined.
Check if your form mechanism leading to this $_GET is working, maybe var_dump it.
If your script should cope with an empty variable there, maybe check this variable first, something like this:
$id = "";
if (isset($_GET['id']) { $id = $_GET['id']; }

Related

How would I fetch variables from an URL and put it into my Database? [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
So I've looked up many tutorials on how to get variables like http://example.net/pb.php?id=1&affsub=stringhere&key=123abc and then when that page is accessed I want it to be put into my database. But I have tried doing so by using this piece of code. And when accessing the page using ?id=1&affsub=stringhere&key=123abc it doesn't show any errors on the page and it also doesn't put it in the database as well. Now I'm not sure what is happening or what I need to do for that to work.
<?
if( $_POST )
{
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("tbl", $con);
$id = $GET['id'];
$affsub = $_GET['affsub'];
$key = $_GET['key'];
$id = mysql_real_escape_string($id);
$affsub = mysql_real_escape_string($affsub);
$key = mysql_real_escape_string($key);
$query = "
INSERT INTO `tbl`.`users` (`id`, `affsub`, `key`) VALUES ('$id',
'$affsub', '$key');";
mysql_query($query);
echo "<h2>User added to system.</h2>";
mysql_close($con);
}
?>
Everything is inside if ($_POST) so you need to to retrieve the data from $_POST[] instead of $_GET[] (and the typo. error $GET['id']). In addition, the parameters should not be in the URL - that would normally indicate a form using the get method but for updating a database you normally want to use method="post" in your form.

mysqli_error() expects parameter 1 to be mysqli, null given

I have a a form that pulls data from a database(mysql to be specific) and echos the data into the value section of <input> tags. It doesn't seem to be working I have coded a view section of my website to do the same thing but from a different table in my database. I use the same code to make making changes easy and if another developer works on my site in the future. Anyway it doesn't seem to be working I'm not sure why though.
The full error I get:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/caseol5/public_html/jj/admin/news_update.php on line 9
Here is line 9 that the error is referring to:
$result = mysqli_query($link,$sql);
I know that both of those function are not null as I did:
echo $link
echo $sql
before that line after I started feting the error and they both are not null.
Here is the full code segment:
$nid = $_GET['nid'];
include ("../sql/dbConnect.php");
$sql = "SELECT * FROM jj_news WHERE news_id = $nid";
echo "<p>The SQL Command: $sql </p>";
echo "<p>Link: $link </p>";
$result = mysqli_query($link,$sql);
if (!$result)
{
echo "<h1>You have encountered a problem with the update.</h1>";
die( "<h2>" . mysqli_error($link) . "</h2>") ;
}
$row = mysqli_fetch_array($result);
$ntitle = $row['news_title'];
$ntline = $row['news_titleline'];
$ndesc = $row['news_desc'];
$nother = $row['news_other'];
I have looked into mysqli_query and I can't find anything I'm missing. I have also tired breaking the code down (and running parts of it and it gives the same error. My guess is it something small that I missed. I've looked at other question on this site that do that are a little similar but none seem to help. I've been looking at this for a while now and need another pair of eyes.
Update
As requested the contents of my dbconnect.php file:
$hostname = "localhost";
$username = "caseol5_jjoes";
$database = "caseol5_jj_site";
$password = "password1";
$link = mysqli_connect($hostname, $username, $password, $database);
$link = mysqli_connect($hostname,$username,$password,$database) or die("Error " . mysqli_error($link));
if (!$link)
{
echo "We have a problem!";
}
As clearly stated in the error message, mysqli_querydocs expects the first parameter to be a mysqli resource. In your case, this parameter is called $link but it holds a null value. A proper mysqli resource is normally obtained from connecting with the database by making use of mysqli_connectdocs
I expect the ../sql/dbConnect.php file holds the logic to connect with the database. Verify whether the $link variable is indeed initialized there. If it's not there, try to find an occurrence of mysqli_connect - maybe the resource is set to a different variable.
Without knowing what exactly is in ../sql/dbConnect.php, your problem right now is that you do not have a valid mysqli resource to use for mysqli_query.

Passing a SESSION variable, getting errors

I am trying to pass a session variable from one page to another but it seems liek the session variable is empty on the next page. Thanks for the help!
Here is the entirety of the code on the two pages.
mysql_connect($db_hostname, $db_username, $db_password);
mysql_select_db($db_sitename);
$pagename= $row_getDisplay['USER_NAME'];
$query=mysql_query("SELECT * FROM COMMENTS WHERE COMMENT_ON='$pagename' LIMIT 0, $no_of_comments");
echo "<hr />";
echo "<h3>Latest Comments</h3>";
session_start();
$count = 0;
while($fetch=mysql_fetch_array($query))
{
echo "<p>".$fetch['COMMENT']."X<br/><sub><b>Comment by: </b>".$fetch['COMMENT_BY']."</sub><hr /><p>";
$_SESSION[strval($count)]=$fetch['COMMENT'];
//echo $_SESSION[strval($count)];
$count = $count + 1;
print_r($_SESSION);
}
mysql_close();
delete_comment.php
<?php
session_start();
print_r($_SESSION);
error_reporting(E_ALL);
ini_set('display_errors', '1');
$count = $_GET['count'];
echo $count;
$comment = $_SESSION[strval($count)];
$db_sitename="genydb";
$db_hostname="localhost";
$db_username=
$db_password=
$con = mysqli_connect($db_hostname, $db_username, $db_password, $db_sitename);
echo $comment;
$myquery = sprintf("DELETE FROM COMMENTS WHERE COMMENT=%s", GetSQLValueString($_SESSION[$_GET['count']], 'text'));
$mysql=($myquery) or die(mysql_error());
mysqli_close($con);
?>
This is the error
Notice: Undefined offset: 0 in /var/www/geny/bootstrap/delete_comment.php on line 8
$comment = $_SESSION[strval($count)];
I believe it is because you are using a numeric key with $_SESSION. I tried it out locally and I got this notice on the first page:
Notice: Unknown: Skipping numeric key 0 in Unknown on line 0
I saw this bug report as well after getting that notice https://bugs.php.net/bug.php?id=42472
If you do something like this it doesn't raise the notice and it passes the variable properly:
$_SESSION['keyName'][strval($count)]=$fetch['COMMENT'];
Edit: Thanks to Wiseguy for turning me on to this bit of info.
His comment below is:
According to this answer, "keys in the $_SESSION array are subject to
the same limitations as regular variable names in PHP, i.e. they
cannot start with a number". I guess this was a side effect of
register_globals. Curiously, the docs no longer state this. Perhaps
this limitation was removed when the register_globals option was
removed in PHP 5.4.0
To elaborate on that a little bit the reason it didn't work with register_globals is because of how PHP treats super global variables such as $_SESSION. One of the things that makes a super global special is that it exists in all scopes without needing to use the 'global' keyword. The other thing is that it creates variables for all of the child elements automatically... again in all scopes. So if you have something like
$_SESSION['username'] = 'Levi';
That would create an additional variable $username which is equal to 'Levi'. So in the example above when you set a
$_SESSION[1] = 'Test';
PHP is going to try and set a variable $1 = 'Test'; Which is not possible

PHP undefined index error in communicating with android

I am retrieving data from a database in android so created a php file as below.
<?php
$db_host = "localhost";
$db_uid = "root";
$db_pass = "";
$db_name = "abc";
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$sql = "SELECT * FROM people WHERE birthyear > '". $_POST["birthyear"]."'";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
Now when i run it in the browser as localhost/script.php
error is thrown and the output is displayed as below
Notice: Undefined index: birthyear in C:\xampp\htdocs\jasonscript.php on line 14
[{"id":"1","name":"m","sex":"1","birthyear":"1989"},{"id":"2","name":"a","sex":"1","birthyear":"1986"},{"id":"3","name":"b","sex":"0","birthyear":"1986"}]
Please tell me how to correct my code.
$output[]=array("key"=>$row['field_name'],"key1"=>$row['field_name2']);
store array like this
You are directly inserting $_POST["birthyear"] in your query which makes you vulnerable to SQL injection. Stop doing it right now!
That is also why you get the error. When you directly call the script in your browser, that will be with a GET request and there wont be any POST variables available. So your $_POST array wont have a key for birthyear and thus it warns you about it.
You should start with something like
<?php
$by = isset($_POST["birthyear"]) ? $_POST["birthyear"] : "";
if (empty($by)) {
echo 'Invalid birthyear';
exit;
}
//SANITIZE YOUR BIRTHYEAR HERE
//in this case, probaly check for a integer between 1900 and 2100 or something.
//Although just an int could be enough to prevent injection
if (!is_int($by)) {
echo 'You failed to provide a valid year';
exit;
}
$sql = "SELECT * FROM people WHERE birthyear > '". $by."'";
//execute the code
?>
Although the above code is safe, you should check out bound parameters like used in mysqli prepared statements or PDO
you probably failed to send the values trough post properly.
try print_r($_POST); to see what you are actually sending
you still get all results because every year is > ''

$_Post problems [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
what is this notice referring to
can i get an answer in plain English please
i am new at this .. the better it is explained the fewer times i will need to repost
Notice: Undefined index: username in C:\wamp\www\espn.com\login.php on line 16
Notice: Undefined index: password in C:\wamp\www\espn.com\login.php on line 17
1<?php
2
3//Database Information
4
5 $dbhost = "localhost";
6 $dbname = "users";
7 $dbuser = "root";
8 $dbpass = "*****";
9
10 //Connect to database
11
12 mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
13 mysql_select_db($dbname) or die(mysql_error());
14
15 session_start();
****16 $username = $_POST['username'];
17 $password = md5($_POST['password']);****
18
19 $query = sprintf('SELECT * FROM users WHERE username="%s" AND password="%s"',
20 ($username), ($password));
21
22 $result = mysql_query($query);
23
if (mysql_num_rows($result) != 0) {
$error = "Bad Login";
include "login.html";
} else {
$_SESSION['username'] = "$username" ;
include "memberspage.php";
}
Sure. The form that is submitted does not have any name tag.
Please fix your html part as follow:
<input **name="username"**/>
So that you can easily use $_POST['username'] to recover the value from the form.
Actually every time you see "undefined index" it means that a key of an array is missing.
It's like:
$a = array('zero', 'one', 'two');
and you calling:
$a[3];
In this case $_POST is a global array which is missing the key 'username' and 'password'.
When you submit a page, the data (user input / form data) is sent as an array which you can access via $_POST.
Now, when you access $_POST[somename], the PHP engine tries to retrieve the value for the key "somename" in the array $_POST.
In your program (specifically lines 16 & 17), the key for the array does not exist.
So, it is better you do a check like this:
$username = isset($_POST['username'])?$_POST['username']:null;

Categories