php does not send correct stuff to mysql - php

Hi guys I am learning PHP and the code below sends information to my MySQL database but it does not match with the data i just gave him to insert, for example it inserts 1|blank|blank for the code below. I canĀ“t solve it :
insert.php file:
<?php
$con=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Person (PID,Name, Age)
VALUES ('1','$firstname', '$age')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added to database";
mysqli_close($con);
?>
It keeps me saying this:
Notice: Undefined index: firstname in E:\XAMPP\htdocs\Bioinformatics\insert.php on line 11
Notice: Undefined index: age in E:\XAMPP\htdocs\Bioinformatics\insert.php on line 12
code for html form:
<!DOCTYPE html>
<html>
<body>
<form name="input" action="insert.PHP" method="get">
First name: <input type="text" name="FirstName" value="Ronaldo"><br>
Age: <input type="text" name="Age" value="28"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Thanks for any help guys!

It looks like you have forgotten to post the needed data.
$_POST['firstname'] and $_POST['age'] are not defined in your html.
You are missing the following inputs or have misspelled them:
<input type="text" name="firstname" />
<input type="text" name="age" />

cause you have not values for $_POST['firstname'] and $_POST['age'] try to check it's have values or not.
if(!empty($_POST['Firstname'])) {
$firstname = mysqli_real_escape_string($con, $_POST['Firstname']);
}
else {
echo 'firstname empty';
}
if(!empty($_POST['Age'])) {
$age= mysqli_real_escape_string($con, $_POST['Age']);
}
else {
echo 'age empty';
}
also same for age
For check post values try print_r($_POST); on this page

change
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
to
$firstname = $_POST['firstname'] ? mysqli_real_escape_string($con, $_POST['firstname']) : "";
$age = $_POST['age'] ? mysqli_real_escape_string($con, $_POST['age']) : "";

echo "<pre>";print_r($_REQUEST);exit; // to check values in all variable.
Place your php code below html code to get rid of undefined index notices or use isset() function eg. if(isset($_POST['age'])) or initialize those variables with null value. like $age = "";
also see answer by #karlingen

Related

How do I fix this undefined array key? [duplicate]

This question already has answers here:
Checking if form has been submitted - PHP
(9 answers)
Closed 1 year ago.
This is the error currently show. Below The first code I save as details.php and the second on as details.html
Warning: Undefined array key "first_name" in C:\xampp\htdocs\children_math\detail2.php on line 12
Warning: Undefined array key "last_name" in C:\xampp\htdocs\children_math\detail2.php on line 13
Warning: Undefined array key "email" in C:\xampp\htdocs\children_math\detail2.php on line 14
Warning: Undefined array key "age" in C:\xampp\htdocs\children_math\detail2.php on line 15
ERROR: Could not able to execute INSERT INTO details (first_name, last_name, email, age) VALUES ('', '', '', ''). Cannot add or update a child row: a foreign key constraint fails (record.details, CONSTRAINT details_ibfk_1 FOREIGN KEY (id) REFERENCES users (id))
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "record");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']);
$last_name = mysqli_real_escape_string($link, $_REQUEST['last_name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$age = mysqli_real_escape_string($link, $_REQUEST['age']);
// Attempt insert query execution
$sql = "INSERT INTO details (first_name, last_name, email, age) VALUES ('$first_name', '$last_name', '$email', '$age')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="detail2.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<p>
<label for="ages">Email Address:</label>
<input type="text" name="age" id="ages">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>```
i had a similar problem; i solved it by checking the file referenced in the error and the line. In your case its details2.php.In my case that error was triggered because the variable names $variable_name = $_POST['key_value']; were initialized outside my if(isset($_POST['Register'])) block. All i did was include it immediately after my if(condition)block like so;
if (isset($_POST['Register'])) {
// receive all input values from the form
$name = mysqli_real_escape_string($conn, $_POST['name']);
$Username = mysqli_real_escape_string($conn, $_POST['username']);
$phone_number = mysqli_real_escape_string($conn, $_POST['phone_number']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$Church = mysqli_real_escape_string($conn, $_POST['church']);
$Password1 = mysqli_real_escape_string($conn, $_POST['password']); //encrypt password
$Password2 = mysqli_real_escape_string($conn, $_POST['passwordConf']);
$token = bin2hex(random_bytes(50)); // generate unique token
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($_POST['name'])) {
$errors['name'] = 'Name required';
}
....
Ensure that your form has the method attribute set to post
<form action="your_page.php" method="post">
<label for="email">Email :</label>
<input type="text" id="email" name="emailInput"><br><br>
</form>
At your_page.php, you can get the value by $email = $_POST['emailInput'];
The string(emailInput) inside the $_POST['emailInput']; is the name of your input tag.

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

Added database rows are empty mysql/php

I want to write from my form to my database. I'm confused because this resembles the scripts from tutorials and there it works.
Form (w3schools example) extract:
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
php:
<?php
$con=mysqli_connect("localhost","XXX","AAA","databasename");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$age = mysqli_real_escape_string($_POST['age']);
$sql="INSERT INTO test (firstname, lastname, age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
This adds a new row to my database with each submission. The problem: this added row is empty, except for the age column which is always 0, regardless of what I submit.
Where is my mistake?
Refer to php document you must give two values to mysqli_real_escape_string.
try this:
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);

Undefined index form error

i read all answer about undefined index error but not help full for me because i'm already using isset function to check plz how to slove this problem..
<?php
$con=mysqli_connect("localhost","root","","contact");
if (mysqli_connect_errno())
{
echo "failed".mysqli_connect_error();
}
checking for submited data
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$website=$_POST['website'];
$gender=$_POST['gender'];
$comment=$_POST['comment'];
}
$sql="insert into form(name,website,gender,comment) Values('$_POST[name]','$_POST[website]','$_POST[gender]','$_POST[comment]')";
if(!mysqli_query($con,$sql))
{
die('error:'.mysqli_error($con));
}
else "added";
mysqli_close($con);
?>
<html>
<body>
<form method=post action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Website: <input type="text" name="website"><br>
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<input type=submit name="submit"><br>
</form>
</body>
these errors comes
Notice: Undefined index: name in H:\Wamp\Xamp\htdocs\form.php on line 15
Notice: Undefined index: website in H:\Wamp\Xamp\htdocs\form.php on line 15
Notice: Undefined index: gender in H:\Wamp\Xamp\htdocs\form.php on line 15
Notice: Undefined index: comment in H:\Wamp\Xamp\htdocs\form.php on line 15
Please try the following corrected code :
if(isset($_POST['submit']))
{
$name=isset($_POST['name']) ? $_POST['name'] : '';
$website=isset($_POST['website']) ? $_POST['website'] : '';
$gender=isset($_POST['gender']) ? $_POST['gender'] : '';
$comment=isset($_POST['comment']) ? $_POST['comment'] : '';
$sql="insert into form(name,website,gender,comment) Values('$name','$website','$gender','$comment')";
// Open the database connection here
// aka, mysqli_connect()
if(!mysqli_query($con,$sql))
{
die('error:'.mysqli_error($con));
}
else "added";
mysqli_close($con);
}
?>
<html>
<body>
<form method=post action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Website: <input type="text" name="website"><br>
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<input type=submit name="submit"><br>
</form>
</body>
What I did is added validation to check if those fields are set, and if so, then set the value, if not, then set the variable (aka $name) to ''. You should probably add some further validation in the event of required fields being = '' (equal to blank).
I also adjusted your query to not use the $_POST vars, instead it uses the variables that you are assigning the $_POST values to, so you know they exist for sure.
And lastly, I moved the mysql connection code and query itself into the if(isset(submit)) statement so it does not try to process those on regular page load where the form has not been submitted yet.
Update this insert query,
$sql="insert into form(name,website,gender,comment) values('". $name ."','". $website ."','". $gender ."','". $comment ."')";
Hope this help you!
Change
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$website=$_POST['website'];
$gender=$_POST['gender'];
$comment=$_POST['comment'];
}
$sql="insert into form(name,website,gender,comment) Values('$_POST[name]','$_POST[website]','$_POST[gender]','$_POST[comment]')";
if(!mysqli_query($con,$sql))
{
die('error:'.mysqli_error($con));
}
else "added";
mysqli_close($con);
?>
to
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$website=$_POST['website'];
$gender=$_POST['gender'];
$comment=$_POST['comment'];
$sql="insert into form(name,website,gender,comment) values ('$name','$website','$gender','$comment')";
if(!mysqli_query($con,$sql))
{
die('error:'.mysqli_error($con));
}
else "added";
mysqli_close($con);
}?>
than friends problem is slove
What wrong?
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$website=$_POST['website'];
$gender=$_POST['gender'];
$comment=$_POST['comment'];
$sql="insert into form(name,website,gender,comment) Values('". $name . "','" . $website . "','" . $gender . "','" . $comment . "')";
//these also in if(isset()) Block
if(!mysqli_query($con,$sql))
{
die('error:'.mysqli_error($con));
}
else "added";
}
thanx to all

PHP code does not update database, no sql error and my IDE is returning no errors, however the database is not updating

I'm sorry to ask such a narrow question, but I have this code in PHP and it is supposed to update a user's account. There is no error being returned and my IDE cannot identify the problem either. The problem is now that the code is not updating the database. I hope I can get some help on the subject.
Here is my PHP code:
<?php
session_start();
$con = mysqli_connect("mysql.serversfree.com", "u190182631_embo", "17011998embo", "u190182631_login");
$username = $_POST['user_name'];
$last = $_POST['lname'];
$first = $_POST['fname'];
$address = $_POST['address'];
$email = $_POST['email'];
$year = $_POST['year'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE users SET last_name = '$last'
WHERE user_name = $_SESSION[user_name]");
mysqli_close($con);
}
?>
Any my HTML form if that is needed:
<form method="post" action="update.php">
Username: <input type="text" name="user_name" value="<?php echo $_SESSION['user_name']?>"><br><br>
Email: <input type="text" name="email" value="<?php echo $_SESSION['user_email']?>"><br><br>
Last Name: <input type="text" name="lname" value="<?php echo $_SESSION['last_name']?>"><br><br>
First Name: <input type="text" name="fname" value="<?php echo $_SESSION['first_name']?>"><br><br>
Street Address: <input type="text" name="address" value="<?php echo $_SESSION['address']?>"><br><br>
Year Graduated: <input type="text" name="year" value="<?php echo $_SESSION['year']?>"><br><br>
<input type="submit" value="Update Information"><br>
</form>
<form method="link" action="manage.php">
<input type = "submit" value = "Cancel"><br>
</form>
Any help would be great!
Try this - it will also help against SQL injection attacks:
$db = new mysqli("mysql.serversfree.com", "u190182631_embo", "17011998embo", "u190182631_login");
$username = $_POST['user_name'];
$last = $_POST['lname'];
$first = $_POST['fname'];
$address = $_POST['address'];
$email = $_POST['email'];
$year = $_POST['year'];
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = $db->prepare("UPDATE users SET last_name = ? AND WHERE user_name = ?;");
$stmt->bind_param("ss", $last, $_SESSION['user_name']);
$stmt->execute();
$stmt->close();
}
The big problem here is that you don't know how to debug the problem yourself, nor what information to include in a request for help.
There is no error being returned
How do you know? you don't check for any error from the query. Consider:
$upd="UPDATE users SET last_name = '$last'
WHERE user_name = $_SESSION[user_name]";
if (!mysqli_query($con,$upd)) {
print "query failed: $upd \n\n<br />" . mysqli_error();
}
You've shown a fragment of the code used to generate the form - but not what actually got sent to to the browser,
As Fred -ii- says, it seems very strange that $_SESSION[user_name] is not quoted in your SQL.
try this
mysqli_query($con,"UPDATE users SET last_name = '$last' WHERE user_name = {$_SESSION['user_name']}");
Update this line of code:
mysqli_query($con,"UPDATE users SET last_name = '$last'
WHERE user_name = $_SESSION[user_name]");
with the new one:
mysqli_query($con,"UPDATE users SET last_name = '$last'
WHERE user_name = $_SESSION['user_name']");
Hope it will work!

Categories