In my script SQL, row empty in the database - php

I am trying to pinpoint the problem in these form scripts.
I would like to create a line in the SQL server with the data that will be inserted into the HTML form, but each time only the empty line is created without also inserting the form inputs.
HTML
<form action="insert2.php" method="post">
<label for="First_name">First_name:</label>
<input type="text" name="First_name" id="First_name">
<label for="PASSWORD">PASSWORD:</label>
<input type="text" name=value name="pass" id="pass">
<label for="Emailaddress">Emailaddress:</label>
<input type="text" name=value name="email" id="email">
<input name="submit" type="submit" value="Submit">
</form>
PHP
<?php
if(isset($_POST['submit'])){
$First_name = $_REQUEST['First_name'];
$pass = $_REQUEST['password'];
$email = $_REQUEST['Emailaddress'];
}
$servername = "host";
$username = "user";
$password = "";
$dbname = "dbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(First_name, PASSWORD, Emailaddress)
VALUES ('$First_name', '$pass', '$email')";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

The posted values should be set as $_POST['ExampleField'] not just a variable with that name.
Ex: $First_name should be $_POST['First_name']
If you look in your error logs you are likely getting undefined variable errors with the code as it is now, because $First_name, $PASSWORD and $Emailaddress are never defined.
Also you should avoid directly putting variables into queries like that, it opens you up to large security risks. I would recommend reading up on SQL Injection (https://www.w3schools.com/sql/sql_injection.asp) and binding parameters (https://www.php.net/manual/en/pdostatement.bindparam.php) to see how to avoid those risks.

You need to retrieve the values after a submit of some sort. You have a submit button but you'll want to give it a name (I named it submit). This code should work but you'll be vulnerable to injection attacks.
PHP
<?php
if(isset($_POST['submit'])){
$First_name = $_REQUEST['First_name'];
$pass = $_REQUEST['PASSWORD'];
$email = $_REQUEST['Emailaddress'];
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(First_name, PASSWORD, Emailaddress)
VALUES('$First_name','$pass','$email')";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
HTML
<form action="insert2.php" method="post">
<label for="First_name">First_name:</label>
<input type="text" name="First_name" id="First_name">
<label for="PASSWORD">PASSWORD:</label>
<input type="text" name="PASSWORD" id="PASSWORD">
<label for="Emailaddress">Emailaddress:</label>
<input type="text" name="Emailaddress" id="Emailaddress">
<input name="submit" type="submit" value="Submit">
</form>

Related

Can't get PHP to process form data into MySQL database [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
I'm trying to process some HTML form data into a MySQL database using some PHP, but this is my first foray into webdev and I think I'm in over my head. The form is POSTed to the formSubmit.php file, which turns them into the variables that the sql command then queries. I've tried changing round the variable layout, but it still won't send for some reason.
The HTML form:
<form class="middleForm" name="pizzaGuest" action="formSubmit.php" method="POST">
<fieldset>
<legend>Guest details</legend>
First name:<br>
<input type="text" name="firstName" required><br>
Last name:<br>
<input type="text" name="lastName" required><br>
Email address:<br>
<input type="email" name="email" required><br>
Party date:<br>
<input type="date" name="date" required><br>
Diet:<br>
<select name="diet">
<option value="omnivore" selected>Omnivore</option>
<option value="pescatarian">Pescatarian</option>
<option value="vegetarian">Vegetarian</option>
<option value="vegan">Vegan</option>
</select><br>
Dairy free?<br>
<input type="checkbox" name="dairyFree"><br>
Toppings:<br>
<input type="text" name="toppings"><br>
Allergies:<br>
<input type="text" name="allergies"><br>
<input type="submit" value="Submit">
</fieldset>
</form>
formSubmit.php:
<?php
$servername = "localhost";
$username = "partyForm";
$password = "████████████";
$dbname = "pizza";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$FirstName = $_POST["firstName"];
$LastName = $_POST["lastName"];
$Diet = $_POST["diet"];
$Allergies = $_POST["allergies"];
$Email = $_POST["email"];
$DairyFree = $_POST["dairyFree"];
$sql = "REPLACE INTO guests (FirstName, LastName, Diet, Allergies, Email, DairyFree) VALUES ($FirstName, $LastName, $Diet, $Allergies, $Email, $DairyFree);";
mysql_query($sql)
mysqli_close($conn);
?>
You might try using prepared statements instead as they proect against sql injection and avoid the need to add quotes as your sql omits.
<?php
$servername = "localhost";
$username = "partyForm";
$password = "xxx";
$dbname = "pizza";
$conn = new mysqli( $servername, $username, $password, $dbname );
if( !$conn ) die("Connection failed");
$sql = "replace into guests ( `firstname`, `lastname`, `diet`, `allergies`, `email`, `dairyfree` ) values (?,?,?,?,?,?);";
$stmt=$conn->prepare($sql);
$stmt->bind_param('ssssss',$_POST["firstName"], $_POST["lastName"], $_POST["diet"], $_POST["allergies"], $_POST["email"], $_POST["dairyFree"] );
$stmt->execute();
$stmt->close();
$conn->close();
?>
For a best usage and confort, check the PDO driver for MySQL instead of mysql. With this method, you can perform prepared statements easily.
The connection with this driver will be:
$dbh = null;
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
print "Erreur !: " . $e->getMessage() . "<br/>";
die();
}
$stmt = $dbh->prepare("REPLACE INTO guests (FirstName, LastName, Diet, Allergies, Email, DairyFree) VALUES (:FirstName, :LastName, :Diet, :Allergies, :Email, :DairyFree);");
$stmt->bindParam(':FirstName', $FirstName);
$stmt->bindParam(':LastName', $LastName);
$stmt->bindParam(':Diet', $Diet);
$stmt->bindParam(':Allergies', $Allergies);
$stmt->bindParam(':Email', $Email);
$stmt->bindParam(':DairyFree', $DairyFree);
$stmt->execute();
// Close the connection at the end of your queries
$dbh->close();
$dbh = null;
This the best approach to secure your code and minimize the risk go SQL injections.

Insert into sql table with php from html form

I am trying to insert into my table (courses) in my sql database. But when I run my code (by clicking submit) I get this error:
I am no longer getting an error, I get the message:
New course created successfully
But when I check the database, the course has not been added
This is my code:
<?php
if (isset($_POST['submit'])) {
try {
require "../config.php";
require "../common.php";
$connection = new PDO($dsn, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO course (courseName, cDescription, programID, programYear, credit)
VALUES (:courseName, :cDescription, :programID, :programYear, :credit)";
$courseName = $_POST['courseName'];
$cDescription = $_POST['cDescription'];
$programID = $_POST['programID'];
$programYear = $_POST['programYear'];
$credit = $_POST['credit'];
$statement = $connection->prepare($sql);
$statement->bindParam(':courseName', $courseName, PDO::PARAM_STR);
$statement->bindParam(':cDescription', $cDescription, PDO::PARAM_STR);
$statement->bindParam(':programID', $programID, PDO::PARAM_STR);
$statement->bindParam(':programYear', $programYear, PDO::PARAM_STR);
$statement->bindParam(':credit', $credit, PDO::PARAM_STR);
$connection->exec($statement);
echo "New course created successfully";
} catch(PDOException $error) {
echo $statement. "<br>" . $error->getMessage();
}
}
?>
<?php include "templates/header.php"; ?>
<h2>Add a course</h2>
<form method="post">
<label for="courseName">Course Name:</label>
<input type="text" name="courseName" id="courseName" required>
<label for="cDescription">Course Description:</label>
<input type="text" name="cDescription" id="cDescription" size="40" required>
<label for="programID">Program ID:</label>
<input type="number" name="programID" id="programID" required>
<label for="programYear">Program Year:</label>
<input type="number" name="programYear" id="programYear" required>
<label for="credit">credit:</label>
<input type="number" name="credit" id="credit" required>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
To try and see what was wrong, I tried simplifying this to, which works
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "courseselector";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO course (courseName, cDescription, programID, programYear, credit)
VALUES ('courseName', 'cDescription', 1, 4, 1)";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<?php include "templates/header.php"; ?>
<h2>Add a course</h2>
<form method="post">
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
I was missing
$statement->execute();
Above
$connection->exec($statement);

PHP code saying input is empty but it's not?

I'm having a problem with my php code, it seems that it returns "Password Should Not Be empty" when I do input a password. I think it might be coming from my html code because I make them input it twice. Do I need to make another variable in my database for confirm password?
<?php
$firstname = filter_input(INPUT_POST, 'firstname');
$lastname = filter_input(INPUT_POST, 'lastname');
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST, 'password');
if (!empty($firstname)) {
if (!empty($lastname)) {
if (!empty($email)) {
if (!empty($password)) {
$host = "127.0.0.1:3307";
$dbusername = "root";
$dbpassword = "";
$dbname = "register";
// Create connection
$conn = new mysqli($host, $dbfirstname, $dblastname, $dbemail,
$dbpassword);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
} else {
$sql = "INSERT INTO Signup (firstname, lastname, email, password) values ('$firstname','$lastname','email','password')";
if ($conn->query($sql)) {
echo "New record is inserted sucessfully";
} else {
echo "Error: " . $sql . "" . $conn->error;
}
$conn->close();
}
} else {
echo "Password should not be empty";
die();
}
}
}
} else {
echo "Username should not be empty";
die();
}
Your error is because your post value is $_POST['psw'], while your code is expecting $_POST['password']. Either change your HTML form, or your PHP code so that the values are the same.
Your code is very confusing. I made it a little simpler, try this and see if you still get the same error:
# Check to see if you're getting the right variables in the first place:
var_dump($_POST); //Remove once you're sure you're getting the right stuff
if(!$firstname = filter_input(INPUT_POST, 'firstname')){
die("First name should not be empty");
}
if(!$lastname = filter_input(INPUT_POST, 'lastname')){
die("Last name should not be empty");
}
if(!$email = filter_input(INPUT_POST, 'email')){
die("Email should not be empty");
}
if(!$password = filter_input(INPUT_POST, 'password')){
die("Password should not be empty");
}
$host = "127.0.0.1:3307";
$dbusername = "root";
$dbpassword = "";
$dbname = "register";
$conn = new mysqli($host, $dbfirstname, $dblastname, $dbemail, $dbpassword);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$sql = "INSERT INTO Signup (firstname, lastname, email, password) values ('$firstname','$lastname','email','password')";
if (!$conn->query($sql)) {
echo "Error: " . $sql . "\r\n" . $conn->error;
$conn->close();
exit;
}
echo "New record is inserted successfully";
General guidelines
Don't nest if() statements. It makes following code very confusing.
If a boolean outcome is a deal breaker, have that outcome first in the if/else statement. For instance if the SQL query fails, have the negative outcome first in the if() statement (which will stop your code), and skip the else statement all together.
Comment your code.
<form method="post" action="overstack.php">
<div class="container">
<br>
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstname"><b>First Name</b></label>
<input type="text" placeholder="Enter First Name" name="firstname" required>
<label for="lastname"><b>Last Name</b></label>
<input type="text" placeholder="Enter Last Name" name="lastname" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
this is my html form for the php code above

How do you trigger the next record in the PHP array via the HTML submit button?

Goal: I want to create an HTML form that displays pre-populated information from the 22 arrays from array_file.php.
First, I will go on index.php. On index.php, I will see a form with pre-populated data. I will not be able to edit the first and last name fields, but I will be able to edit the email field (if necessary).
Second, once everything looks okay, I will click the "Submit" button.
Third, if nothing is wrong (i.e., email field is populated), the "Submit" button should take me to the second record in the array.
Finally, once it has looped through all the arrays, it will provide a message, such as, "You're done!"
Current problem: My current index.php page shows all 22 pre-populated forms on one page. While I can edit and submit to the database using the individual "Submit" button, I'd rather be able to look at each pre-populated form one at a time.
Here is the code:
<?php
ob_start();
include 'array_file.php';
ob_end_clean();
?>
<?php
$i=1;
while ($i<=22){
?>
<form action="index.php" method="post">
<h2>Form</h2>
<label>First Name:</label>
<input class="input" name="first_name" type="text" value="<?php echo htmlentities($array[$i][1]) ?>" disabled><br>
<label>Last Name:</label>
<input class="input" name="last_name" type="text" value="<?php echo htmlentities($array[$i][2]) ?>" disabled><br>
<label>Email:</label>
<input class="input" name="email" type="text" value="<?php echo htmlentities($array[$i][3]) ?>"><br><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
<?php
$i=$i+1;
}
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = mysqli_real_escape_string($conn,$_POST['email']);
if($email !=''){
//Insert Query of SQL
mysqli_query(#conn,"INSERT into form(form_first_name, form_last_name, form_email) values ('$first_name', '$last_name', '$email')");
echo "<br/><br/><span>Data inserted successfully!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some required fields are blank!</p>";
}
}
$mysqli->close(); // Closing Connection with Server
?>
Let me know if you need me to provide any more information. Thank you in advance!
I hope this code is what you need.
<?php
ob_start();
include 'array_file.php';
ob_end_clean();
if(isset($_POST['submit']) and isset($_POST[email])){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = mysqli_real_escape_string($conn,$_POST['email']);
if($email !=''){
//Insert Query of SQL
mysqli_query(#conn,"INSERT into form(form_first_name, form_last_name, form_email) values ('$first_name', '$last_name', '$email')");
echo "<br/><br/><span>Data inserted successfully!</span>";
}
}
/// find which form will be published
if( isset($_SESSION["form"]) and $_SESSION["form"]<22){
$form=$_SESSION["form"]+1;
$_SESSION["form"]=$form;
}else{
$form=1;
$_SESSION["form"]=$form;
}
// determine which is the next form number
if($form<22){ $nextForm=$form+1; }else{ $nextForm="??"; }
<!-- form area !-->
<form action="index.php?form=<?php echo $nextForm; ?>" method="post">
<h2>Form</h2>
<label>First Name:</label>
<input class="input" name="first_name" type="text" value="<?php echo htmlentities($array[$form][1]) ?>" disabled><br>
<label>Last Name:</label>
<input class="input" name="last_name" type="text" value="<?php echo htmlentities($array[$form][2]) ?>" disabled><br>
<label>Email:</label>
<input class="input" name="email" type="text" value="<?php echo htmlentities($array[$form][3]) ?>"><br><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>

How Do I populate my table in SQL with input from the user? PHP

Just starting out with PHP. I have code that gets user input through a form and enters the input into a mySQL table. The code has no parse errors. But when a user submits their name and email. It is not going into the table, the table is still empty, and I cannot seem to figure out the problem. Here is my code:
<div id="main">
<h1>Insert data into database using PDO</h1>
<div id="login">
<h2>Students Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="name" id="Fname" required="required" placeholder="Please Enter Your Name"/><br/><br/>
<label>Student Email :</label>
<input type="text" name="email" id="email" required="required" placeholder="Pear#gmsil.com"/><br/><br/>
<input type="submit" value=" Submit " name="submit"/><br/>
</form>
</div>
</div>
<?php
//server name
$db_hostname = "lll";
//database name
$db_database = "lll";
//username
$db_username = "lll";
$db_password = "lll;";
$db_charset = "utf8mb4";
//a string specifying the database type, the hostname and name of the database
$dsn = "mysql:host=$db_hostname;dbname=$db_database;charset=$db_charset";
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE =>PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
);
try {
//create connection
$pdo = new PDO($dsn,$db_username,$db_password,$opt);
if (isset($_POST["submit"])) {
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO students (name,email)";
VALUES ('". $_POST["name"] ."','" . $_POST["email"] . "');
if ($pdo->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Student Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
in the line of code where you write the SQL statement, you placed an extra "; before the second half of the query.
Change
$sql = "INSERT INTO students (name,email)";
VALUES ('". $_POST["name"] ."','" . $_POST["email"] . "');
to
$sql = "INSERT INTO students (name,email) VALUES ('". $_POST["name"] ."','" . $_POST["email"] . "');
This should fix the problem with your failed inserts.

Categories