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.
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 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" :)
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.
My form won't save in my db
connect code saved as con_mysql.php:
<?php
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PSWD', '*****');
DEFINE ('DB_NAME', 'lexusdb');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
form code:
<form method="post" action="newep.php">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Content:</legend>
<label>Name: <input type="text" name="newcontent" /></label>
</fieldset>
<br />
<input type="submit" value="add new anime" />
</form>
<?php
echo $newrecord
?>
PHP:
<?php
if (isset($_POST['submit'])) {
include('con_mysql.php');
$nanime = $_POST['newcontent'];
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$newcontent')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('Error inserting new record');
}
$newrecord = "1 anime added";
}
?>
at first it just won't save anything in DB using the form, and now it also have Undefined variable: newrecord
all files saved in the same folder and newep.php is also created. my db consist of table named title, inside title have title_id INT(4) not null auto_increment then title_name VARCHAR(255) not null. I hope you guys can help me with this one as you guys have help me by just searching for what i need THANKS
Edit :
There is few things that your code is missing , but its ok , you still learning and its great way to start , learning from the faults is good .
One of the things and its one of the most important things that you missed is that you have to prevent SQL Injection in your code , even if you code was perfect but you query has that issue then you are in troubles , How can you protect your Query ? by this way : SQL INJECTION
Second , i see you using MYSQLI , which is a good relational database driver, but i prefer you start to use PDO . Whats PDO ?
PDO is an acronym for PHP Data Objects. PDO is a lean, consistent way
to access databases. This means developers can write portable code
much easier. PDO is not an abstraction layer like PearDB. PDO is a
more like a data access layer which uses a unified API (Application
Programming Interface).
Its easy and simple . What's the differenet between PDO and MYSQLI ?
Different between MYSQLI and PDO
Third thing and i will take that from one of the comments by Fred , You need to start using Error reporting , read this :
Errors Reports
Now to the code .
In your code you tried to echo a variable from the form before you receive the data from the form ( before the submit happen ) , so you should first send the data and receive it then do whatever you want with it .
In your code :
<?php
echo $newrecord
?>
The right way as you can see it here :
if (isset($_POST['submit']))
{
include_once('con_mysql.php');
$nanime = $_POST['newcontent'];
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$nanime')";
if (!mysqli_query($dbcon, $sqlinsert))
{
die('Error inserting new record');
}
else
{
$newrecord = "1 anime added";
echo $newrecord;
}
}
I hope that my answer helped you , and remember the first part cause its so important .
Here is the full code .
<html>
<head>
</head>
<body>
<form method="post" action="">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Content:</legend>
<label>Name:
<input type="text" name="newcontent" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new anime" />
</form>
<?php
if (isset($_POST['submit']))
{
include_once('con_mysql.php');
$nanime = $_POST['newcontent'];
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$nanime')";
if (!mysqli_query($dbcon, $sqlinsert))
{
die('Error inserting new record');
}
else
{
$newrecord = "1 anime added";
echo $newrecord;
}
}
?>
</body>
</html>
It looks like you have a typo when including the file which opens connection. Instead of:
include('con_mysql.php.php');
I guess it should be:
include('con_mysql.php');
The next thing is checking your $_POST. Only fields with a name would be there, so you need to change your condition from:
if (isset($_POST['submit'])) {
to:
if (!empty($_POST)) {
and finally you are using an uninitialized variable in your query,
so change that line:
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$newcontent')";
to
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$nanime')";
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.
this is probably a very simple question to solve, however I've been stuck with this for a while and I can't figure out for the life of me what's wrong with my code. It may be just a syntax mistake but I've gathered this code from other questions and it should work but I keep getting the errors : - Undefined variable : mysqli and - Call to a member function query() of a non-object , both in the line "$result = $mysqli->query($sql);".
Here's the snippet of my code where I have the dropdown menu set up.
<label class="control-label" for="formInput85">Professor</label>
<?php
$sql = "SELECT name FROM professores";
$result = $mysqli->query($sql);
echo "<select class=".'"form-control"'.">";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
And here's my code in the very beginning of the page, that is connecting to my database in phpmyadmin.
<?php
session_start();
echo $_SESSION['name'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "teste";
$conn = new mysqli($servername,$username,$password,$dbname);
?>
Thank you for your help! If you have any tips on how to send the value selected into another row of the table I gladly appreciate it as it will be my next step :)
$mysqli is not the right variable in this case. So this line:
$result = $mysqli->query($sql);
has to become
$result = $conn->query($sql);
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.