Insert And Retrieve Data in MySQL with $.post Noob Question - php

Trying to insert data into MySQL database with PHP. I don't want to refresh the page. The data isn't inserted when I press the Send Message button, but the data is displayed. Please help a noob out. Here's the HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Contact Form</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="form">
<form method="POST" action="form.php" id="foo" name="foo">
<h1>Contact Form</h1>
<table>
<tr>
<td>
<label for="fname">Full Name:</label><br>
<input type="text" name="fname" placeholder="John Doe" id="">
</td>
</tr>
<tr>
<td>
<label for="email">Your Email:</label><br>
<input type="email" name="email" placeholder="example#gmail.com" id="">
</td>
</tr>
<tr>
<td>
<label for="msg">Your Message:</label><br>
<textarea name="msg" placeholder="Type your message..." id="" cols="30" rows="10"></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Send Message">
</td>
</tr>
</table>
</form>
</div>
<p id="target">
</p>
<script>
$(function() {
$("#foo").submit(function(event){
// Stop form from submitting normally
event.preventDefault();
/* Serialize the submitted form control values to be sent to the web server with the request */
var formValues = $(this).serialize();
// Send the form data using post
$.post("form.php", formValues, function(response){
$('#target').load('show.php');
});
});
});
</script>
</body>
</html>
Here's form.php which is supposed to insert data into the database:
<?php
error_reporting(E_ALL);
log_errors(1);
display_errors(1);
if(isset($_POST['submit']))
{
$name = $_POST['fname'];
$email = $_POST['email'];
$message = $_POST['msg'];
//database details. You have created these details in the third step. Use your own.
$host = "localhost";
$username = "user";
$password = "GoTn_1290";
$dbname = "form_entriesdb";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect($host, $username, $password, $dbname);
//check connection if it is working or not
if (!$con)
{
die("Connection failed!" . mysqli_connect_error());
}
//This below line is a code to Send form entries to database
$sql = $con->prepare("INSERT INTO contactform_entries (name_fld, email_fld, msg_fld) VALUES (?, ?, ?)");
$sql->bind_param("sss", $name, $email, $message);
$sql->execute();
//connection closed.
$sql->close();
$con->close();
}
?>
And here's what displays my data, show.php:
<?php
$servername = "localhost";
$username = "user";
$password = "secret";
$dbname = "form_entriesdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT id, name_fld, email_fld, msg_fld FROM contactform_entries";
$result = $conn->query($sql2);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name_fld"]. " " . $row["email_fld"]. " " . $row["msg_fld"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

I ended up using .ajax instead of .post. I also changed my filename to index.php. I can't find the website where I got my code from, but here it is:
<!DOCTYPE html>
<html>
<head>
<title>Insert data in MySQL database using Ajax</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div style="margin: auto;width: 60%;">
<div class="alert alert-success alert-dismissible" id="success" style="display:none;">
×
</div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Name" name="name">
</div>
<div class="form-group">
<label for="pwd">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Email" name="email">
</div>
<div class="form-group">
<label for="pwd">Phone:</label>
<input type="text" class="form-control" id="phone" placeholder="Phone" name="phone">
</div>
<div class="form-group" >
<label for="pwd">City:</label>
<select name="city" id="city" class="form-control">
<option value="">Select</option>
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Pune">Pune</option>
</select>
</div>
<input type="button" name="save" class="btn btn-primary" value="Save to database" id="butsave">
</form>
</div>
<p id="target">
</p>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var city = $('#city').val();
if(name!="" && email!="" && phone!="" && city!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
name: name,
email: email,
phone: phone,
city: city
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
$('#target').load('show.php');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the fields !');
}
});
});
</script>
</body>
</html>
Here's save.php. It's the code that inserts data into the database:
<?php
include 'database.php';
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$city=$_POST['city'];
$sql = $con->prepare("INSERT INTO `crud`( `name`, `email`, `phone`, `city`) VALUES (?,?,?,?)");
$sql->bind_param("ssss", $name, $email, $phone, $city);
$rc = $sql->execute();
if (true===$rc) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
//connection closed.
$sql->close();
$con->close();
?>
Here is show.php:
<?php
include 'database.php';
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$query = "SELECT name, email, phone, city FROM crud";
$result = $con->query($query);
if ($result->num_rows > 0) {
// output data of each row
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["name"]. " " . $row["email"]. " " . $row["phone"]. " " . $row["city"]."<br>";
}
} else {
echo "0 results";
}
$result -> free_result();
$con->close();
?>
And here are the database connection details, database.php:
<?php
$servername = "localhost";
$username = "user";
$password = "secret";
$db="school";
$con = mysqli_connect($servername, $username, $password,$db);
?>
The code posted is entirely functional.

Related

Trouble with posting data to database using jquery ajax

I have looked up tutorials multiple times and am having trouble figuring out where my code is wrong. I am able to run my php file and get my information sent into my database, so I know my connection isn't the issue, so I am thinking its my index.html file. It may have something to do with how i tried to implement jquery, but I don't know about that either
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="login.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#login').click(function(event){
event.preventDefault();
var username =$('#use').val();
var pass = $('#pass').val();
$.ajax({
url: 'login.php',
method:'POST',
data:
{
User: username,
Pass: pass
},
success:function(result){
alert(result);
}
});
});
});</script>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form">
<input type="text" placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p class="message">Already registered? Sign In</p>
</form>
<form class="login-form">
<input type="text" id="use" placeholder="username"/>
<input type="password" id="pass" placeholder="password"/>
<button type="submit" id="login">login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
</body>
</html>
PHP code connecting to my DB
<?php
$dbname = 'project test';
$dbuser = 'root';
$dbpass = '';
$dbhost = 'localhost';
$username=$_POST['use'];
$password=$_POST['pass'];
$conn= mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (User, Pass)
VALUES ('{$username}','{$password}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close(); ;
?>
In your index.html file, you are sending User and Password values However, when you are trying to get them in your php file, you are trying to get use and pass values. Their names don't match. The names need to match in order to get the values correctly.

How do i send HTML input fields to my MySQLi database using PHP?

I am trying to send the data put into the input fields to my database and I cant seem to make it work out properly..
The ultimate goal is to put in the input fields into the database and show the inserted data in another window.
Here's my code
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// create a variable
$naam=$_POST['namen'];
$plaats=$_POST['plaatsen'];
$land=$_POST['landen'];
//Execute the query
mysqli_query($conn,"INSERT INTO phptoets(Namen,Plaatsen,Landen)
VALUES('$naam','$plaats','$land')");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="POST">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
Try this. It will help you. I've done few changes in your code.
- Add form to post the data on server
- Add database name in connection
- Add provincie field in form (because you are trying to get that in php)
- Use the same variable in query as declared at the time of connection
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "DATABASE";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// create a variable
$namen=$_POST['naam'];
$plaatsen=$_POST['plaats'];
$landen=$_POST['land'];
$provincie=$_POST['provincie'];
//Execute the query
mysqli_query($conn, "INSERT INTO employees1(naam,plaats,land,provincie) VALUES('$namen','$plaatsen','$landen','$provincie')");
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="POST" action="">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="text" name="provience" class="input_provience" placeholder="Provience"><br>
<input type="button" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
This is my solution:
You forgot to set database name and the names of your input fields where not equal to your $_POST names.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// create a variable
$naam=$_POST['naam'];
$plaats=$_POST['plaats'];
$land=$_POST['land'];
//Execute the query
mysqli_query($conn,"INSERT INTO phptoets(namen,plaatsen,landen)
VALUES('$naam','$plaats','$land')");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="post">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
<?php
// TESTS
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br>";
if(isset($_POST['submit']))
{
// create a variable
$a = (string)filter_input(INPUT_POST,'naam');
$b = (string)filter_input(INPUT_POST,'plaats');
$c = (string)filter_input(INPUT_POST,'land');
$d = (string)filter_input(INPUT_POST,'provincie');
echo("executing query <br>");
//Execute the query
if($a != null && $b != null && $c != null && $c != null)
{
$sql="INSERT INTO employees1 (naam,plaats,land,provincie) VALUES (?,?,?,?)";
echo("sql ".$sql. "<br>");
if($stmt = $conn->prepare($sql))
{
$stmt->bind_param("ssss",$a,$b,$c,$d);
$stmt->execute();
$stmt->close();
}
}
$sql = "SELECT naam, plaats, land, provincie FROM employees1";
if ($stmt = $conn->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($naam,$plaats,$land,$provincie);
while ($stmt->fetch())
{
printf("naam : %s, plaats: %s, land: %s, provincie: %s <br>",$naam,$plaats,$land,$provincie);
}
$stmt->close();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<form class="my_form" target="_self" enctype="multipart/form-data" method="post">
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="text" name="provincie" class="input_land" placeholder="Provincie"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</form>
</div>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
I will just name few things that I changed in your code, not mentioning syntax errors
you dont specify db_name in your sql connection
you dont use prepared statements nor any kind of input filtering
(note : my input filtering is very basic, read more about how to
filter inputs)
to address html form you need to create one and have submit input
type inside

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>

Form saying its sent but there is no data is showing up in the database

I'm new to PHP and still trying to get my head round it. this form says that the data has been sent to the database but when I look the database is empty, no errors are showing up? is there a problem with my code.
Note: I understand that this form is not protected from SQL Injection.
HTML
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Page 3 Form</h2><hr/>
<span id="error">
</span>
<form action="page4_insertdata.php" method="post">
<label>Company Name :<span>*</span></label><br />
<input name="company_name" type="text" placeholder="Joes Cleaner" required>
<br />
<label>Ref :<span>*</span></label><br />
<input name="ref" type="text" placeholder="H123" required>
<br />
<label>Website :<span>*</span></label><br />
<input name="website" type="text" placeholder="www.google.com" required>
<br />
<label>Email :<span>*</span></label><br />
<input name="email" type="email" placeholder="Joescleaners#gmail.com" required>
<br />
<label>Telephone :<span>*</span></label><br />
<input name="tel" type="text" placeholder="07123456789" required>
<br />
<label>Message :<span>*</span></label><br />
<input name="message" id="message" type="text" size="500" required>
<br />
<input type="reset" value="Reset" />
<input name="submit" type="submit" value="Submit" />
</form>
</div>
</div>
</body>
</html>
PHP
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Multi Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Multi Page Form</h2><hr/>
<?php
$servername = "localhost";
$db_database = 'form';
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "DB Connected successfully. ";
$company_name = $_POST['company_name'];
$ref = $_POST['ref'];
$website = $_POST['website'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$sql = "INSERT INTO detail (company_name,ref,website,email,tel,message)
VALUES ('$company_name','$ref','$website','$email','$tel','$message')";
if($sql){
echo " Database Sent.";
}
else {
echo "ERROR to insert into database";
};
?>
</div>
</div>
</body>
</html>
Change the following code:
if($sql){
echo " Database Sent.";
}
else {
echo "ERROR to insert into database";
};
To:
$result = $conn->query($sql);
if($result){
echo " Database Sent.";
}
else {
echo "ERROR to insert into database";
};
This way you are actually performing the query and checking on failure of query...
To make your query a bit safer, try the following:
$sql = "
INSERT INTO detail (
company_name,
ref,
website,
email,
tel,
message
)
VALUES (
'" . mysqli_real_escape_string($company_name) . "',
'" . mysqli_real_escape_string($ref) . "',
'" . mysqli_real_escape_string($website) . "',
'" . mysqli_real_escape_string($email) . "',
'" . mysqli_real_escape_string($tel) . "',
'" . mysqli_real_escape_string($message) . "'
)";
Better yet, use binding of params by replace the $sql instantiation and query execution ($conn->query()) with the following:
$stmt = $conn->prepare("INSERT INTO detail (company_name,ref,website,email,tel,message) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $company_name, $ref, $website, $email, $tel, $message);
$stmt->execute();
You can read up on binding parameters with mysqli by visiting PHP: mysqli_stmt::bind_param - Manual
Complete code:
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Multi Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Multi Page Form</h2><hr/>
<?php
$servername = "localhost";
$db_database = 'form';
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $db_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "DB Connected successfully. ";
$stmt = $conn->prepare("INSERT INTO detail (company_name,ref,website,email,tel,message) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss',
$_REQUEST['company_name'],
$_REQUEST['ref'],
$_REQUEST['website'],
$_REQUEST['email'],
$_REQUEST['tel'],
$_REQUEST['message']
);
if($stmt->execute()) {
echo " Database Sent.";
} else {
echo "ERROR to insert into database: " . $stmt->error;
};
?>
</div>
</div>
</body>
</html>
You arent actually sending a query, you are setting the variable $sql = "INSERT....."
which is always true.
you need to do:
$result = $mysqli->query($sql);
if ($result......)

Categories