Using PHP POST method to post to the same page - php

Tried figuring this out on my own using previous threads, but other peoples' examples didn't quite help me figure out what I need. The stand-alone files themselves work, data gets inserted into the DB just fine... but I'm trying to adapt these documents a bit to work as an all-in-one, single PHP document.
I figure I'll just throw out what I'm trying to do and the code I have so far, and maybe someone will understand what I'm trying to accomplish and be able to explain how to do it.
I basically have an PHP document with form (form.php) that uses POST to send the form data to a second PHP document, which in turn sends the form data to a MySQL database. I want the user to be able to post the data using the same document and have the data fields reset so that the user and submit enter more information through the form. I would like the make the user aware of errors due to incomplete fields, and I would like the user to be made aware of successful entries (which I will do using the echo function).
form.php is as follows:
<html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
<title>MySQL Database Creation System</title>
<script src="jquery-1.11.0.min.js"></script>
</head>
<body>
<div class="wrapper">
<img src="eris.png" align="middle">
<form action="insert.php" method="post">
Firstname: <input type="text" size="16" name="firstname">
Lastname: <input type="text" size="16" name="lastname">
Age: <input type="text" size="1" maxlength="3" name="age">
<input type="submit" class="button">
</form>
</div>
</body>
insert.php is as follows:
<html>
<head>
<link rel="stylesheet" type="text/css" href="insert.css">
<title>MySQL Database Creation System</title>
</head>
<body>
<div class="wrapper">
<img src='eris.png' align='middle'>
<?php
if ( (trim($_POST['firstname']) == "") || (trim($_POST['lastname']) == "") || (trim($_POST['age']) == "") )
{
echo "<p>ERROR: All fields must be completed</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
else
{
$con=mysqli_connect("localhost","test","test","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "<br>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 Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql))
{
die('<br>Error: ' . mysqli_error($con));
}
mysqli_close($con);
echo "<p>New item added.</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
?>
</div>
</body>
Thanks in advance for any assistance you can give.

I hope I get the point. In this case you are near. Just merge your scripts like this:
<?php
// check if there is a post request ...
// if not - nothing happens
if(!empty($_POST))
{
if ( (trim($_POST['firstname']) == "") || (trim($_POST['lastname']) == "") || (trim($_POST['age']) == "") )
{
echo "<p>ERROR: All fields must be completed</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
else
{
// your inser code
$con=mysqli_connect("localhost","test","test","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "<br>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 Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql))
{
die('<br>Error: ' . mysqli_error($con));
}
mysqli_close($con);
echo "<p>New item added.</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
<title>MySQL Database Creation System</title>
<script src="jquery-1.11.0.min.js"></script>
</head>
<body>
<div class="wrapper">
<img src="eris.png" align="middle">
<!-- change insert.php to form.php -->
<form action="form.php" method="post">
Firstname: <input type="text" size="16" name="firstname">
Lastname: <input type="text" size="16" name="lastname">
Age: <input type="text" size="1" maxlength="3" name="age">
<input type="submit" class="button">
</form>
</div>
I hope that is near your expectations.

Restore your form.php like below -
What have I done here -
1) <form action="insert.php" method="post">
TO
<form action="" method="post">
2) Added all of your php code in form.php
<?php
if ( (trim($_POST['firstname']) == "") || (trim($_POST['lastname']) == "") || (trim($_POST['age']) == "") )
{
echo "<p>ERROR: All fields must be completed</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
else
{
$con=mysqli_connect("localhost","test","test","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "<br>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 Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql))
{
die('<br>Error: ' . mysqli_error($con));
}
mysqli_close($con);
echo "<p>New item added.</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
<title>MySQL Database Creation System</title>
<script src="jquery-1.11.0.min.js"></script>
</head>
<body>
<div class="wrapper">
<img src="eris.png" align="middle">
<form action="" method="post">
Firstname: <input type="text" size="16" name="firstname">
Lastname: <input type="text" size="16" name="lastname">
Age: <input type="text" size="1" maxlength="3" name="age">
<input type="submit" class="button">
</form>
</div>
</body>

Then Your form page should like this.
<html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
<title>MySQL Database Creation System</title>
<script src="jquery-1.11.0.min.js"></script>
</head>
<body>
<div class="wrapper">
<img src="eris.png" align="middle">
<form action="" method="post">
Firstname: <input type="text" size="16" name="firstname">
Lastname: <input type="text" size="16" name="lastname">
Age: <input type="text" size="1" maxlength="3" name="age">
<input type="submit" class="button">
</form>
</div>
</body>
<?php
if ( (trim($_POST['firstname']) == "") || (trim($_POST['lastname']) == "") || (trim($_POST['age']) == "") )
{
echo "<p>ERROR: All fields must be completed</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
else
{
$con=mysqli_connect("localhost","test","test","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "<br>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 Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql))
{
die('<br>Error: ' . mysqli_error($con));
}
mysqli_close($con);
echo "<p>New item added.</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
?>
Thanx

Related

The data is not registered to the database

I want to make a student registration form. I get no error messages, but the data is not entered into the database.
INDEX is for INDEX NUMBER
USERNAME is for USER
EMAIL is for EMAIL
I had trouble with index variable it said that it is undefined, I am not sure if I defined the variable properly.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- TemplateBeginEditable name="doctitle" -->
<title>Untitled Document</title>
<!-- TemplateEndEditable -->
<!-- TemplateBeginEditable name="head" -->
<!-- TemplateEndEditable -->
</head>
<body>
<?php
session_start();
$_SESSION["message"] = "";
$mysqli = new MySQLi("localhost","root","","accounts");
if ($_SERVER['REQUEST_METHOD'] == "POST"){
$username = $mysqli->real_escape_string($_POST["username"]);
$email = $mysqli->real_escape_string($_POST["email"]);
$index = ($_POST["email"]);
$_SESSION["username"] = $username;
$_SESSION["email"] = $email;
$sql = "INSERT INTO users (index, email, name) "
. "VALUES ('$index', '$email', '$username')";
//check if mysql query is successful
if ($mysqli->query($sql) === true)
{
$_SESSION[ 'message' ] = "Registration succesful! Added $username to the database!";
//redirect the user to welcome.php
header( "location: welcome.php" );
}
else{
$_SESSION["message"] = "user could not be added to the database";
}
}
else{
$_SESSION["message"] = "could not initiate session";
}
?>
<link href="//db.onlinewebfonts.com/c/a4e256ed67403c6ad5d43937ed48a77b?family=Core+Sans+N+W01+35+Light" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="form.css" type="text/css">
<div class="body-content">
<div class="module">
<h1>Create an account</h1>
<form class="form" action="form.php" method="post" enctype="multipart/form-data" autocomplete="off">
<div class="alert alert-error"></div>
<input type="text" placeholder="User Name" name="username" required />
<input type="email" placeholder="Email" name="email" required />
<br>
<input type="text" placeholder="Index Number" name="index" required /><br>
<input type="submit" value="Register" name="register" class="btn btn-block btn-primary" />
</form>
</div>
</div>
</body>
</html>
Change this line :
$sql = "INSERT INTO users (index, email, name) "
. "VALUES ('$index', '$email', '$username')";
To this :
$sql = 'INSERT INTO users (index, email, name) '
. 'VALUES ("$index", "$email", "$username")';
Hope to solve your problem.

My php code does not post to database on server but it is working on localhost

This is the code. It is working on localhost, but when I upload it to my server the PHP does not send information to MySQL.
<?php
session_start();
include('connect.php');
if(isset($_POST['signup'])){
echo "<pre>"; print_r($_POST); echo "</pre>";
$name=$_POST['name'];
$email=$_POST['email'];
$password=md5($_POST['password']);
$contact=$_POST['contact'];
$city=$_POST['city'];
$address=$_POST['address'];
$signup_sql=mysqli_query($con,"select * from signup where email='".$email."'");
//$signup_res=mysqli_query($con,$signup_sql);
//$signupresult=mysqli_fetch_array($signup_res);
$dataa = mysqli_fetch_array($signup_sql);
if(empty($signup_res)){
$sql="insert into signup (name,email,password,contact,city,address) values ('".$name."','".$email."','".$password."','".$contact."','".$city."','".$address."')";
$res=mysqli_query($con,$sql);
if($res>=1){
#header("location:login.php");
}
else{
#header("location:index.php");
}
}else{
#header("location:index.php");
}
}
?>
You're not testing the select query correctly. if(empty($signup_res)) only tests if the query got an error. But a query that doesn't match anything is not an error, it's just an empty result.
You should check the result of fetching the result:
if(empty($dataa))
And then when you perform the insert query, you're not checking its success correctly, either. $res will be either TRUE or FALSE, not a number. If you want to redirect to login.php if the insert failed, it should be:
if (!$res) {
header("location: login.php");
} else {
header("location: index.php");
}
I also recommend that while debugging you remove the redirect and display the error message when the query fails. You also shouldn't use # while debugging (and there's little reason to use # for header() calls anyway).
YiPp i fixed it by by changing code to
<?php
session_start();
header('location:login.php');
$con = mysqli_connect('localhost','id8127977_decors','Priya#1994');
if($con){
echo" connection successful";
}else{
echo " no connection";
}
mysqli_select_db($con, 'id8127977_decors');
$name=$_POST['name'];
$email=$_POST['email'];
$password=md5($_POST['password']);
$contact=$_POST['contact'];
$city=$_POST['city'];
$address=$_POST['address'];
$q = " select * from signup where email = '$email' ";
$result = mysqli_query($con, $q);
$num = mysqli_num_rows($result);
if($num == 1){
echo" duplicate data ";
}else{
$qy= "insert into signup (name,email,password,contact,city,address) values ('".$name."','".$email."','".$password."','".$contact."','".$city."','".$address."')";
mysqli_query($con, $qy);
}
?>
<!doctype html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>File Upload PHP</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8">
<form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />
</div>
<div class="form-group">
<label for="email">EMAIL</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required />
</div>
<input id="uploadImage" type="file" accept="image/*" name="image" />
<div id="preview"><img src="filed.png" /></div><br>
<input class="btn btn-success" type="submit" value="Upload">
</form>
<div id="err"></div>
</div>
</div>
</div></body></html>

Notice: Undefined index: username in F:\wamp64\www\practise\insert.php on line 16

I have done this from one of the youtube channel .. ii just copied all the code but still its not working. can you anyone can help me on this. I have facing the error at end saying NOT INSERTED.
**index.php**
<html>
<head>
<title>Data entry practise</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="wrapper">
<form action="insert.php" method="_POST">
Name: <input type="text" name="username"><br><br>
Email Address: <input type="text" name="email"><br><br>
<input type="submit" value="insert">
</form>
</div>
</body>
</html>
Now this is the inset.php code section. seems like here is some error .. please help me out
**insert.php**
<?php
$con = mysqli_connect('localhost','root','');
if(!$con)
{
echo "not connected";
}
if(!mysqli_select_db($con,'tutorial'))
{
echo 'database Note Selected';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
$sql = "INSERT INTO person (Name,Email) VALUES ('$Name', '$Email')";
if(!mysqli_query($con, $sql))
{
echo "Not Inserted";
}
else
{
echo "Inserted";
}
?>
The problem is that the form method is incorrect. You have to write it without the underscore
**index.php**
<html>
<head>
<title>Data entry practise</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="wrapper">
<form action="insert.php" method="POST">
Name: <input type="text" name="username"><br><br>
Email Address: <input type="text" name="email"><br><br>
<input type="submit" value="insert">
</form>
</div>
</body>
</html>
EDIT:
I think the problem is on your mysql connection. You need to add the db on the $con variable, like this:
insert.php
$con = mysqli_connect('localhost','root','', 'tutorial');
if(!$con)
{
echo "not connected";
}
if(!mysqli_select_db($con,'tutorial'))
{
echo 'database Note Selected';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
$sql = "INSERT INTO person (Name,Email) VALUES ('$Name', '$Email')";
if(!mysqli_query($con, $sql))
{
echo "Not Inserted";
}
else
{
echo "Inserted";
}
?>
I tested with your code and it is working.
One more thing, you need to change the form method to "POST", without underscore, it is important.

Trouble with recording information in sql tables from Html Forms

I have created a html register page which is really basic and requires the user to enter their First name, Last name, email, and password. However only the first and last names are being recorded in the database in phpmyadmin and the email and passwords are showing as blank cloumns. I have tried to drop and add the tables and columns again without any luck, i have changed variable names and no luck as well. Not too sure what to do.
Php code
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$password_ = $_POST['password_'];
if (isset($_POST['register'])) {
register($first_name,$last_name,$_email,$password,$conn);
}
$conn->close();
function register($first_name,$last_name,$email,$password,$conn) {
// echo $first_name . " " . $last_name . " " . $student_id . " " . $email;
$sql = "INSERT INTO `register` (`first_name`, `last_name`, `email`, `password_`) VALUES ('$first_name', '$last_name', '$email', '$password_')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
html code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<form role="form" action="register.php" method="POST">
<div class="form-group">
<label>First Name:</label>
<input type="text" class="form-control" id="first_name" name="first_name"required>
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" class="form-control" id="last_name" name="last_name"required>
</div>
<div class="form-group">
<label>Email address:</label>
<input type="varchar" class="form-control" name="e_mail" id="email"required>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" id="password" name="password"required>
</div>
<div class="form-group">
<label>Confirm Password:</label>
<input type="password" class="form-control" id="confirm_password"required >
<script>
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
</div>
<button type="submit" class="btn btn-default" name="register">Register</button>
</form>
</body>
</html>
In order to grab the _POST variables, your input forms must have a name attribute. For your Email form, you have only specified an ID and no name. Go back and add in the name='email' attribute and it should work. Same for password.
It looks like i was missing an underscore in the php register code where it states the function. i have added it and now my code seems to be working, thanks for all the feedback!

PHP form, converting input field into a drop down list

The below code is a simple form that is sending the data that is inputted to my local database.
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="school" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
<!-- Right side div -->
</div>
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
?>
</body>
</html>
The issue that I am finding is that I am trying to change the Student City input field into a drop down where the values is retrieve from the database and put into a drop down list for a new user to select.
Could someone advise on what needs to be done please.
i am trying to use the below code and send the below list to my database.
<option value="US">United States</option>
<option value="UK">United Kingdom</option>
<option value="France">France</option>
<option value="Mexico">Mexico</option>
but i am finding it hard to send the these values to the database with my above code as well as where to place this code.
As a rough example of how you could build the dropdown menu using data from your db this should give you the general idea perhaps.
/* store formatted menu options in temp array */
$html=array();
/* query db to find schools/cities */
$sql='select distinct `student_school` from `students` order by `student_school`';
$res=$mysqli_query( $conn, $sql );
/* process recordset and store options */
if( $res ){
while( $rs=mysqli_fetch_object( $res ) ){
$html[]="<option value='{$rs->student_school}'>{$rs->student_school}";
}
}
/* render menu */
echo "<select name='stu_city'>", implode( PHP_EOL, $html ), "</select>";
You need to refactor your code by moving the if (isset($_POST)) above the html:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT city_name FROM cities" ;
if ($conn->query ( $sql ) === TRUE) {
$cities = ... // build the cities from the query result
} else {
$cities = '<option value="none">No cities found</option>' ;
}
if (isset ( $_POST ["submit"] )) {
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('" . $_POST ["stu_name"] . "','" . $_POST ["stu_email"] . "','" . $_POST ["stu_city"] . "')";
if ($conn->query ( $sql ) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close ();
}
?>
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr />
<form action="" method="post">
<label>Student Name :</label> <input type="text" name="stu_name"
id="name" required="required" placeholder="Please Enter Name" /><br />
<br /> <label>Student Email :</label> <input type="email"
name="stu_email" id="email" required="required"
placeholder="john123#gmail.com" /><br />
<br /> <label>Student City :</label> <select name="stu_city" multiple><?php echo $cities; ?>
</select>><br />
<br /> <input type="submit" value=" Submit " name="submit" /><br />
</form>
</div>
<!-- Right side div -->
</div>
</body>
</html>
Use the Select tag: Lets say you hav a column in your database with Student City, like this, lets say the database field is called city
City 1
City 2
City 3
Step 1: Query the database and fetch all the Cities
$sql = "SELECT city FROM table_name";
$result = $conn->query($sql);
Then you come to your dropdown:
<select name="stu_city" id="..." required>
<?php
while($cities = $conn->fetch_array($result){
extract($cities);
echo "<option value='...'>$city</option>";
}
?>
</select>
You need to refactor your code by moving the if (isset($_POST)) above the html:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT city_name FROM cities" ;
$result = $conn->query ( $sql );
if (isset ( $_POST ["submit"] )) {
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('" . $_POST ["stu_name"] . "','" . $_POST ["stu_email"] . "','" . $_POST ["stu_city"] . "')";
if ($conn->query ( $sql ) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close ();
}
?>
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr />
<form action="" method="post">
<label>Student Name :</label> <input type="text" name="stu_name"
id="name" required="required" placeholder="Please Enter Name" /><br />
<br /> <label>Student Email :</label> <input type="email"
name="stu_email" id="email" required="required"
placeholder="john123#gmail.com" /><br />
<br /> <label>Student City :</label> <select name="stu_city" multiple>
<?php
if ($result == TRUE) {
while($cities = $conn->fetch_array($result)){
extract($cities);
echo "<option value=''>$city_name</option>";
}
}
else {
echo "<option value='none'>No cities found</option>";
}
?>
</select>><br />
<br /> <input type="submit" value=" Submit " name="submit" /><br />
</form>
</div>
<!-- Right side div -->
</div>
</body>
</html>

Categories