How do i stop my page from submitting on first load? - php

When i first enter my form it calls my php function and displays the error for entering a blank. How do i stop that and only call the function when i submit and not on page load? I feel like i need to do a "if(isset" somewhere but i can't figure it out.
<head>
<html>
<center>
<body onLoad="document.chip_insert.chip_number.focus()";>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function validateName(){
var x=document.forms["chip_insert"]["order_number"].value;
if (x.length<=10) {
document.forms["chip_insert"]["order_number"].focus();
document.getElementById("order_number").style.border='3px solid red';
document.getElementById("erron").innerHTML = "Invalid";
return false
}
if (x.length=11) {
document.getElementById("order_number").style.border='1px solid black';
document.getElementById("erron").innerHTML = "";
}
if (x==null || x=="")
{
document.forms["chip_insert"]["order_number"].focus();
document.getElementById("order_number").style.border='3px solid red';
document.getElementById("erron").innerHTML = "Invalid";
return false;
}
}
function validateForm(){
var y=document.forms["chip_insert"]["chip_number"].value;
if (y.length<=14) {
document.forms["chip_insert"]["chip_number"].focus();
document.getElementById("chip_number").style.border='3px solid red';
document.getElementById("errcn").innerHTML = "Invalid";
return false
}
if (y==null || y=="")
{
document.forms["chip_insert"]["chip_number"].focus();
document.getElementById("chip_number").style.border='3px solid red';
document.getElementById("errcn").innerHTML = "Invalid";
return false;
}
}
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function isaNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
window.addEventListener('keydown', keydownCallback);
function tabOnEnter(field, event) {
if (event.keyCode === 13) {
if (event.preventDefault) {
event.preventDefault();
} else if (event.stopPropagation) {
event.stopPropagation();
} else {
event.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function keydownCallback(event) {
if (event.keyCode === 191) {
setTimeout(setFocusToTextBox);
}
}
function setFocusToTextBox() {
document.getElementById("order_number").focus();
document.forms["chip_insert"]["order_number"].value="";
document.forms["chip_insert"]["chip_number"].value="";
if (event.preventDefault) {
event.preventDefault();
} else if (event.stopPropagation) {
event.stopPropagation();
} else {
event.returnValue = false;
}
}
</script>
</center>
<center>
<div
style="width:1000px;
height:300px;
border:6px ridge
blue;">
<?php
$value = "";
if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
?>
</script>
<style>
h1 {
font-size: 22pt;
font-family: verdana;
}
</style>
<h1>Jeffers HomeAgain Microchip Entry</h1>
<style>
body {
background-image: url("http://JVSIntranet/microchip/image.jpg");
}
</style>
<form name="chip_insert" id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post" onkeydown="keydownCallback(event)">
<label style="font-size:18pt; color:blue; font-family:verdana;" for="order_number">Order Number</label><br>
<input tabindex="1" style="height:40px;font-size:16pt; font-family:verdana;" maxlength="11" type="text" name="order_number" onblur="validateName(order_number)" id="order_number" value="<?php echo $value; ?>" onkeypress="return isNumber(event)" required="required" onkeydown="return tabOnEnter(this, event)" onfocus="this.focus();this.select()" /><span id="erron"></span> <br /><br />
<label style="font-size:18pt; color:blue; font-family:verdana;" for="chip_number">Chip Number</label><br>
<input tabindex="2" style="height:40px;font-size:16pt; font-family:verdana;" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" onkeydown="validateName()" onfocus="this.focus();this.select()" onkeypress="return isaNumber(event)" /><span id="errcn"></span> <br /><br />
<input tabindex="7" type="submit" value="Enter" />
</form>
</center>
<center>
<style>
font { color: red; font-size: 25pt; font-family: verdana; }
</style>
<font>
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname"
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MICROCHIP_TBL (chip_number,order_number)
VALUES
('$_POST[chip_number]','$_POST[order_number]')";
if (!mysqli_query($conn, $sql)) {
echo "ERROR: NUMBER IS ALREADY IN DATABASE! SCAN YOUR CHIP NUMBER AGAIN!";
}
mysqli_close($conn);
?>
</center>
</font>
<center>
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqli = "SELECT * FROM MICROCHIP_TBL ORDER BY entry_date desc LIMIT 20";
$result = $conn->query($sqli);
if ($result->num_rows > 5) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " " . $row["entry_date"] . "::You scanned Order Number--" . $row["order_number"] . "--with Chip Number--" . $row["chip_number"]. "<br>";
}
}else{
echo "0 results";
}
$conn->close();
?>
</center>
</div>
</body>
</head>
</html>

You can do:
if (isset($_POST['submit'])) {
// code to execute on submit
} else {
// code to execute on first request
}
// code to always execute
That's assuming that 'submit' is the name of your submit button, and the form method is post.

One method I see there is to put a hidden field into the form for example:
<input type="hidden" name="IsSubmitted" id="IsSubmitted" value="1" />
Then in your code you check:
if (isset($_POST["IsSubmitted"]) && $_POST["IsSubmitted"] != "")
{
// Do you stuff
}

Related

Ajax call not replacing the content

What I want to do is replace the content of a div after a log in with a welcome message. I've read AJAX tutorials but I might've got it wrong.
Isn't the logIn function supposed to change the content of the element with the given id, with the content echoed by the php file?
Because right now, the log in is done but the content echoed by the php file is displayed in login.php instead of replacing the content of my "user_panel" div.
My html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My awesome blog!</title>
<script>
function logIn(u,p) {
if (u== "" && p== "") {
document.getElementById("user_panel").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("user_panel").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","login.php?u="+u+"&p="+p,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div class="nav">
<div class="container">
<div id="user_panel">
<ul>
<li>Login</li>
<li>Register</li>
</ul>
</div>
</div>
</div>
<form class="login" action="login.php" method="post">
<label class="login_label" for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label class="login_label" for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<input type="submit" value="Login" onclick="logIn(document.getElementById('username'),document.getElementById('password'))">
</form>
</body>
</html>
my php
<?php
$server = "localhost";
$username = "root";
$password = "123456";
$dbname = "BlogDb";
// Create connection
$con = mysqli_connect($server, $username, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully2";
$u = $_POST['username'];
$p = $_POST['password'];
setcookie("User_in", $u, time() + (86400 * 30), "/");
// Set session variables
$_SESSION["user_on"] = $u;
$sql= "SELECT username,is_admin FROM User WHERE username ='".$u."' and password='".$p."'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<ul>";
echo "<li>";
echo "Welcome " . $row['username'] . "! How are you today?";
echo "</li><li>";
echo "<a href=logout.php>Log out</a>";
echo "</li></ul>";
}
mysqli_close($con);
?>
What am I doing wrong here?
the input type='sumbit' when clicked where submit this form so you must prevent this default event you can change this type='button'!
document.getElementById('username') where return node n't input value get input value can use
document.getElementById('username').value
below is my change code:
html:
<input type="submit" value="Login" onclick="logIn()">
js:
function logIn(e) {
e = e || window.event;
e.preventDefault();
var u = document.getElementById('username').value,
p = document.getElementById('password').value;
if (u== "" && p== "") {
document.getElementById("user_panel").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("user_panel").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","login.php?u="+u+"&p="+p,true);
xmlhttp.send();
}
}
*** This is a comment as I don't have access to the comment section I am adding as answer******
Hi Matt,
If Ajax is used there is no need to use html-->input-->submit. Use a <button> tag
and then invoke the js function.

keeping first field in html form after submitting then have a master submit button after someone is done with the first field

I am currently using this php form to submit into our mySQL database with a "chip_number" and "order_number" also with a date and time stamp. We want to use this with no keyboard or mouse, just a scanner. Currently it tabs the first field and when the second field is scanned the form is submitted, which is working as intended but it completely starts the form over, i would like it to keep the first field (order_number) after submitting so we can scan multiple "chip_numbers" on the same "order_number" then have a Master submit button if you will to send it all through when the employee is done with that order number and start with a blank form. This is the script i am using. thanks to all in advance!
<!-- Insert -->
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MICROCHIP_TBL (chip_number,order_number)
VALUES
('$_POST[chip_number]','$_POST[order_number]')";
IF (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: TRY AGAIN HUMAN!";
}
mysqli_close($conn);
?>
<html>
<head>
<!-- Validate form function -->
<!--<script type="text/javascript">
// function validateForm()
// {
// var x=document.forms["chip_insert"]["order_number"].value;
// var y=document.forms["chip_insert"]["chip_number"].value;
// if (x==null || x=="")
// {
// alert("Please enter an Order Number.");
// document.forms["chip_insert"]["order_number"].focus();
// return false;
// }
// if (y==null || y=="")
// {
// alert("Please enter a Microchip Number.");
// document.forms["chip_insert"]["chip_number"].focus();
// return false;
// }
// }
</script>
-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
</script>
</head>
<body onLoad="document.chip_insert.order_number.focus();">
<center>
<h1>Jeffers HomeAgain Microchip Entry</h1>
<form name="chip_insert" id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post">
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
Tag Number: <input tabindex="2" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" /><br /><br />
<input tabindex="7" type="submit" />
</center>
</form>
header('Location: http://JVSIntranet/microchip/homeagain.php');
This code redirects back to the form, I guess. You should add the ordernumber so it can be picked up by the form.
$ordernr = $_POST['order_number'];
header("Location: http://JVSIntranet/microchip/homeagain.php?order_number=$ordernr"); //mark the double quotes
in your form code you will have to use something like
<?php $value = (isset($_GET['order_number'])) ? " value=$_GET['order_number'] " : ""; ?>
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" <?php echo $value; ?> required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
I finally got it. i had to take out the Return function from my form and i added this to my script:
$value = "";
if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
then i put this in my input line and it works fine:
value="<?php echo $value; ?>"

adding information to mysql database

Before i proceed, i would like to say i am a beginner and i am trying to validate a form using ajax, for username availability. Validations are done. But, everytime the page gets redirected to the form action page (Even if there are errors). I want, if there are errors i get a alert message and if no errors then data is written to db. I have been trying this for quite some time but i think i messed up and i dont understand what is wrong. Please, correct my mistakes. I am just trying to learn. What i am doing wrong here and what should i do?
registration.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--<link rel="stylesheet" type="text/css" href="css/style.css"/>-->
<title>Using AJAX</title>
<script type="text/javascript" src="jquery-2.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#txtUsr').on('keyup', function(){
var username=$("#txtUsr").val();
var user_name_avail_result=$('.check');
var userCorrect=true;
if(username.length>2)
{
$.ajax({
type : 'POST',
cache:'false',
data : "username="+username,
url : "usr_available.php",
beforeSend: function()
{
user_name_avail_result.fadeIn(1000).html('<img src="green_ajax-loader.gif" /> ');
},
success: function(responseText) {
if(responseText == 200)
{
$(".check").html("<img src='available.png'/><span style='color:#59b200;'>Username available</span>");
}
else if(responseText ==201)
{
$(".check").html("<img src='not-available.png'/><span style='color:#ff0033;'>Username not available</span>");
userCorrect=false;
}
else if(responseText==202)
{
$(".check").html("Username too short");
userCorrect=false;
}
}
});
}
else
{
user_name_avail_result.html('<span style="color:#e50000;">Name too Short!</span>');
userCorrect=false;
}
if(username.length == 0) {
user_name_avail_result.html("");
userCorrect=false;
}
var exprUsr=/(^[A-Za-z][A-Za-z0-9]*([._-][a-z0-9]+){3,15})$/;
if(!exprUsr.test(username))
{
userCorrect=false;
}
});
$("#txtPwd").on('keyup',function(){
var regPwd=/^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,12})+$/;
var passTxt=$('#txtPwd').val();
var pwdCorrect=true;
if(!regPwd.test(passTxt))
{
$(".chkPwd").html('<div style="width:200px; height:80px; margin-left:190px; margin-top:-20px; text-align:left;"><span style="font-size:small; color:#ff0033;">Password must contain at least one digit, one lowercase, one uppdercase and one special character</span></div>');
pwdCorrect=false;
}
else
{
$(".chkPwd").html("");
}
if(passTxt.length==0)
{
$(".chkPwd").html("You Must Enter a Password");
pwdCorrect=false;
}
});
$("#txtUsr,#txtPwd,#txtMob").keydown(function(e) { <!-- Dont allow users to enter spaces for their username and passwords and Mobile Number-->
if (e.which == 32) {
return false;
}
});
$("#txtMob").keydown(function(e){<!--No other keys except number keys and backspace and tab work-->
if(e.which==8 || e.which==9)
return true;
if(e.which<48 || e.which>57)
return false;
});
$("#txtMob").on('keyup',function(){
var exprMob=/^[789]\d{9}$/;
var mobNum=$('#txtMob').val();
var mobCorrect=true;
if(!exprMob.test(mobNum))
{
if(mobNum.length<10)
{
$("#span3").html("Number must be minimum 10 characters long");
mobCorrect=false;
}
else
{
$("#span3").html("Number in wrong format");
mobCorrect=false;
}
}
else
{
$("#span3").html("");
}
});
function Validation(n){
if(userCorrect==false || pwdCorrect==false || window.mobCorrect==false)
{
alert("One or More field(s) is/are unfinished/empty. Please re-check.");
return false;
}
else
{
return true;
}
}
});
</script>
<script type="text/javascript">
function clearAll()
{
document.getElementById("txtUsr").value="";
document.getElementById("txtPwd").value="";
document.getElementById("txtMob").value="";
}
</script>
<style>
.chkPwd
{
margin-left:80px;
}
.check
{
margin-left:90px;
}
.form
{
margin:auto;
text-align:center;
font-family:Consolas;
font-size:medium;
}
.texts
{
font-family:Consolas;
}
#userDiv
{
background-color:#ccdbff;
height:320px;
width:500px;
border-radius:10px;
opacity:0.8;
}
#mainBody
{
background-color:#7a7acc;
width:100%;
height:100%;
}
</style>
</head>
<body class="form" id="mainBody">
<h1 style="color:#bfff00;">Registration</h1><br>
<form class="form" id="regForm" action="registration_success.php" method="POST" onsubmit="return Validation(this)">
<div class="form" id="userDiv"><br><br>
Username: <input class="texts" id="txtUsr" name="txtUsr" type="text" placeholder="Type user name here" autocomplete="off" maxlength="15" autofocus="autofocus" title="Please dont enter an aweful username!"/><br>
<span id="span1" class="check" style="font-size:small; color:"></span>
<br>
Password: <input type="password" id="txtPwd" class="texts" name="txtPwd" placeholder="Type password here" autocomplete="off" maxlength="12" title="Password must contain at least one digit, one lowercase, one uppdercase and one special character"/><br>
<span id="span2" class="chkPwd" style="font-size:small; color:red;">Min 6 and Max 12 Characters</span><br>
MobileNo.:<input type="text" maxlength="10" id="txtMob" class="texts" name="txtMob" placeholder="Enter your mobile number here" autocomplete="off" title="Please enter numbers only"/><br>
<span id="span3" class="chkMob" style="font-size:small; margin-left:10px; color:#ff0033; font-size:small;"></span><br>
<pre class="texts"> <input type="button" value="Back To LogIn" id="register" class="texts" name="register"/> <input type="submit" value="Submit" id="submit" class="texts" name="send"/> <input type="button" value="Reset" id="clear" onclick="clearAll()"/></pre>
</div>
</form>
</body>
</html>
user_available.php
<?php
if($_SERVER['REQUEST_METHOD']==='POST'){
if(!empty($_POST['username'])){
mysql_connect("localhost", "root","") or die ("Oops! Server not connected"); // Connect to the host
mysql_select_db("db_chkAJAX") or die ("Oops! DB not connected"); // select the database
// Check for the username posted
$username= mysql_real_escape_string($_POST["username"]); // Get the username values & prevent SQL-Injection
if(strlen($username)>2){
$check_query= mysql_query('SELECT Username FROM LoginRecord WHERE Username = "'.$username.'" ') or die("Cannot get data from table"); // Check the database
if(mysql_num_rows($check_query)<1){ // check num or rows 0 or greater than 0
echo 200;//Username doesnot exist in database
}
else{
echo 201;//Username exists in databse
}
} else {
echo 202;//Too short username
}
}
mysql_close($link);
return;//Stop execution
}
?>
registration_success.php
<!--Writing to the database-->
<?php
if(isset($_POST['send']) && !empty($_POST['txtUsr']) && !empty($_POST['txtPwd']) && !empty($_POST['txtMob']))
{
//Connecting to databse
$usr_name=test_input(strtolower($_POST['txtUsr']));
$pwd=$_POST['txtPwd'];
$mob=test_input($_POST['txtMob']);
$db_host='localhost';
$db_user='root';
$db_pwd='';
$conn=mysql_connect($db_host, $db_user, $db_pwd,true);
if(!$conn)
{
echo "Database connection Unsuccessful".mysql_error($conn)."<br>";
}
else
{
echo "Database connection Successful"."<br>";
}
//Creating a new database
$sql="CREATE DATABASE IF NOT EXISTS db_chkAJAX";
if (mysql_query($sql,$conn))
{
echo "Database db_student created successfully"."<br>";
}
else
{
echo "Error creating database: "."<br>";
}
//Creating a Table
$dataselect=mysql_select_db("db_chkAJAX",$conn);
if(!$dataselect)
{
die("Database not Selected".mysql_error()."<br>");
}
else
{
echo "Database Selected"."<br>";
}
$sql_create="CREATE TABLE IF NOT EXISTS LoginRecord (Username varchar (50), Password varchar(15), MobileNumber bigint(10))";
$qry=mysql_query($sql_create);
if(!$qry)
{
die("Table not created".mysql_error()."<br>");
}
else
{
echo "Table Created Successfully"."<br>";
}
//Inserting values into table
$data_insert="INSERT INTO LoginRecord(Username, Password, MobileNumber) VALUES('$usr_name', '$pwd', '$mob')";
$data_insert_query=mysql_query($data_insert);
if(!$data_insert_query)
{
die(" Unsuccessful data Insertion into table".mysql_error()."<br>");
}
else
{
echo "Data inserted into table successfully"."<br>";
}
//Closing the connection
mysql_close($conn);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
One problem, you are using html comments in your javascript instead of javascript comments, use //
http://www.jshint.com
Also, It looks like you need to set the check variables as global, since you are validating outside of the function that checks if they are valid.
I don't think you need to put this inside of Validate()
http://www.w3schools.com/js/js_form_validation.asp

PHP and AJAX registration form for start page

I am learning to create a social ntwk. I hv used an AJAX framework for the signup page and it wked. Now I am trying to use the same framewk for the start page . Its nt wking. The problems are with the gender conditionals. The submit button does nt click.Hw cn I fix this code so that form submits whn user is either male or female
}
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$gender = $row["gender"];
}
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["f"])){
// CONNECT TO THE DATABASE
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$f = preg_replace('#[^a-z0-9]#i', '', $_POST['f']);
$l = preg_replace('#[^a-z0-9]#i', '', $_POST['l']);
$wt= preg_replace('#[^a-z ]#i', '', $_POST['wt']);
$a= preg_replace('#[^a-z ]#i', '', $_POST['a']);
$ws= preg_replace('#[^a-z ]#i', '', $_POST['ws']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// FORM DATA ERROR HANDLING
if($f == "" || $l == "" || $wt || $a == "" || $ws || $c == "" ){
echo "The form submission is missing values.";
exit();
} else {
// Add user info into the database table for the main site table
$sql = "UPDATE users SET firstname='$f', lastname ='$l', wagsbooty ='$wt', abs ='$a', wagsboobs ='$ws', crash ='$c' WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
echo "startup_success";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
<style type="text/css">
#startupform{
margin-top:24px;
}
#startupform > div {
margin-top: 12px;
}
#startupform > input,select {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
#startupbtn {
font-size:18px;
padding: 12px;
}
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function startup(){
var f = _("firstname").value;
var l = _("lastname").value;
var wt = _("wagsbooty").value;
var a = _("abs").value;
var ws = _("wagsboobs").value;
var c = _("crash").value;
var status = _("status");
if(f == "" || l == "" wt || a == "" || ws || c == "" ){
status.innerHTML = "Fill out all of the form data";
} else {
_("startupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "start_page1.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "startup_success"){
status.innerHTML = ajax.responseText;
_("startupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("startupform").innerHTML = "OK!";
}
}
}
ajax.send("f="+f+"&l="+l+"&wt="+wt+"&a="+a+"&ws="+ws+"&c="+c);
}
}
</script>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<h3>Fill in this form to create your profile!</h3>
<form name="startupform" id="startupform" onsubmit="return false;">
<div>Firstname: </div>
<input id="firstname" type="text" onfocus="emptyElement('status')" maxlength="16">
<br /><br />
<div>Lastname: </div>
<input id="lastname" type="text" onfocus="emptyElement('status')" maxlength="16">
<br /><br />
<div>
<?php
if($gender === 'm'){
echo "WAG with hottest booty :";?></br>
<select id="wagsbooty" onfocus="emptyElement('status')" maxlength="255">
<?php include_once("template_wags_list.php");
}else{
echo "Star with hottest abs:";?></br>
<select id="abs" onfocus="emptyElement('status')" maxlength="255">
<?php include_once("template_abs_list.php");
}
?>
</select>
</div>
</br>
<div>
<?php
if($gender === 'm'){
echo "WAG with hottest boobs :";?></br>
<select id="wagsboobs" onfocus = "emptyElement('status')" maxlength="255">
<?php include_once("template_boobs_list.php");
}else{
echo "I have a crash on :";?></br>
<select id="crash" onfocus ="emptyElement('status')" maxlength="255">
<?php include_once("template_crash_list.php");
}
?>
</div>
</select>
</br>
</br>
<button id="startupbtn" onclick="startup()">Create Profile</button>
<span id="status"></span>
</form>
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>
You don't have anywhere on the page for the user to select their gender within the page - you should add either a radio button or a select box to the page and pass that info to the startup() function.

Connecting HTML page with MySQL using PHP

This is my code to connect a page to a database (MySQL):
<html>
<body>
<title>Home</title>
<script language="javascript">
function checkTextField(field) {
if (field.value == '') {
alert("Field is empty");
}
}
function a(id) {
var ay = document.getElementById(id).value;
var pattern = /\d{4}-\d{2,4}/;
if(pattern.test(ay))
{
ay.style.backgroundColor="#52F40C";
return true;
}
else
{
window.alert ("Enter in YYYY-YY or YYYY-YYYY format");
ay.style.backgroundColor="red";
ay.focus();
ay.value="";
return false;
}
}
function c()
{
var n=document.getElementById("name");
var re=/^[a-zA-Z]+ ?[a-zA-Z]*$/;
if(re.test(n.value))
{
n.style.backgroundColor="#52F40C";
}
else
{
window.alert("Invalid place name");
n.style.backgroundColor="#F40C0C";
n.focus();
n.value="";
}
}
function d()
{
var n= document.getElementById("date");
var re=/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/;
if (re.test(n.value))
{
n.style.backgroundColor="#52F40C";
}
else
{
window.alert("enter in MM DD YYYY format");
n.style.backgroundColor="#F40C0C";
n.focus();
n.value="";
}
}
</script>
<body style="background-color:#708090;">
<?php
if (isset($_POST['submit']))
{
$mysqli= new mysqli("localhost","admin","admin", "nba" );
if($mysqli === false)
{
die("could not connect:" . mysqli_connect_error());
}
if ($inputError != true && empty($_POST['ayear']) )
{
echo 'ERROR: Please enter a valid year';
$inputError = true;
}
else
{
$ayear = $mysqli-> escape_string($_POST['ayear']);
}
if ($inputError != true && empty($_POST['fyear']) )
{
echo 'ERROR: Please enter a valid year';
$inputError = true;
}
else
{
$fyear = $mysqli-> escape_string($_POST['fyear']);
}
if ($inputError != true)
{
$sql="INSERT INTO year VALUES ('$ayear','$fyear')";
if ($mysqli-> query($sql)==true)
{
echo'Added';
}
else
{
echo"ERROR: Could not execute query : $sql. " . $mysqli-> error;
}
}
$mysqli-> close();
}
?>
<h1 style="font-family:Verdana;text-align:center;">National Board of Accrediation <br>of<br> Programme</h1>
<br>
<div id="menu" style="background-color:#800000;height:25px;width:1000px">
<b><font "style="font-family:Verdana">Part I&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspPart II&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspPart III&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspPart IV</font></b>
</div>
</p>
<h4 style="font-family:Verdana;text-align:center;"><b><u>Declaration</u></b></h4>
<form method="post" action="home.html">
<p> (<input type="text" size="9" name="ayear" id="ayear" onChange="a('ayear');" onBlur="checkTextField(this);">) (<input type="text" size="9" name="fyear" id="fyear" onChange="a('fyear');" onBlur="checkTextField(this);">).</p>
<p>Place:<input type="text" size="20" name="name" id="name" onChange="c();" onBlur="checkTextField(this);"></p>
<p>Date:<input type="text" size="10" name="date" id="date" onChange="d();" onBlur="checkTextField(this);">
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
The database connection is not working. How can I fix this? What is the problem with the code?
Unless you've set HTML to be executed like PHP code, none of your dynamic code will work.
Save a copy of that file with a .php extension and test if it works.
Change your file Extension to .php
And furthermore on your Form Action include a PHP extetention. like below
<form method="post" action="home.php">
Besides the other suggestions, I see that you have put a 'space' after -> on several locations;
e.g.
$mysqli-> escape_string($_POST['ayear']);
Should be
$mysqli->escape_string($_POST['ayear']);
Why you are trying to execute your php code in HTMl
Save your file wth .php extension definitely it will work.

Categories