This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
Here i'm going to do a insert to the MySQL.but here i'm getting error.I saw there's a duplicated for the same but in those answers they asked to add ISSET.In my coding i added that also but still i'm getting this error.
Error 1 : Notice: Undefined index: Description in ....... add.php on line 8
Error 2 : Notice: Undefined variable: _FILE in ..........\add.php on line 9
Error 3 : Fatal error: Call to undefined function NOW() in ....add.php on line 12
Here i added my Coding below
<html>
<body>
<?php
include('config.php');
if(isset($_POST['submit']))
{
$Title=$_POST['Title'];
$Description=$_POST['Description'];
$Image = addslashes(file_get_contents($_FILE['Image']));
$Categories = $_POST['category'];
$ModifiedBy = 1;
$ModifiedDate = NOW();
$query1=mysql_query("insert into testdb values('','$Title','$Description','$Image','$Categories','$ModifiedBy',$ModifiedDate,1)");
if($query1)
{
header("location:list.php");
}
}
?>
<fieldset style="width:300px;">
<form method="post" action="" enctype="multipart/form-data">
Title: <input type="text" name="Title"><br>
Description: <input type="text" name="description"><br>
Image : <input type="file" name="Image" /><br>
<select name="category" id="category">
<option>Choose</option>
<option value="1">new</option>
<option value="2">info</option>
<option value="2">Event</option>
<br>
<input type="submit" name="submit">
</form>
</fieldset>
</body>
</html>
You have grammar issues in your code. It should be this:
$Title=$_POST['Title'];
$Description=$_POST['description'];
$Image = addslashes(file_get_contents($_FILES['Image']));
$Categories = $_POST['category'];
$ModifiedBy = 1;
$ModifiedDate = 'NOW()';
$query1=mysql_query("insert into testdb values('','$Title','$Description','$Image','$Categories','$ModifiedBy',$ModifiedDate,1)");
Error 1: Case of "description" is wrong!
Error 2: it should be $_FILES (add an S). Also that is not how you handle file uploads -
[read more here][1]
Error 3: NOW() is a mysql tag. not php. you can use date() if you want this in php.
$_FILE should probably be $_FILES, just a typo there. The linked page will give you a bit more information about how to post files using PHP.
The NOW() function is for mysql, not PHP. You can use php's date format to emulate the way MySQL saves dates instead:
date("Y-m-d H:i:s")
For the Description error, that's to do with casing. Description != description. Try and be consistent with casing where you can, that often helps when looking for errors. Also, space your code out a little and make use of indentation.
When in doubt over an error, I usually check what line I get the error on. If it's one I've not encountered before, try a search and see if something similar comes up. #John Conde's link in his comment is a great place to start
Related
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 8 years ago.
When I say 'new', I mean that this is just about the first time I'm attempting php.
Anyway. I keep getting this error notice "Undefined index: type in c:\x\calculator.php on line 33", but it still echoes "You forgot to pick mathtype!" and the calculator works fine. This error notice occurs only when I don't select any radio box for math type (+-/*).
//Part of the form
<form action="calculator.php" method="post">
<input type="text" name="1stnumber">
<input type="text" name="2ndnumber">
<input type="radio" name="type" value="addition">
<input type="radio" name="type" value="subtraction">
<input type="submit" name="send">
<?php
//My variables
$number = $_POST['1stnumber']
$numbero = $_POST['2ndnumber']
$mathtype = $_POST['type'] /* **<-line 33** */
//The calculation part of the form here, which is working
//Tell the user if he didn't pick a math type (+-)
if(is_null($mathtype)){
echo "You forgot to pick mathtype!"
}
?>
Tried with elseif as well.. I don't see what's wrong between line 33 and the if(is_null()) line!
Sorry if it looks poor, messy, or if something doesn't make sense. Might be a few typos as well. Any help is appreciated.
Simply check if type is posted before you pick it up
if(isset($_POST['type']))
{
$mathtype = $_POST['type'];
}
else
{
echo "Type was not selected";
}
Set a default selected option, using the checked attribute.
<label><input type="radio" name="type" value="addition" checked="checked"> +</label>
<label><input type="radio" name="type" value="subtraction"> -</label>
Don't forget inputs needs labels in html if left out you can use a placeholder attribute, but that's clearly not possible with type="radio"; therefore wrap the input in a label with the text description next to it eg + or -
Also, is this a copy and paste error, bc all php statements must be terminated with a semicolon ;
$number = $_POST['1stnumber']; // <- terminate
$numbero = $_POST['2ndnumber']; // <- terminate
$mathtype = $_POST['type']; // <- terminate
echo "You forgot to pick mathtype!"; // <- terminate
It's always good practice to check if the variable you're trying to retrieve from $_POST has actually been set, try this:
<?php
//My variables
if (isset($_POST['1stnumber'])) {
$number = $_POST['1stnumber'];
}
if (isset($_POST['2ndnumber'])) {
$numbero = $_POST['2ndnumber'];
}
if (isset($_POST['type'])) {
$mathtype = $_POST['type']; /* **<-line 33** */
}
//The calculation part of the form here, which is working
//Tell the user if he didn't pick a math type (+-)
if (is_null($mathtype)) {
echo "You forgot to pick mathtype!";
}
?>
Check if the form is posted:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//My variables
$number = $_POST['1stnumber']
$numbero = $_POST['2ndnumber']
$mathtype = $_POST['type'] /* **<-line 33** */
//The calculation part of the form here, which is working
//Tell the user if he didn't pick a math type (+-)
if(is_null($mathtype)){
echo "You forgot to pick mathtype!"
}
}
?>
Else the is_null check will also be executed on the first load (before the form has been posted).
I wrote a simple php script that basically echos the values put into a form on the page, later, I will have this write to a DB but I was working on troubleshooting it before I did that since I keep getting this warning.
Does anyone know why I am getting it? If I just fill in the fields and submit the form, the script works fine and the warning disappears.
PHP Function:
function quickEntry()
{
$subTitle = $_POST['subTitle'];
$subDetails = $_POST['details']; //This is line 13 in my code
echo "$subTitle";
echo "<br>$subDetails";
}
HTML / PHP Code:
<form method="post" action="">
<hr>
<h1>Quick Entry:<p></h1>
Subject Title:<br> <input type="text" name="subTitle"><br><br>
Subject Details: <p><textarea name="details" placeholder="Enter Details here..."></textarea><p><br>
<input type="submit" name="QuickEntrySubmit" value="Submit Quick Entry" /><br>
</form>
<?php
if (isset($_POST['QuickEntrySubmit']))
{
quickEntry();
}
?>
I know that I could disable warnings and I wouldn't see this, but I really just want to know why php is throwing the warning so I can fix the syntax appropriately and keep my code clean going forward. Full warning is:
Notice: Undefined index: details in C:\xampp\htdocs\test1.php on line 13
Thanks!
The reason why you are getting that error is because you are not checking whether the 'subTitle' and 'details' inputs have values in them.
Your code should work well like this:
function quickEntry(){
$subTitle = isset($_POST['subTitle'])? $_POST['subTitle']: null;
$subDetails = isset($_POST['details'])? $_POST['details']: null ; //This is line 13 in my code
if(!is_null($subTitle) && !is_null($subDetails)){
echo "$subTitle";
echo "<br>$subDetails";
} else{
//blah blah blah
}
You get the warnings because the $_POST variables with the indexes that you're checking for ($_POST['subTitle'] & $_POST['details']) aren't set, so the variables are empty as you reference something that isn't there.
You should do a check to ensure they are set first before trying to assign them to a variable:
$subTitle = (isset($_POST['subTitle']) && !empty($_POST['subTitle'])) ? $_POST['subTitle'] : null;
$subDetails = (isset($_POST['details']) && !empty($_POST['details'])) ? $_POST['details'] : null;
The above code will check to ensure the post index isset() and isn't empty() before assigning it to the variables.
NOTE
The variables are set when you submit the form because you are actually posting the data to the script.
You see the input attribute name? When you submit the form, they are the relevant $_POST indexes.
Just remember to ensure that the values aren't empty if you intend to print them to the markup.
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
$name = $_REQUEST['fname'];//Notice is coming at this line
echo $name;
?>
</body>
</html>
The above code shows Notice like this:-
Notice: Undefined index: fname in C:\xampp\htdocs\Programs\request.php on line 10
How to remove this error? I took this code from w3schools.com.
It is running fine in w3schools.com site. In my PC also it runs but when I open this program in my browser, it shows the above line.
Plz help me..
it gives this notice when $_REQUEST['fname'] is not set.
Change:
$name = $_REQUEST['fname'];//Notice is coming at this line
to:
$name = isset($_REQUEST['fname']) ? $_REQUEST['fname'] : "";
you need to check that if it is set or not by isset()
PHP gives notice when variable are not defined like in your case $_REQUEST['fname'] is not set/defined.
Change to:
$name = isset($_REQUEST['fname']) ? $_REQUEST['fname'] : "";//better way
OR you can do
$name = #$_REQUEST['fname'];//this way notice or warnings are suppressed
I have a simple code to add banners from admin panel to the index of the site. But the add function doesnt work correctly here is the form to add banner
<h2>Add Banner</h2>
<?php include ("../engine/config/config.php"); ?>
<form method="post" action="">
Clicks
<input type="text" name="click" value="0" style="width: 200px;" /> <div class="hr"></div>
Impressions
<input type="text" name="imp" value="0" style="width: 200px;" /> <div class="hr"></div>
LINK
<input type="text" name="url" value="http://" style="width: 200px;" /> <div class="hr"></div>
Size
<select name="razmer">
<option value='468x60'>468x60</option>
<option value='88x31'>88x31</option>
</select>
<div class="hr"></div>
Banner<br />
<input type="text" name="picurl" value="http://" style="width: 200px;" /><div class="hr"></div>
<input type="submit" name="submit" value="Submit"> <br />
</form>
<?
if($_POST['submit']) {
$click = $_POST['click'];
$imp = $_POST['imp'];
$url = $_POST['url'];
$razmer = $_POST['razmer'];
$picurl = $_POST['picurl'];
$sql = "INSERT INTO `banneradd` (click, imp, url, razmer, picurl, username) VALUES ('$click', '$imp', '$url', '$razmer', '$picurl', '')";
$result = mysql_query($sql);
echo "<div class='hr'>The Banner has been added, please go back to the index: <a href='view_reklama.php'> Index </a></div>";
}
?>
So it say it was added but when I go back ITS NOT. There is no error or anything, can someone help? Thanks in advance :)
Okay, there are way too many things wrong with your code, so if you're learning from a particular site or person... find a different source.
Don't open PHP with <?. This is the shorthand style. It is disabled on many if not most web servers, and for good reason -- because XML introduces its encoding using the same opening <? and it causes conflict. Always open your PHP with <?php. http://www.php.net/manual/en/ini.core.php#ini.short-open-tag
Don't use if($_POST['submit']), use if (isset($_POST['submit'])). Your current script should generate an error, but it's probably being masked because PHP defaults to not showing very many errors. It does trigger a warning, though, because you're checking if the variable (or rather array value) $_POST['submit'] is equal to true. In fact, that variable is undefined. Use isset() to check if a variable exists. http://php.net/manual/en/function.isset.php
Sanitize your user's input. If somebody typed a ' into any of your fields, your query would break. Why? Because in your query, you're placing your stringed values in single quotes, and any instance of another single quotation mark would break out of that. There is such a thing as magic quotes in PHP (which automatically escapes POST values), but it's absolutely awful, so please disable it. http://php.net/manual/en/security.magicquotes.php The best way to escape user input is with real escape functions (more on that later).
mysql_ functions are deprecated. Use PDO or MySQLi. If you're getting used to the mysql_ functions, it is easier to transition to MySQLi. For simplicity, I'll use the procedural style, but it's much better to go with the OOP style....
If you want to debug MySQL commands with PHP, you should format your queries carefully, print the error, and also print the computed query, because sometimes you need to look at the actual resulted query in order to see what is wrong with it.
That said, here's what I suggest:
<?php
error_reporting(E_ALL);
// Turn on all error reporting. Honestly, do this every time you write a script,
// or, better yet, change the PHP configuration.
$connection = mysqli_connect('host', 'username', 'password', 'database');
// Somewhere in your config file, I assume you're calling mysql_connect.
// This is a pretty similar syntax, although you won't need mysql_select_db.
if (isset($_POST['submit'])) {
$click = mysqli_real_escape_string($connection, $_POST['click']);
// This will escape the contents of $_POST['click'], e.g.
// if the user inputted: Hello, 'world'! then this will produce:
// Hello, \'world\'!
$imp = mysqli_real_escape_string($connection, $_POST['imp']);
$url = mysqli_real_escape_string($connection, $_POST['url']);
$razmer = mysqli_real_escape_string($connection, $_POST['razmer']);
$picurl = mysqli_real_escape_string($connection, $_POST['picurl']);
$query = "
INSERT INTO `banneradd` (
`click`,
`imp`,
`url`,
`razmer`,
`picurl`,
`username`
)
VALUES
(
'$click',
'$imp',
'$url',
'$razmer',
'$picurl',
''
);
";
// Format your query nicely on multiple lines. MySQL will tell you what line
// the error occurred on, but it's not helpful if everything's on the same line.
$result = mysqli_query($connection, $query);
$error = mysqli_error($connection);
if ($error) {
echo "A MySQL error occurred: $error<br>";
echo "<pre>$query</pre>";
// If an error occurred, print the error and the original query
// so you can have a good look at it.
die;
// Stop executing the PHP.
}
echo '<div class="hr">The Banner has been added, please go back to the index: Index </div>';
}
?>
See if that helps. Chances are, the MySQL error will be helpful with diagnosing the problem. You might have just misspelled a column name or table name.
Now before we begin let me inform you all that this is just a school assignment and that I am not overly an expert in php and sql coding.
I have the problem, whenever I execute the script, I receive the following error:
Notice: Undefined variable: Team in
C:\xampp\htdocs\NFL\searchmatches.php on line 30.
From my understanding, there would be a spelling error in the link up between the script and the form file, but I can't seem to find the problem.
This is a file to search the database:
Script:
<?php
mysql_connect("localhost","root","0gd1d0wgpg") or die(mysql_error());
mysql_select_db("NFL") or die(mysql_error());
$query=mysql_query("SELECT * FROM Matches where Team ='$Team'") or die(mysql_error());
$numfields = mysql_num_fields($query);
print("<table border=\"1\">\n<tr>\n");
for ($i=0; $i<$numfields; $i++) {
printf("<th>%s</th>\n", mysql_field_name($query,$i));
}
print("</tr>\n");
while ($row = mysql_fetch_row($query)) {
print("<tr>\n");
for ($i=0; $i<sizeof($row); $i++) {
printf("<td>%s</td>\n", $row[$i]);
}
print("</tr>\n");
}
print("</table>\n");
?>
Form:
<form name="addmatch" method="post" action="searchmatches.php">
Search for the match history of a particular team here.<br>
<br>
Team Name: <input type="text" name="Team_Name" value="Team Name">
<br>
<br>
<input type="submit" value="Search">
</form>
Yes there is more coding in the actual files but I figured that, the PHP would be all you needed to help me.
So could somebody please tell me how rid of this error and make the search work.
PHP uses a special "super global" to give you access to submitted form values. The $_POST superglobal is an array with keys that match the name attribute of the form elements (when the form is submitted with the "post" method). Add this line:
$Team = mysql_real_escape_string($_POST['Team_Name']);
above the use of $Team in the query.
To recap, the 'Team_Name' identifier comes from your HTML:
<input type="text" name="Team_Name" value="Team Name">
and then when the form is submitted, whatever you put in that form control is available at $_POST['Team_Name']. I passed the value through the "escape" function so to protect your query from going bonkers (or worse) if that value happened to contain special characters.