I am sorry if this is a repeating question, but I can't find anyone who might have the same question as me yet. I am new in html and php, and I am trying to learn more by practising, basically creating a registration form and keep all the data in the MySQL database, by using xampp. I have created a registration form and saved it as a .html file format, but how can I use php to send the user input from html to the MySQL database? I have seen a lot of examples on Google, but most of them are using php file format, for example instead of registration.html, they use registration.php. I really do appreciate your help. Thank you very much StackOverflow community members.
P/S: I use Visual Studio Code to do this
Step 1: write this code in your html file
in form action redirect it to the php file
<!DOCTYPE html>
<html>
<head>
<title>form</title>
</head>
<body>
<form method="post" action="st.php">
<input type="text" name="text">
<input type="submit" name="submit_btn">
</form>
</body>
</html>
Step 2 create st.php file and call the action
<?php
if(isset($_POST['submit_btn'])){
//your code
header('Location:yourHTMLFile.html?status=success');//redirect to your html with status
}
?>
An example to insert some data in to the MySQL database using PHP
1. Create a Index.php page in a new folder(“764”) created under public_html folder present in your home directory
To use a PHP script on your web page, you just need to end the file name with .php and make sure the permissions on the file are set correctly. Any files to be accessed by the web server must be publically readable, but none of your PHP files (nor the directory containing them) may be group or publically writable. Following are the commands you can use for setting the permissions in linux:
chmod 755 public_html
chmod 644 public_html/764/index.php
The PHP page will have two simple text boxes for the user to enter some data in to it. Label them to be Firstname and Lastname.
INDEX.PHP
<html>
<body>
<h1>A small example page to insert some data in to the MySQL database using PHP</h1>
<form action="insert.php" method="post">
Firstname: <input type="text" name="fname" /><br><br>
Lastname: <input type="text" name="lname" /><br><br>
<input type="submit" />
</form>
</body>
</html>
We also need to make sure that the form method attribute is “post” so as to access the data being entered in a reliable way in the next page being directed “insert.php” so that the data being entered in the textboxes can then be saved to the database in the “insert.php” page.
To connect to MySQL :-
Before you can access your MySQL database, you must contact the system administrators to request an account.
Once the administrators have notified you that your account has been created, you may connect using the following instructions.
Go to http://localhost/phpmyadmin and type your MySQL ID and password being given.
Now enter the new table name “nametable” , number of fields in that table as “2” and hit GO button.
Enter the field names to be “firstname” and “lastname” and keep the length attributes to be “20” for both the fields. The default type of VARCHAR is kept as it is.
After the table fields are being created, the following screen will be shown to you.
Now we need to make a connection to the MySQL database and then send this entered data from our textboxes. For that we create a new PHP page “insert.php” and use the following connection strings to the connection variable $con
After making a connection, a SQL query is being written to enter this data in to the MySQL database being created (“nametable”)
To tell the user that the data is being entered we set the echo to "1 record added"
INSERT.PHP
<html>
<body>
<?php
$con = mysql_connect("localhost","cis_id","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cis_id", $con);
$sql="INSERT INTO nametable (fname, lname)
VALUES
('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
</body>
</html>
Now type the index page URL in your browser and enter some data in to the textboxes. Submit the Query.
For browsing the data, you need to click on Database: cis_id on top of the page (http://localhost/phpmyadmin) to get to the database tables page. Then click on the browse button as shown below, beside the “nametable” which you have already created to browse through the entered data.
the data being entered in to the MySQL database table being created.
Here is the reference.
http://people.cs.ksu.edu/~hankley/d764/tut06/GopisettyPHP.html
Note: Please write questions in proper way and internet is everything to get whatever you want. Hope you will search first and when you are helpless, post question with piece of code. Then only we can help in this forum.
Related
I have a web based, php, DB system using mysql. users login, enter data in forms, click submit, and data is entered and can be read, analyzed, reported on, etc etc etc.
now we have a data provider who wants to send data to the mysql DB via a link, an external submission to the DB from a source not logged in to the system
"The most common way of how we get data over to our clients is by posting over our data to your system. In order to do this I would need a URL to post the data to as well as the
required fields names."
I am not exactly sure what this means.
http://mysite.com/data.php?first_name=bob&last_name=smith // ??
how do i set up, in the above example, data.php, so the data provider can input via the link and not have to post into a form?
Typically, i have an html form like this, on a page we'll call form1.php:
<html><body>
<form method="POST" NAME="form1" action="data.php">
<input type='text' name='first_name'>
<input type='text' name='last_name'>
<input type=submit value="Submit">
</form>
</body></html>
data.php looks like this:
<?
include("dbinfo.inc.php"); // has the access info for the DB, how to connect
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$query = "INSERT INTO table1 (first_name, last_name) VALUES ('$first_name','$last_name')";
mysql_query($query);
mysql_close();
?>
<html>
<head>
<meta HTTP-EQUIV="REFRESH" content="0; url=form1.php">
</head>
</html>
But in this example, the user would have to log in and post to the form. what is the way for the user to generate a link with the pertinent data, and have it submit via data.php not from a form, but directly from a link?
TIA
The GET method sends the data into the link. Your for should look like this:
<form method="GET" NAME="form1" action="data.php">
<input type='text' name='first_name'>
<input type='text' name='last_name'>
<input type=submit value="Submit">
</form>
This will send the browser, for example, to http://mysite.com/data.php?first_name=bob&last_name=smith
In PHP you can take these variables using $lastname=$_GET['last_name'];
So you have to change only the method you take the data from the form in your data.php:
<?
include("dbinfo.inc.php"); // has the access info for the DB, how to connect
$first_name = mysql_real_escape_string($_GET['first_name']);
$last_name = mysql_real_escape_string($_GET['last_name']);
$query = "INSERT INTO table1 (first_name, last_name) VALUES ('$first_name','$last_name')";
mysql_query($query);
mysql_close();
?>
<html>
<head>
<meta HTTP-EQUIV="REFRESH" content="0; url=form1.php">
</head>
</html>
Some help: http://www.w3schools.com/tags/ref_httpmethods.asp
You could learn about the webservices and REST to do it.
To persist given data, you should do it via a POST request instead of GET request (or PUT if it's an update).
The client will only use your URI and make a POST or PUT request to persist or update datas, and make a GET request to get datas and DELETE to remove datas.
Sorry I have posted this question and I googled it alot still Im unable to solve this
I have a php page that has a form and when user clicks refresh or F5 it creates duplicate values in the database and also a message is alerted to the user, indicating resubmitting may insert duplicate values in database.My boss dont want that alert box of the browser to user and also insertion of duplicate values into the database
I know its header(). I read lot of header() in php manual and also server_name functions but still I tried in many ways putting in the top but cant solve it. its very important. can anyone please help me with a sample of code explaining the way to do.any help is greatly appreciated.
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
</form>
demo.php
<?php
$firstname = $_POST['fname'];
?>
Tell me what should i add in the demo.php page to stop it from submitting the form again and again and also if user clicks back button on the browser it should not direct to the previous page , it should still redirect to current page.
So if user clicks refresh or back button it should redirect to current page only and should not insert any duplicate values and also alert box should be disabled.Please explain me what to do here, im in deep help.Thanks
There's lots of things wrong with your code, and lots of ways to mitigate the impact.
First, why are you creating duplicate entries?
In addition to the problem of bad data is also implies that your site is vulnerable to CSRF. Go read up on how to prevent CSRF with single-use tokens.
If you've got performance problems with your site, then users will often click on the submit button multiple times. While addressing the duplicate submission problem on the database, use javascript to disable the submit links on the page and provide visual feedback that the page is doing something.
Redirects are not the way to solve the problem.
My boss dont want that alert box of the browser
Are you talking about the duplicate post alert? While you can get around this using PRG, that creates other problems.
You must post a unique id (session_id) and save it in the database.
When your registration, test if the session_id is already present. If so, send a message to THE USER. "You have already post out this form"
The code:
<?php session_start; ?>
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
<input type="hidden" name="session_id" value="<?php echo session_id();?>">
</form>
demo.php
<?php
//test session_id in database
$session_id = session_id();
mysql_connect('localhost','xxx','xxx');
mysql_select_db('xxx');
$return = mysql_query("SELECT COUNT(*) AS nb_data FROM TABLENAME WHERE session_id='".session_id()."'");
$data = mysql_fetch_assoc($return);
if ($data['nb_data'] == 0){
echo 'Your message';
}
else{
$firstname = $_POST['fname'];
//.....
header('location:xxx.php')?
}
?>
I would use php header function to replace the current location so if the user clicks refresh, it won't repost the information and a session to store the posted value and check for resubmissions.
demo.php
<?php
session_start();
if($_POST)
{
if(!isset($_SESSION[fname]))
{
//database queries here
}
$_SESSION[fname] = $_POST['fname'];
header('location:demo.php', true); //true replaces the current location
}elseif(!issset($_SESSION[fname])){
header('location:form.php');
}
$firstname = $_SESSION[fname];
?>
form.php
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
</form>
You need ON DUPLICATE KEY , this will update the record instead of creating a copy of it :
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
so it wouldn't matter if they hit refresh or resubmit, if the record existed already it would just get updated.
The solution will be to redirect the page after database operations like insert, update and delete
pageName: test.php
if(isset($_REQUEST['deleteBtn']))
{
$emp_id=$_REQUEST['emp_id'];
$count=mysql_query("delete from employees where emp_id=$emp_id");
header("location:test.php");
}
This way if you click F5 or back button the form data will not get posted again.
What you want is to embed a session id in your form when you create it, and to track that session id on the server. Then, when the form is submitted and you are processing the form on the server, if the form was submitted more than once, you can overwrite the first submission in your database, or respond with an error message, or whatever. (Show the popup only on the first submission, whatever.)
An easy way to do this is to generate a session id, send it as a hidden field in the form, and when the form is submitted store the session id in your database with the constraint that the session id be unique.
I want to display warning messages in html. This code shows two text boxes named "company" and "name". con.php connects to the database and inserts the information. But if I enter nothing, then the values are still getting stored in the database as null. I want user to know that he shouldn't leave the fields blank by displaying some messages and also a warning should appear if the given company already exists in the database. How do I implement that?
<html>
<head>
<title>store in a database</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>company Store</h2>
<form name="form1" method="post" action="con.php">
<p>company:<input type="text" name="company">
<br/>
<br/>
<br/>
Name: <input type="text" name="name" size="40">
<br/>
<br/>
<br/>
<input type="submit" value="Save">
<input type="button" onclick="window.close()" value="cancel">
</form>
</body>
While an alert message cannot be produced without JavaScript, you could take advantage of HTML5's placeholder attribute to inform the user of this message:
<input type="text" placeholder="You must enter something in this field"! name="whatever" id="whatever" />
And couple this with JavaScript:
var inputElem = document.getElementById('whatever');
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function(){
if (inputElem.value = '' || inputElem.value.length < 1){
alert('You must enter some actual information');
return false;
}
};
However JavaScript can be edited by the users, via Firebug, Web Inspector, Dragonfly...or by simply creating a new html file and submitting the form to the same source from the action attribute of the form element. Therefore your form-handling script must be sanitised and checked on the server as well as the client; client-side checking is a convenience to the user (to prevent unnecessary page-reloads, submissions and so on), it is not a security feature, and should not be used, or mistaken, as such.
Best way is using Ajax if you want to do it at the same page. You need to read some tutorials on it. It's not that easy to explian here.
If reloading or redirecting to other page is ok for you, you should compare the submitted form value with the values in the database in a PHP script which is redirected from form submission (action url). If values doesn't match and not empty, store the values to database and redirect to a page like the list of companies or "company successfully created" message page. If values match with an old record or empty, redirect back to the same form page with a flag (something like form.php?error=1 etc.) and show the proper error message.
Also you can use JavaScript for immediate alerts. But you should always do the same checks at PHP side since JavaScript can be disabled in browsers.
In con.php you should do your data validation and return the markup (or redirect to page describing the error).
So, check for empty fields, and if the exists redirect the user to a page saying the fields can not be empty (and probably allow them to enter new values).
If the data entered is ok, check the database for duplicates and if they exist, redirect the user to a page saying that the company already exists (and again probably allow the user to correct the data).
You can not do it only with HTML.
You need to add a form validation (to prevent empty strings), HTML5 form validation can do that for you (check http://www.broken-links.com/2011/03/28/html5-form-validation/), but not all browser support it, so you will need to use JavaScript to validate the form.
There are JavaScript libraries that will take an old browser and make it behave like a browser that support HTML5 (check http://www.matiasmancini.com.ar/jquery-plugin-ajax-form-validation-html5.html).
You will also need to retrieve the companies already in your database and check them against the user input and alert him if needed.
On top of that you will need to validate the data in your PHP before inserting it to the database (check for empty string for example).
I'm quite new in this PHP programming and already tried looking my issue at this forum but no success.
I have build a simple webform using PHP and stuck when trying to edit form. My form consist of below
register html form - basicallly user fill in the form and hit submit. the form will then go to register.php
Register.php - all the field store at database and I also display the form using the SESSION (not call from database) in this page.
Here is my problem start. At the dispay(register.php) I want allow user to edit his/her information and submit again(which i think use update query base on ID). But I truly don't know how to do this.
Can someone advice me or give some simple code for this so that I can have clearer view?
you also must strip slashes for avoiding Sql injection
In previous pages you must store the username from textbox of login
Something like this:
session_start();
$_SESSION['username']=$_POST['input of login txtbox'];
you can just get the condition with user cause you have just one unique user 2 users mustn't have the same user name then just store the username of them in $_SESSION
$connection=Mysql_connect('server','user','pass');
if(array_key_exists('sub2',$_POST))
{
if(!$connection)
{
echo 'connection is invalid';
}
else
{
Mysql_select_db('Your DB',$connection);
$pas=$_POST['pass1'];
$username=$_POST['username'];
$pas=mysql_escape_string($pas);
$username=mysql_escape_string($username);
$query="update user set user='$username'and pass=password('$pas') where username='".$_SESSION['username'].";
//some code
}
in your form:
<p><b>User Name:</b><input type="text" name="username" />
<p><b>Password:</b><input type="password" name="pass1" />
<input type="submit" name="sub2" value="update"/>
use this site for secure your code
Please help me with file upload with text fields details going to database in codeigniter. ( for example i want image name and some another form field going to database and file uploads to server)
Also how do i stop the form submission in database upon page resfresh ?
The best I can do is link you to the relevant pages so that you can learn more. If you provide more information I might be able to help you more:
File upload:
http://codeigniter.com/user_guide/libraries/file_uploading.html
Database:
http://codeigniter.com/user_guide/database/index.html
I recommend using the Active Record part of the database library:
http://codeigniter.com/user_guide/database/active_record.html
As for how to stop form submission on page refresh, simply use redirect('controller/method'); after you have handled the form data. For example:
if(!is_bool($this->input->post('fieldvalue'))
{
$this->model->writeToDB($_POST);
redirect('controller/method');
}
so that every time data is submitted, it is added to the db and then the redirect will revisit the page, thus the browser won't remember what was in the post array and that will solve the problem.
view:
<form method="post" action="#">
<input type="text" name="foo"/>
<input type="submit"/>
</form>
controller:
$this->load->model('yourmodel','model',true);
if(isset($_POST['text']))
$result = $this->model->doQuery($_POST['text']);
model:
function doQuery($text){
$result = $this->db->query("insert into table $text");
return $result;
}
(edit) upload:
use $_FILES and move_uploaded file