I have 3 files.
1st one :
<html>
<form action="employeeDel.php" method ="post">
Enter Ssn To Delete Employee:<br>
<input type="number" name="ssnDel">
<br>
<br>
<input type="submit" value="Submit">
</form>
</html>
This form sends data to employeeDel.php.
employeeDel.php :
<html>
<form action ="employeeDelFinal.php" method="post">
<input type="hidden" name="ssn" value="ssnDel">
<?php
$ssnDel = $_POST ["ssnDel"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = mysqli_connect ( $servername, $username, $password, $dbname );
// Check connection
if (! $conn) {
die ( "Connection failed: " . mysqli_connect_error () );
}
$sql = "SELECT * from employee WHERE ssn=".$ssnDel;
<input type="submit" name="Delete?">
</form>
</html>
From here, when user clicks on submit button, I want html form to send ssnDel value to employeeDelFinal.php file.
employeeDelFinal.php :
<?php
$ssnDel = $_POST ["ssn"];
echo ssnDel;
?>
That value never reaches here. I got an error on employeeDel.php file, it says value of ssnDel is null. I guess in the beginning of form in employeeDel file, I create ssnDel again, so it becomes null.
Is there a way to send a data from html form to employeeDel.php, from employeeDel.php to employeeDelFinal.php by using form? I tried hidden text but it didn't solve my problem as seen.
The line
<input type="hidden" name="ssn" value="ssnDel">
should be something like
<input type="hidden" name="ssn" value="<?php echo(intval($_POST['ssnDel'])); ?>">
(Assuming that ssnDel is an ID-Number.)
Otherwise that hidden variable will have the string-value ssnDel, not the value of the variable $_POST['ssnDel'].
And as already mentioned, echo ssnDel; should be echo $ssnDel; and you should use less spaces (e.g. no spaces after $_POST or function names).
There are couple of things I noticed. You have
employeeDelFinal.php :
<?php
$ssnDel = $_POST ["ssn"];
echo ssnDel;
?>
You don't have a dollar sign in your echo statement ssnDel.
And why do you have spaces in between $_POST ["ssnDel"] make it
$_POST["ssnDel"]
Related
I am working on a html form which will connect to a database using a php script to add records.
I have it currently working however when I submit the form and the record is added , the page navigates to a blank php script whereas I would prefer if it when submitted , a message appears to notify the user the record is added but the page remains the same. My code is below if anyone could advise me how to make this change.
Html Form :
<html>
<form class="form" id="form1" action="test.php" method="POST">
<p>Name:
<input type="Name" name="Name" placeholder="Name">
</p>
<p>Age:
<input type="Number" name="Age" placeholder="Age">
</p>
<p>Address
<input type="text" name="Address" placeholder="Address">
</p>
<p>City
<input type="text" name="City" placeholder="City">
</p>
</form>
<button form="form1" type="submit">Create Profile</button>
</html>
PHP Database Connection Code :
<html>
<?php
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx",
"Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values
('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
</html>
Typically your action file would be something like thankyou.php where you'd put whatever message to the user and then maybe call back some data that was submitted over. Example:
Thank you, [NAME] for your oder of [ITEM]. We will ship this out to you very soon.
Or this file can be the the same page that your form resides on and you can still show a thank you message with some javascript if your page is HTML. Something like:
<form class="form" id="form1" action="test.php" method="POST onSubmit="alert('Thank you for your order.');" >
I am taking into consideration that your PHP Database Connection Code snipplet that you posted above is called test.php because you have both connecting to the data base and inserting data into the database in one file.
Taking that into consideration, I think the only line you are missing, to return you back to to top snipplet of code that I shall call index.php would be an include statement just after the data has been added to the database
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values ('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
echo "Data added";
include 'index.php'; //This file is whatever had the earlier form
Once you hit the submit button on your form, test.php is called, your data is handled and passed back to index.php.
N.B:
The other thing i should mention is to make it a habit of using mysqli_real_escape_string() method to clean the data that is in the $_POST[]; because in a real website, if you don't, you give an attacker the chance to carry out SQL injection on your website :)
you said page is coming blank and data is saved so i assumed that there are two files one which contains form and another which contains php code (test.php).
when you submit the form you noticed that form is submitted on test.php
and your test.php has no any output code that's why you are seeing blank page.
so make a page thankyou.php and redirect on it when data is saved.header('Location: thankyou.php'); at the end of file.
Put this in form action instead of test.php
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Put your php code at top of the page.
$Name = $_POST['Name'];
This is step closer to being a safer way to posting into your db as well.
$Name =mysqli_real_escape_string( $_POST['Name']);
I like the jscript Alert from svsdnb to tell user data was successfully added to db.
This is not intended to be an out of the box solution; it's just to get you pointed in the right direction. This is completely untested and off the top of my head.
Although you certainly could do a redirect back to the html form after the php page does the database insert, you would see a redraw of the page and the form values would be cleared.
The standard way to do what you're asking uses AJAX to submit the data behind the scenes, and then use the server's reply to add a message to the HTML DOM.
Using JQuery to handle the javascript stuff, the solution would look something like this:
HTML form
<html>
<!-- placeholder for success or failure message -->
<div id="ajax-message"></div>
<form class="form" id="form1">
<p>Name: <input type="Name" name="Name" placeholder="Name"></p>
<p>Age: <input type="Number" name="Age" placeholder="Age"></p>
<p>Address: <input type="text" name="Address" placeholder="Address"></p>
<p>City: <input type="text" name="City" placeholder="City"></p>
<!-- change button type from submit to button so that form does not submit. -->
<button id="create-button" type="button">Create Profile</button>
</form>
<!-- include jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- ajax stuff -->
<script>
// wait until DOM loaded
$(document).ready(function() {
// monitor button's onclick event
$('#create-button').on('click',function() {
// submit form
$.ajax({
url: "test.php",
data: $('#form1').serialize,
success: function(response) {
$('#ajax-message').html(response);
}
});
});
});
</script>
</html>
test.php
<?php
// note: never output anything above the <?php tag. you may want to set headers.
// especially in this case, it would be better to output as JSON, but I'm showing you the lazy way.
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx", "Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
// if mssql needs the non-standard brackets, then put them back in...
// note placeholders to get benefit of prepared statements.
$query = "INSERT INTO SalesLT.Test " .
"(Name,Age,Address,City) Values " .
"(?,?,?,?)";
$params1 = array($Name,$Age,$Address,$City);
$success = false;
if($result = sqlsrv_query($conn,$query,$params1)) {
$success = true;
}
sqlsrv_close($conn);
// normally would use json, but html is sufficient here
// done with php logic; now output html
if($success): ?>
<div>Form submitted!</div>
<?php else: ?>
<div>Error: form not submitted</div>
<?php endif; ?>
I have some PHP and HTML code which should send data from the form to my MySQL database. However, on clicking Submit in the form, the page reloads and nothing happens. No echo or anything. The HTML is in the same file as the PHP file.
PHP
<?php
if(isset($_POST['submit'])){
$usernamep = $_POST['usernameinput'];
$passwordp = $_POST['passwordinput'];
$servername = "localhost";
$username = "USERNAMECENSOR";
$password = "PASSWORDCENSOR";
$dbname = "database";
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 accounts (username, password)
VALUES ('$usernamep', '$passwordp')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Success";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
HTML
<form method="POST" action="">
<input type="text" name="usernameinput"><br>
<input type="password" name="passwordinput"><br>
<input type="submit" class="button" value="Sign in">
</form>
Note: I know this code is currently subject to SQL injection, and the password is not encrypted. It is temporary starting code in an attempt to get it working first.
You lack the name attribute in the submit button, add name="submit".
<form method="POST" action="">
<input type="text" name="usernameinput"><br>
<input type="password" name="passwordinput"><br>
<input type="submit" name="submit" class="button" value="Sign in">
</form>
Your test is wrong. You have no input named "submit" (with attribute name = submit). It should be:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
...
}
A broad test like this will not even need a named submit. The HTML form may even be posted on another event using jQuery or JavaScript.
In your PHP file, you use isset($_POST['submit']). You don't have any form input with name="submit". You could make your submit button be
<input type="submit" name="submit" class="button" value="Sign in">
You have to include your php file into the action of the form tag.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="usernameinput"><br>
<input type="password" name="passwordinput"><br>
<input type="submit" class="button" value="Sign in">
</form>
a form is posted to db only once, i have to delete the row in db for the form to post new form data again. I tried several modifications from internet but didnt allowed me to post after the first successful time
Form:
<form action="post.php" method="POST">
<h5>A form:</h5>
<input class="right-inputs" id="field1" type="number" name="field1" placeholder="Enter stuff">
<input class="right-inputs" id="field2" type="text" name="field2" value="" readonly>
<script src="js/insert.js"></script>
<button class="btn-cmn" type="submit" name="submit">post</button>
</form>
post.php:
<?php
include_once 'db.php';
$var1 = $_POST['field1'];
$var2 = $_POST['field2'];
$sql = "INSERT INTO `a_table` (column1, column2) VALUES ('$var1', '$var2')";
mysqli_query($conn, $sql);
mysqli_close($conn);
header("Location: page.php?post=success");
?>
db.php:
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "database_sample";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
?>
your table structure look like :
I think You have Primary Key in your table that not automatic generate value. So you can't add more row while have same Primary key..
Make sure you generate unique key for primary or have auto increment number for this.
I think issues in your database to put error_reporting(E_ALL); in your php page in top section then after try to insert so get some error view in your code.
I am starting to learn the basics of SQL and PHP codes.
I am trying to create a simple newsletter subscription page. this would require the user to enter their email and submit. That will then get added to my database.
Now, this works well when the HTML and PHP code are separate and the submission occurs but redirects to the PHP page with the echo.
I want to get the message on the same page and I tried merging the PHP code in the page as below
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
mysql_connect("hostname", "username", "password");
mysql_select_db("db name");
$user = $_POST['email'];
$query = "INSERT INTO tablename(columname)VALUES('$email')";
echo "inserted";
}
?>
<html>
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
</html>
Hoever with this code it just doesnt do anything.
What have am I doing wrong here? Appreciate your expert advice.
There are few mistakes in the code, you can fix them by doing the following:
Save the file as a php file first. For example name it "email.php".
Make the form action="email.php"
Don't write two complete separate codes in the same file, one for php file and the other for html file like you did. You can include the html code inside the php code using heredoc syntax which allows you to include a long html code like the following:
echo<<<_HTMLCODE
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
_HTMLCODE;
In the query syntax, add $user instead $email because the variable $user contains the value submitted by the form.
Add a code to excute the inserted query. for example:
mysql_query($query);
So your final code will be like this:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
mysql_connect("hostname", "username", "password");
mysql_select_db("db name");
$user = $_POST['email'];
$query = "INSERT INTO tablename VALUES('$user')";
mysql_query($query);
echo "inserted";
}
echo<<<_HTMLCODE
<form method="POST" action="email.php" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
_HTMLCODE;
?>
I have tried the code above after I added the data of my database on the localhost and after I created a table for the emails and it worked. Here is the edited code with my database access info and the table name in my code editor:
When i opened the table emails in my database, I found the email that I had submitted using the form (your modified code):
(advice: use mysqli instead of mysql)
Please use prepare statements to prevent Sql Injections.
Here is sample code try this.
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli ("localhost", "root", "usbw", "test");
if (mysqli_connect_errno()) {
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
if (isset($_POST['submit'])) {
$email = filter_input(FILTER_VALIDATE_EMAIL, $_POST['email']);
$sql = "INSERT INTO table (email) VALUES (?)";
$stmt = $connect->prepare($sql);
$stmt->bind_param('s', $email);
$result = $stmt->execute();
if ($result) {
$msg = 'Succesfully added';
} else {
$msg = 'OOPS Error Occured';
}
}
?>
<html>
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
</html>
I have just started learning PHP and I am facing this issue when using $_SERVER["PHP_SELF"] to redirect to the same page after user clicks Submit in the form. The problem are the $_POST[] variables I have used in my PHP script in the page, which I need to access AFTER user clicks Submit and the page reloads. But on the first run, when the the user hasn't clicked Submit, the $_POST variables are empty and I am getting errors displayed on the page itself. Of course, there are no errors after the user click Submit and page reloads. I don't want to redirect to another page after Submit. How do I circumvent these errors on the first run?
Is there a better approach for what I am trying to do?
The code for my page is here:
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h3> Welcome!</h3>
</br></br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
First Name: <input type="text" name="fname"> </br></br>
Last Name: <input type="text" name="lname"> </br></br>
Age: <input type="number" name="sage"> </br></br>
<input type="submit" value="Submit"></br></br>
</form>
<?php
$servername = "localhost";
$username = "user1";
$password = "abcd123";
$dbname = "myDbFromPhp";
$fname = $_POST["fname"]; /*Lines responsible for the errors, I think*/
$lname = $_POST["lname"];
$sage = $_POST["sage"];
if($fname != "" and $lname != "") /*Checking for empty vars*/
{
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error)
{
die("Connection failed: ".$conn->connect_error);
}
echo "<h4>Connected successfully</h4>";
$sql = "INSERT INTO Students
(fname, lname, sage)
VALUES
('".$fname."','".$lname."',".(string)$sage.");" ;
if($conn->query($sql) === TRUE)
{
echo "<h4>Value entered successfully</h4>";
}
else
{
echo "</br>Error creating record</br>".$conn->error;
}
$conn->close();
}
?>
</body>
</html>
The page simply takes some input from the user (Student: first name, last name, age), and when user clicks Submit, reloads and saves them to a database.
First time of page load post value not exists so use isset to check that like this
<input type="submit" name="submit" value="Submit"></br></br>
if(isset($_POST['submit']))
{
//all of your db insertion related codes all here
$fname = $_POST["fname"]; /*Lines responsible for the errors, I think*/
$lname = $_POST["lname"];
$sage = $_POST["sage"];
......................
......................
header('Location:samepage.php');
// redirect the page to avoid the duplicate insertion by pressing F5 or reload .
}
your code looks sql injection attack . try to use prepared statement or PDO
In your first loading, that variable does not have values, therefore php genarate a error, therefore you can use isset() to check whether data assigned or not
if(isset($_POST["fname"])){
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$sage = $_POST["sage"];
}
you can do all functionalities inside the if(isset($_POST["fname"])){ }