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 6 years ago.
I know stackoverflow disapproves of repeat questions, but bear with me as I have scanned many similar questions without finding specific resolutions that will help me. (Mostly they mention things about avoiding database insertions)
I encounter these error messages:
here db connection success
Notice: Undefined variable: firstname in C:\xampp\htdocs\practice_connection_app\submit.php on line 10
Notice: Undefined variable: lastname in C:\xampp\htdocs\practice_connection_app\submit.php on line 10
Notice: Undefined variable: conn in C:\xampp\htdocs\practice_connection_app\submit.php on line 11
Fatal error: Call to a member function exec() on null in C:\xampp\htdocs\practice_connection_app\submit.php on line 11
The first result simply shows that I have connected to my database which I made using phpMyadmin.
Here is my relevant code (my html submission page which calls on a php action):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>student info</title>
</head>
<body>
<br>
Enter your first name and last name in the corresponding boxes.
<br>
<form action="submit.php" method="POST">
First: <input type="text" name="firstname"/>
<br>
Last: <input type="text" name="lastname"/>
<br>
<input type="submit">
</form>
</body>
</html>
the database connection (I think)
<?php
echo 'here';
$dsn = 'mysql:host=localhost;dbname=practice_students';
$username = 'test_usr';
$password = 'pa55word';
try {
$db = new PDO($dsn, $username, $password);
echo 'db connection success';
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
AND my php submit page
<?php
echo 'here ';
$dsn = 'mysql:host=localhost;dbname=practice_students';
try {
$db = new PDO($dsn);
echo 'db connection success';
$sql = "INSERT INTO people (firstname, lastname)
VALUES ('$firstname', '$lastname')";
$conn->exec($sql);
echo "Now we know your name! Hi," . " " . $firstname . " " . $lastname;
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
I understand that I may need to do some 'cleaning up' to avoid database insertions, but for now I would just like to know how I can ensure my submissions are going to the database and can be returned.
Thanks in advance!
Not sure which manual you ahve been reading to end up with that code....
You need to access your POST variables (using $_POST['firstname']) AFTER sanitizing them of course....
EDIT:
To access the POSTed variable, you can do the following:
$firstname = $_POST['firstname'];
But you really need some santization going on, you could use php's filter_var:
$firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
Though, you can do better than that, and be very strict in what you allow through your filters / sanitizers... Please go investigate this part after you get your code "working" :)
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 3 years ago.
I am trying to fetch the data from database for a an input field product code and i need to use its value to update the rest of the column values in the database but instead it is creating a different record and in the value field of the input box 'named' code, it shows and undefined variable error, please help.
HTML code:
<div class="small-8 columns">
<input type="text" id="right-label" placeholder="Product_code"
value="<?php echo "$pcode"?>" name="code">
</div>
PHP Script:
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="bolt";
try{
$conn = new
PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["submit"])){
$pcode = ($_POST["code"]);
$pname = ($_POST["Pname"]);
$pdesc = ($_POST["desc"]);
$pimg = $_FILES["Img_name"]["temp_name"];
$imgExt = strtolower(pathinfo($pimg,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg','jpg','png','gif','pdf');
$pqty = ($_POST["Pqty"]);
$pprice = ($_POST["Pprice"]);
$sql="UPDATE products SET product_name=$pname,product_desc=$pdesc,
product_img_name=$pimg,qty=$pqty,price
=$pprice) WHERE product_code=$pcode";
$stmt = $conn->exec($sql);
$stmt->execute();
echo $stmt->rowCount() . "new records added succesfully";
}
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
$sql is declared within the if condition, if if(isset($_POST["submit"])){
is false, you will get this error because $sql is not within the scope. Declare it on above condition and initialize it.
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 5 years ago.
My code:
$name=$_POST["name"];
This is the error
Notice: Undefined index: name in /home/u615903880/public_html/reg3.php
on line 4
code :
<?php
$con = new mysqli("xxxxx", "xxxx", "xxxx");
$name = $_POST["name"];
$username = $_POST["username"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO users (name, username, emailaddress, password)VALUES (?,?,?,?)");
mysqli_stmt_bind_param($statement, "ssss", $name, $username, $emailaddress, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
Error lines 4,5,6,9,10,14
Try
$name = isset($_POST['name']) ? $_POST['name'] : 'nothing provided';
You can put anything instead of 'nothing provided' like NULL or something
Its Notice not an error:
you can use
error_reporting(1);
on top of page this will hide warnings and notices.
or you can use code this way
if(isset($_POST["name"])){
$name=$_POST["name"];
}
You didn't send a POST variable called name. If it was from an HTML form, make sure the input is not disabled or it won't post. Also, make sure your form field has a name and not just an id, as it is the name that is used in a post request:
<input type="text" id="notused" name="used" />
In which case $_POST['used'] would work upon submission.
I suspect the key 'name' is not defined in the $_POST array.
to check for missing key you could use:
$name = $_POST["name"]??null; // PHP /7+
or
$name = isset($_POST["name"])?$_POST["name"]:null; // older
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 7 years ago.
I am trying to create a simple blog entry form where a user enters the title, blog entry and submits it. The form should then insert the 'blog entry' into MYSQL using the insert query.
I am getting NO errors.
When I submit form nothing is changed, the database has no new
entry and the form doesn't show "Post Submitted" or "Post Not
Submitted".
Here is the blog.php code
<?php
// 1. Establish a connection using three functions: 1. mysqli_connect() 2. mysqli_connect_errno() 3. mysqli_connect_error()
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "blog";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occured
if(mysqli_connect_errno()) {
die("Database connection failed " . mysqli_connect_error() . "( " . mysqli_connect_errno() . " )");
}
//Form submitted
if(isset($_POST['submit'])) {
//Error checking
if(!$_POST['title']) {
$error['title_error'] = "<p>Please supply a title.</p>\n";
}
if(!$_POST['blog']) {
$error['blog_error'] = "<p>Please supply blog content.</p>\n";
}
//No errors, process
if(!is_array($error)) {
//Process your form
// 2. Perform Your Query
$post_title = $POST["title"];
$post_content = $POST["blog"];
$query = "INSERT INTO entries (blog_id, blog_title, blog_content)
VALUES ('null', '{$post_title}', '{$post_content}')";
$result = mysqli_query($connection, $query);
//Display confirmation of post.
if($result) {
echo "Post submitted!";
} else {
echo "Error, post NOT submitted!";
}
//Require or include any page footer you might have
//here as well so the style of your page isn't broken.
//Then exit the script.
exit;
} else {
echo $error;
}
}
?>
<doctype>
<html>
<head>
<title> Blog </title>
</head>
<body>
<form method="POST" action="blog.php">
Title: <input name="title" type="text"> <br />
Blog: <textarea name="blog" cols="100" rows="5"> Blog Text here... </textarea> <br />
<input value="submit" type="submit" value="Submit" />
</form>
</body>
</html>
Here is a screen shot of the form AFTER submitting it.
Here is a screenshot of MYSQL database called blog, and table called entries:
Here is the structure of my database:
Does anybody know what I'm doing wrong. I am new to PHP and I have no idea how to debug a problem when I'm getting no errors!
UPDATE 1.
The solution worked. Thank you. However I getting the following error:
Notice: Undefined variable: error in C:\XAMPP\htdocs\blogwebsite\blog.php on line 30
I know it's because I have not initialized the $error[] array. But what is the standard way of getting rid of this error? Please help!
Your if(isset($_POST['submit'])) { condition will not set as true because you did not set a name tag for your submit button.
It should be
<input value="Submit" type="submit" name="submit"/>
Then on the re-assigning to another variable the passed-on data from the form, it should not be $POST["title"], it should be $_POST["title"].
You should also consider using mysqli_real_escape_string to prevent SQL injections.
$post_title = mysqli_real_escape_string($connection, $_POST["title"]);
$post_content = mysqli_real_escape_string($connection, $_POST["blog"]);
But still, you should use prepared statement rather than using mysqli_* with the functions of the deprecated mysql_* API.
Regarding the error you are getting for undefined variable, why don't you just scrap the input checking part of your code, and replace it with simply this:
if(!empty($_POST["title"]) || !empty($_POST["blog"])){ /* IF BOTH INPUTS HAVE CONTENTS */
/* THE CODE YOU WANT TO EXECUTE */
}
else {
$error = "<p>Please supply a title or a blog content.</p>\n";
}
Or just remove your input checking, and use HTML's required attribute.
<input name="title" type="text" required>
<textarea name="blog" cols="100" rows="5" required>
so that your PHP code will be straight-forward:
if(isset($_POST["submit"])){
/* YOUR INSERT QUERY HERE */
}
The cons of required, as well as the !empty() condition, is that it accepts empty space (). To bypass this, you should use Javascript or libraries that support this kind of stuff.
In your html form, the submit element has two "value" attributes but no "name" attribute. Therefore it is not being found in the if(isset($_POST['submit'])) check and the original form being displayed as if nothing was posted.
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 7 years ago.
I getting this kind of error message, any idea what is wrong with the code on line 9? Basically, the code is to search the user input from the form, then search the username from ldap.
PHP Notice: Undefined index: username in C:\inetpub\wwwroot\LDAP\New3\search2.php on line 9
<?php
$ds = #ldap_connect("ldap.xxxxx.my");
if (!$ds) {
die("Unable to connect to test server.");
}
$res = #ldap_bind($ds); # Anonymous bind
$userid = $_POST['username']; // User key their userid or email
$srch = #ldap_search($ds,
"o=company, o=CompanyNet",
"uid=$userid", # Search on username
array('uid'), # We want username
0, # We want values and types (see docs)
10 # We want, at most, 10 results
);
if (ldap_errno($ds) == 4) { # Error code for "too many results"
print "<B>More than 10 results were returned. Only 10 displayed.</B><BR>\n";
}
if ($srch) {
$results = #ldap_get_entries($ds, $srch); # Retrieve all results
for ($i = 0; $i < $results["count"]; $i++) { # Iterate over all results
print "<B>".$results[$i]["uid"][0]."</B> exist in directory "."<BR>\n";
}
}
else {
print "<B>Directory lookup failed: ".ldap_error($ds)."</B><BR>\n";
}
#ldap_close($ds); # Close off my connection
?>
<html>
<head>
</head>
<body>
<form action="search.php" method="POST">
<input type="text" name="username" length="30">
<input type="submit" name="submit" value = "Search">
</form>
</body>
</html>
You're getting the error because you're expecting the $_POST array to be set whenever you load the page.
That is not the case. It will only ever be set when the form is submitted, so you can handle that by adding this if condition:
if(isset($_POST['submit'])) {
$ds = #ldap_connect("ldap.xxxxx.my");
if (!$ds) {
die("Unable to connect to test server.");
}
$res = #ldap_bind($ds); # Anonymous bind
$userid = (!empty($_POST['username'])) ? $_POST['username'] : ''; // User key their userid or email
// ... the rest of your code
}
As Fred stated in the comments, you might want to make sure that username is not empty, by using php's inbuilt function - empty()
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.
I am having issues when trying to insert ("username" as i use as an example) into my mysql db.. anyways, as soon as I update the site, I get the "success" message I set, if it worked as it should and a blank row is inserted into my db. However, it also works the normal way when typing something into the textbox (after I got the "success" message) and press submit, it's also getting inserted into the db. But my issue is this first blank insert that shouldn't be there, I have no further idea how to solve that one atm :/
I also get a notice in the top of the site, saying "Undefined index: username", I have no idea what I've done wrong :/
Here's my code btw:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "pw";
$dbname = "dbname";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
$user = $_POST["username"];
$sql = "INSERT INTO account (username) VALUES ('$user')";
if($conn->query($sql) === true) {
echo "Success!";
} else {
echo "Error: " . $sql . "<br />" . $conn->error;
}
$conn->close();
?>
<form method="POST" action="">
<input type="text" name="username" placeholder="Username" /><br /><br />
<input type="submit" name="submit" value="Go" />
</form>
Thx in adv. :)
1) You are vulnerable to sql injection attacks. Enjoy having your server pwn3d.
2) Your code runs unconditionally, EVERY TIME the page is loaded. Therefore when a user first hits the page, you run your code. Since no form has been submitted, $_POST['username'] is undefined and you end up inserting an empty string into the DB.
At bare minimum you should have something like
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... db code here ...
}
so that it only runs when a POST was performed.