Sort output from MySql with php - javascript

I try to return table values from Mysql db sorted
. I manage to connect and update the table right,
at the same page I wish to return the table back to html as chat history. just can't get the messages to show up sorted by time .
2) how is there a better way to return the output with ajax & jquery to the last div id messages?
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sender = $_POST["sender"];
$receiver = $_POST["receiver"];
$message = $_POST["message"];
date_default_timezone_set('Asia/Tel_Aviv');
$create_date = date('Y-m-d H:i:s');
//Not sure this is right way to update the date.
if ($create_date != $update_date)
$date == $update_date;
$sql = "INSERT INTO messages (sender, receiver, message, create_date) VALUES ('$sender', '$receiver', '$message', '$create_date')";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, sender, receiver, message, create_date FROM messages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["id"]. ") " . $row["sender"]. " to " . $row["receiver"]. " : " . $row["message"]. " / " . $row["create_date"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Html
<form action="" method="POST" enctype="multipart/form-data">
<p>name of sender:
<input class="input" name="sender" id="sender" value="" size="13"
maxlength="13" dir="ltr" autocomplete="on" type="text" height="20" required><br>
<p>name of receiver:
<input class="input" name="receiver" id="receiver" value="" size="13"
maxlength="13" dir="ltr" autocomplete="on" type="text" height="20" required><br>
<p>Message: <br>
<textarea name="message" id="message" value="" rows="5" cols="30" dir="ltr" required></textarea><br>
<input value="Submit" name="button" alt="submit" onsubmit="return checkForm(this);" border="0" type="submit" align="absmiddle"></p>
</form>
<P>MESSAGES</P>
<div id="messages">
<?php include_once("action.php") ?>
Javascript validation
(can't work )
I used required in html5 instead
function checkForm(form)
{
if($('#sender').val() == ''){
alert("Sender name can not be left blank");
form.sender.focus();
return false;
}
if($('#receiver').val() == ''){
alert("Receiver name can not be left blank");
form.receiver.focus();
return false;
}
if($('#message').val() == ''){
alert("Message input can not be left blank");
form.message.focus();
return false;
}
return true;
}

Maybe you can change your select query to
SELECT id, sender, receiver, message, create_date FROM messages ORDER BY create_date

Related

PHP MYSQL Upload Image With other data

This is what it looks like.
But when i press the submit button it wont upload the image.
Is it possible to have 2 functions in one SUBMIT?
It saves the other data in my database but the image is not uploaded nor it is in my database.
<?php
$con=mysqli_connect("localhost","root","","presyohan");
// Check connection
if (mysqli_connect_error())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit']))
{
$prod_name = $_POST['prod_name'];
$prod_price = $_POST['prod_price'];
$prod_category = $_POST['prod_category'];
$sql="INSERT INTO products (prod_name, prod_price, prod_category)
VALUES('$prod_name','$prod_price','$prod_category')";
$result=mysql_query($sql);
if ($con->query($sql) === TRUE) {
session_start();
$_SESSION['users'] = $rows['prod_name'];
$_SESSION['id'] = $rows['user_id'];
header("Location: store-index.php");
die();
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
//imageupload
$filename = $_FILES['uploadfile']['name'];
$filetmpname = $_FILES['uploadfile']['tmp_name'];
$folder = 'images/products/';
move_uploaded_file($filetmpname, $folder.$filename);
$sqls = "INSERT INTO 'products' ('prod_img') VALUES ('$filename')";
$qry = mysqli_query($con, $sqls);
if ($qry) {
echo 'header("Location: store-index.php")';
}
$con->close();
}
?>
<form class="form" action="add-prod.php" method="post" enctype="multipart/form-data">
<div class="upload-btn-wrapper">
<label for="file-upload" class="custom-file-upload">
Product Image <i class="fas fa-cloud-upload-alt"></i>
</label>
<input id="file-upload" type="file" name="uploadfile" />
</div>
<div class="form__group">
<button class="btn" type="submit" name="submit">ADD</button>
</div>
</form>
enter image description here

Getting Ajax error 500 when trying to post items from Database

What I am trying to do is modify some attributes in my database. The way I want to do it, is to have a dropdown menu that is populated with options (in this case, student names) from the table I am calling, and then populating text fields with the information that pertains to that specific student, that can then be edited and then submitted to the database. So far, my drop down menu works. It fills itself with the appropriate attributes. My problem comes when I'm trying to populate the text fields with the other attributes. I opened up the console to see if I was getting any errors (because nothing was happening after I selected a student) and it said there was an error 500 with my POST.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
# Perform database query
$query = "SELECT * FROM student";
$result = $conn->query($query) or die('Query 1 failed: ' . mysql_error());
?>
<label for="studentSelect">Student Name: </label>
<select id="studentSelect">
<option value="0">Please select</option>
<?php
while ($row = $result->fetch_assoc())
{
echo '<option value="' . $row['studentID'] . '" > "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>';
}
?>
</select>
<div>
<label for="element_5_1">First Name</label>
<input id="element_5_1" name="element_5_1" class="element text large" type="text">
</div>
<div>
<span class="floatLeft">
<label for="element_5_3">Last Name</label>
<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text">
</span>
<span style="float:left">
<label for="element_5_4">Major</label>
<input id="element_5_4" name="element_5_4" class="element text medium" style="width:4em" type="text">
</select>
</span>
<span style="float:left">
<label for="element_5_5">Credits Earned</label>
<input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" type="text">
</span>
</div>
<script type="text/javascript">
function makeAjaxRequest(studentFirstName)
{
$.ajax({
type: "POST",
data: { studentFirstName: studentFirstName },
dataType: "json",
url: "process_ajax.php",
success: function(json)
{
insertResults(json);
},
failure: function (errMsg)
{
alert(errMsg);
}
});
}
$("#studentSelect").on("change", function()
{
var id = $(this).val();
if (id === "0")
{
clearForm();
}
else
{
makeAjaxRequest(id);
}
});
function insertResults(json)
{
$("#element_5_1").val(json["studentFirstName"]);
$("#element_5_3").val(json["studentLastName"]);
$("#element_5_4").val(json["major"]);
$("#element_5_5").val(json["creditsEarned"]);
}
function clearForm()
{
$("#element_5_1, #element_5_3, #element_5_4, #element_5_5").val("");
}
</script>
I then have a separate ajax processing file
<?php
$host = "********.mysql.database.azure.com";
$username = "************";
$password = "*******";
$db_name = "**********";
//Establishes the connection
$conn = mysqli_init();
mysqli_real_connect($conn, $host, $username, $password, $db_name, 3306);
if (mysqli_connect_errno($conn)) {
die('Failed to connect to MySQL: '.mysqli_connect_error());
$studentName = $_POST['studentFirstName'];
$query = "SELECT * FROM student";
$result = mysql_query($query) or die('Query 2 failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
if ($studentName == $row['studentFirstName']){
echo json_encode($row);
}
}
?>
I hope I've given enough information for someone to be able to spot my errors. Thank you!
Parse error line 22.
<?php
$host = "********.mysql.database.azure.com";
$username = "************";
$password = "*******";
$db_name = "**********";
//Establishes the connection
$conn = mysqli_init();
mysqli_real_connect($conn, $host, $username, $password, $db_name, 3306);
if (mysqli_connect_errno($conn)){
die('Failed to connect to MySQL: '.mysqli_connect_error());
$studentName = $_POST['studentFirstName'];
$query = "SELECT * FROM student";
$result = mysql_query($query) or die('Query 2 failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
if ($studentName == $row['studentFirstName']){
echo json_encode($row);
}
}
}
?>
You have to change also your javascript
function insertResults(json)
{
$("#element_5_1").val(json.studentFirstName);
$("#element_5_3").val(json.studentLastName);
$("#element_5_4").val(json.major);
$("#element_5_5").val(json.creditsEarned);
}
After 4 hours of trial and error, this is the code I came up with that works in populating the input fields. I'm pretty sure your error was the fact that your
<option value="' . $row['studentID'] . '" > "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>
should have been
<option value="' . $row['studentID'] . '" name="studentFirstName"> "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>
anyways onto my code:
config.php
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = ""; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
index.php
<?php
include("config.php");
$sql = "SELECT * FROM messaging";
$result = $conn->query($sql);
$conn->close();
?>
<!Doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<label for="studentSelect">Student Name: </label>
<select id="studentSelect">
<option value="0">Please select</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?php echo $row['msg_id']; ?>" name="studentFirstName" id="studentFirstName">"<?php echo $row['msg_from'] ?>" "<?php echo $row['msg_to'] ?>"</option>
<?php } ?>
</select>
<div>
<span class="floatLeft">
<label>First Name</label>
<input id="populate_first_name" class="element text large" type="text">
</span>
<span class="floatLeft">
<label>Last Name</label>
<input id="populate_last_name" class="element text medium" style="width:14em" type="text">
</span>
<span style="float:left">
<label>Major</label>
<input id="populate_major" class="element text medium" style="width:4em" type="text">
</select>
</span>
<span style="float:left">
<label>Credits Earned</label>
<input id="populate_credits_earned" class="element text medium" style="width:6em" type="text">
</span>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#studentSelect").change(function(){
var studentFirstName = $(this).val();
$.ajax({
url: 'process_ajax.php',
type: 'post',
data: {studentFirstName:studentFirstName},
dataType: 'json',
success:function(response) {
var len = response.length;
for( var i = 0; i<len; i++) {
var studentFirstName = response[i]['studentFirstName'];
var studentLastName = response[i]['studentLastName'];
var major = response[i]['major'];
var creditsEarned = response[i]['creditsEarned'];
$("#populate_first_name").val(studentFirstName);
$("#populate_last_name").val(studentLastName);
$("#populate_major").val(major);
$("#populate_credits_earned").val(creditsEarned);
}
}
});
});
});
</script>
</body>
</html>
process_ajax.php
<?php
include("config.php");
$studentName = $_POST['studentFirstName']; // department id
$sql = "SELECT * FROM student";
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ) {
if ($row['msg_id'] == $studentName) {
$studentFirstName = $row['studentFirstName'];
$studentLastName = $row['studentLastName'];
$major = $row['major'];
$creditsEarned = $row['creditsEarned'];
$users_arr[] = array("studentFirstName" => $studentFirstName, "studentLastName" => $studentLastName, "major" => $major, "creditsEarned" => $creditsEarned);
}
}
// encoding array to json format
echo json_encode($users_arr);
?>
Try it out and lemme know if it works

Get data MySQL DB and display on in HTML

How would I code into my program using PHP/JavaScript and HTML/CSS to display data from a database I made in MySQL Monitor on the blue section below:
I made buttons that use PHP to go into the database and show the data on the HTML page:
HTML:
<form action="fullridez.php" method="post">
<h4 id="Filter">GPA</h4>
<input id="FilterBox" name="gpa" type="text"/>
<h4 id="Filter">Amount</h4>
<input id="FilterBox" name="amount" type="text"/>
<h4 id="Filter">School</h4>
<input id="FilterBox" name="school" type="text"/>
<input type="submit" id="FilterBox" name="myForm" onkeypress="checkEnter()" ><img src="search.png" width=15 height=15 /></button>
</form>
<script>
</script>
PHP:
<?php
if(isset($_POST['myForm'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarshiplist";
$conn = mysqli_connect($servername, $username, $password, $database);
$gpa = $_POST['gpa'];
$amount = $_POST['amount'];
$count = "SELECT * FROM scholarships";
$result = mysqli_query($conn, $count);
if ($result->num_rows > 0) {
$sql = "SELECT * FROM scholarships WHERE GPA <= " . $gpa . " AND Amount <= "
. $amount;
if ($result = mysqli_query($conn, $sql)) {
while ($row=mysqli_fetch_row($result)) {
for($i = 0; $i < count($row); $i++) {
echo $row[$i] . '<br>';
}
}
}
} else {
echo "0 results";
}
$conn->close();
}
SQL:
USE ScholarshipList;
CREATE TABLE Scholarships
(
id int unsigned NOT NULL auto_increment,
School varchar(500) NOT NULL,
GPA decimal(10,2) NOT NULL,
Amount decimal(10,2) NOT NULL,
PRIMARY KEY (id)
);
I am using XAMPP
When I click the button on the HTML file it bring me to the PHP page and all I see is the PHP code. I don't want it to go to the page but stay on the same page showing the data below the buttons.
This is what the page looks like so far
page
What am I doing wrong?
If your HTML form is contained within the 'fullridez.php' file and you are posting the form inputs to that same file, then you need to have some PHP where you'd like to output to be checking for results and then looping through those results while echoing them out:
<table>
<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td></tr>
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<tr><td>"
. $row['col_1'] . "</td><td>"
. $row['col_2'] . "</td><td>"
. $row['col_3'] . "</td></tr>";
}
?>
</table>
You can build a wireframe div table with for loop:
<?php
$num_rows = mysql_num_rows($result);
for ($i=0;$i<$num_rows;$i++) {
//loop through all rows of data
$row = mysql_fetch_assoc($result); // your data is now: $row['fieldName']
?>
<div>
GPA <input name="" value="<?php echo($row['gpa'])?>;" type="text">
AMOUNT <input name="" value="<?php echo($row['amount'])?>;" type="text">
SCHOOL <input name="" value="<?php echo($row['school'])?>;" type="text">
</div>
<?php
} //end of the loop
?>

onClick argument of php function

I've written the code below to set a variable in mysql to either 1 or 0. But somehow whenever i click the first button (1) it's always saving the 0-value assigned to the second button in the mysql table.
<head>
<?php
function update_ziekenwagen($Status) {
$servername = "localhost";
$username = "webapp";
$password = "password";
$dbname = "spoed";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE AlgemeneVars SET value='".$Status."' WHERE id=4";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully:" . $Status;
//echo "UPDATE AlgemeneVars SET value=' " . $Status . " ' WHERE id=4";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();}
?>
</head>
<body>
<input type="button" value="Vertr" id="Vertr" name="Vertr" onclick="document.write('<?php update_ziekenwagen(1); ?>');" />
<input type="button" value="Terug" id="Terug" name="Terug" onclick="document.write('<?php update_ziekenwagen(0); ?>');" />
</body>
<head>
<?php
function update_ziekenwagen() {
$Status = $_POST['status'];
$servername = "localhost";
$username = "webapp";
$password = "sW7HwM225PxrwbZC";
$dbname = "spoed";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE AlgemeneVars SET value='".$Status."' WHERE id=4";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully:" . $Status;
//echo "UPDATE AlgemeneVars SET value=' " . $Status . " ' WHERE id=4";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
if (!empty($_POST)){
update_ziekenwagen();
}
?>
</head>
<body>
<form>
<input type="hidden" name="status" value="1" />
<input type="submit" />
</form>
<form>
<input type="hidden" name="status" value="0" />
<input type="submit" />
</form>
</body>
You can still make it work without using Ajax though using the above code. But this is NOT safe or good practice at all.

How to disable submit till only required fields are filled up

I have searched but I get info about how to disable submit button till all fields are completed....
I have following form where some fields are required and some are optional.
I want to disable submit button till required fields are completed.
sample code of form :
<form name="registration_form" id="registration_form" action="nextaction.php" method="post" enctype="multipart/form-data" >
Name : <input type="text" id="name" name="name" required>
Email : <input type="text" id="name" name="name" required>
Mobile : <input type="text" id="mobile" name="mobile" required>
Gender : <input type="text" id="gender" name="gender" >/*optional*/
Occupation : <input type="text" id="occupation" name="occupation" >/*optional*/
City : <input type="text" id="city" name="city" required>
Avatar : <input type="file" id="avatar" name="avatar" required>
<input type="submit" class="link-button-blue" id="register" value="PROCEED TO NEXT STEP" />
===========
Edited
what I have tried for submit disable untill all field completed as follows :
First Thing :
<input type="submit" class="link-button-blue" id="register" value="PROCEED TO NEXT STEP" disabled="disabled" />
script :
<script>
$(document).ready(function (){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
});
</script>
$('#registration_form input[required]').on('input propertychange paste change', function() {
var empty = $('#registration_form').find('input[required]').filter(function() {
return this.value == '';
});
$('#register').prop('disabled', (empty.length));
});
https://jsfiddle.net/ot5kn5c7/
This should work.
Anytime anything changes on any required input check for the count of required fields that are not empty. Once there are 0 required empty inputs update the disabled property for the button. (0 evaluates as false)
If you didn't to disable the button and wanted to only stop the form from submitting you would attach to the submit event on the form and just prevent the default action using similar logic checking the length.
$('form').on('submit', function(e) {
var empty = $(this).find('input[required]').filter(function() {
return this.value == '';
});
if (empty.length) {
e.preventDefault();
alert('enter all required field!')
}
});
Working solution for your case: https://jsfiddle.net/j9r5ejho/
$('form').submit(function(){
var valid = true;
$('input[required]').each(function(i, el){
if(valid && $(el).val()=='' ) valid = false;
})
return valid;
})
Untested but it should work with something like this:
(function() {
// whenever you type in a field
$('form > input').keyup(function() {
var empty = false;
// scan all fields in this form with the attribute required
$('form').find('input[required]').each(function() {
// if it's empty, cancel the loop
if ($(this).val() == '') {
empty = true;
return false;
}
});
// in case we have an empty required field,
// disable submit button
if (empty) {
$('input:submit').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})();
In order to prevent posting the form on a button or input type="submit", you can simply use e.preventDefault() which would prevent from proceeding with the default behavior.If you are using jquery validation and have a required attribute, you can just invoke $.validate() to validate the form.
$('input:submit').click(function(e)
{
if(!$.validate())
e.preventDefault();
});
example : https://jsfiddle.net/DinoMyte/suj951ga/1/
Just in case you want to try something like this. This won't disable the submit button but if you want to stop it from submitting until all required fields are fill in. This should work.
Not sure what database your using but this is for the PDO. You can just change the connection part to mysqli.
It won't submit to your database until you complete all the required fields and will also display the required input error messages.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white
space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
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 info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Success! Form Submitted!";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Use this if you want to redirect it to another page so it won't send the form again to your PDO database if they refresh it.
It won't submit to your database and will stay on the HOME.PHP page until you complete all the required fields and will also display the required input error messages while on HOME.PHP page.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
Added a "header("Location: welcome.php");" after "$conn->exec($sql);"
HOME.PHP
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
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 info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
header("Location: welcome.php");
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
WELCOME.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Success! Form Submitted!</h1>
<script type="text/javascript" src="js/main.js" ></script>
</body>
</html>

Categories