When click submit, the page turns white blank [duplicate] - php

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
I'm a student and I was given a task to make a reservation system. I'm a bit new to php so I still need some guidance, my problem here is, when I try to insert data from a form, my page turns white blank just after I clicked the submit button.
I've tried googled for answers and some answers are because there are extra/lack of brackets, extra spaces in php coding and there are also a tip to put this coding in the beginning of php code error_reporting(-1); to see what is the error but unfortunately, there are no right solutions.
By posting this I hope some of you can help me and see what's wrong with my coding.
Your help is much needed. Thank you so much in advance.
Page2.php:
<?php
session_start();
require('db.php');
include("auth.php");
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
$trn_date = date("Y-m-d H:i:s");
$checkBox = implode(',', $_POST['item']);
$microphones = $_REQUEST['microphones'];
$amplifers =$_REQUEST['amplifers'];
$loudspeakers = $_REQUEST['loudspeakers'];
$mixers =$_REQUEST['mixers'];
$catatan = $_REQUEST['catatan'];
$submittedby = $_SESSION["username"];
$ins_query="insert into pasystems
(`trn_date`,`item`,`microphones`,`amplifers`,`loudspeakers`,`mixers`,`catatan`,`submittedby`)values
('$trn_date','". $checkBox ."','$microphones','$amplifers','$loudspeakers','$mixers','$catatan','$submittedby')";
mysqli_query($con,$ins_query)
or die(mysql_error());
$status = "New Record Inserted Successfully.
</br></br><a href='view.php'>View Inserted Record</a>";
}
?>
html:
<form action="Page2.php" name="form" method="POST">
<input type="hidden" name="new" value="1" />
<ul class="errorMessages"></ul>
<div class="form-group row text-left">
<label for="example-date-input" class="col-2 col-form-label">Nama Peralatan: </label>
<div class="col-10">
<div class="form-group">
<div class="form-row">
<div class="col-md-3">
<div class="form-check text-left">
<label class="form-check-label">
<input class="form-check-input" name="item[]" type="checkbox" value="Microphones">
Microphones
</label>
</div>
</div>
<div class="">
<input class="form-control" type="number" name="microphones" value="0" id="example-number-input">
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-3">
<div class="form-check text-left">
<label class="form-check-label">
<input class="form-check-input" name="item[]" type="checkbox" value="Amplifiers">
Amplifiers
</label>
</div>
</div>
<div class="">
<input class="form-control" type="number" name="amplifiers" value="0" id="example-number-input">
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-3">
<div class="form-check text-left">
<label class="form-check-label">
<input class="form-check-input" name="item[]" type="checkbox" value="Loudspeakers">
Loudspeakers
</label>
</div>
</div>
<div class="">
<input class="form-control" type="number" name="loudspeakers" value="0" id="example-number-input">
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-3">
<div class="form-check text-left">
<label class="form-check-label">
<input class="form-check-input" name="item[]" type="checkbox" value="Mixers">
Mixers
</label>
</div>
</div>
<div class="">
<input class="form-control" type="number" name="mixers" value="0" id="example-number-input">
</div>
</div>
</div>
</div>
</div>
<div class="form-group row text-left">
<label for="exampleTextarea" class="col-2 col-form-label">Catatan: </label>
<div class="col-10">
<textarea class="form-control" name="catatan" id="exampleTextarea" rows="3"></textarea>
</div>
</div>
<p style="color:#FF0000;"><?php echo $status; ?></p>
<center><button type="submit" name="submit" class="btn btn-info">Submit</button></center>
</form>
I have edited my coding but it seems to still have a problem

Here is a solution using object oriented-styled MySQLi with prepared statements. Though, I recommend you to move to PDO instead of MySQLi. It's cleaner and better.
Here are some great tutorials for PDO and MySQLi. And, in order to activate error reporting, here is a good resource to look into: Error reporting basics.
In principle, all data access operation are implemented in the upper - php - part of the page. Fetched data is saved in arrays (like $n_anjuranItems). In the html code part you just loop through this arrays. Doing this you don't mix data access codes with html codes.
Also you should not write html codes using php.
There is a "#todo" in the code. Search for it please.
As said, I re-added the combobox "n_anjuran". The inputs catatan and n_anjuranmust be completed/selected. But try with empty/unselected values, so that you see how the error messages are displayed. You can give the inputs the required attribute in html if you wish.
You should sanitize and filter the posted values in PHP (server side). You should also validate the input values on the client side.
In html, the last insert id is appended to "View record" anchor.
I removed the checkboxes and "item" field from db table.
I redesigned html with Bootstrap 3.3.7 by my taste and wrote some comments which I hope you understand.
Normally, if no input parameters are involved, you could use mysqli::query instead of mysqli_stmt::prepare + mysqli_stmt::execute. Personally I tend to prepare the sql statements, even if I don't need to.
Good luck.
Page db.php
<?php
/*
* Enable internal report functions. This enables the exception handling,
* e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
* (mysqli_sql_exception).
*
* MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
* MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
*
* See:
* http://php.net/manual/en/class.mysqli-driver.php
* http://php.net/manual/en/mysqli-driver.report-mode.php
* http://php.net/manual/en/mysqli.constants.php
*/
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create the db connection.
$connection = new mysqli('host', 'user', 'pass', 'db');
Page page2.php
<?php
session_start();
require_once 'db.php';
require_once 'auth.php';
// #todo Delete. Just for testing.
$_SESSION['username'] = 'Tarzan';
// Flag to signalize if record saved.
$recordSaved = FALSE;
/*
* ================================
* Operations upon form submission.
* ================================
*/
if (isset($_POST['submitButton'])) {
/*
* ==========================
* Validate the input values.
* ==========================
*/
if (!isset($_POST['microphones'])) {
$errors[] = 'Please provide the microphones number.';
}
if (!isset($_POST['amplifiers'])) {
$errors[] = 'Please provide the amplifiers number.';
}
if (!isset($_POST['loudspeakers'])) {
$errors[] = 'Please provide the loudspeakers number.';
}
if (!isset($_POST['mixers'])) {
$errors[] = 'Please provide the mixers number.';
}
if (!isset($_POST['catatan']) || empty($_POST['catatan'])) {
$errors[] = 'Please provide the catatan.';
}
if (!isset($_POST['n_anjuran']) || empty($_POST['n_anjuran'])) {
$errors[] = 'Please select a n_anjuran.';
}
/*
* ======================
* Read the input values.
* ======================
*/
$trnDate = date('Y-m-d H:i:s');
$microphones = $_POST['microphones'];
$amplifiers = $_POST['amplifiers'];
$loudspeakers = $_POST['loudspeakers'];
$mixers = $_POST['mixers'];
$catatan = $_POST['catatan'];
$n_anjuran = $_POST['n_anjuran'];
$submittedBy = $_SESSION['username'];
/*
* ========================================
* Save the new record if no errors raised.
* ========================================
*/
if (!isset($errors)) {
$sql = 'INSERT INTO pasystems (
`trn_date`,
`microphones`,
`amplifiers`,
`loudspeakers`,
`mixers`,
`catatan`,
`n_anjuran`,
`submittedby`
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?
)';
// Prepare the SQL statement for execution.
$statement = $connection->prepare($sql);
/*
* Bind the variables for the parameter markers (?). The first
* argument of mysqli_stmt::bind_param is a string that contains one
* or more characters which specify the types for the corresponding bind variables.
*/
$bound = $statement->bind_param(
'siiiisis' // Bind variable types.
, $trnDate
, $microphones
, $amplifiers
, $loudspeakers
, $mixers
, $catatan
, $n_anjuran
, $submittedBy
);
// Execute the prepared statement.
$executed = $statement->execute();
// Close the prepared statement and deallocate the statement handle.
$statement->close();
// Get the last insert id.
$lastInsertId = $connection->insert_id;
// Update record saved flag.
$recordSaved = TRUE;
}
}
/*
* ==========================
* Fetch the n_anjuran items.
* ==========================
*/
$sql = 'SELECT kd_dept, desc_dept FROM koddept';
// Prepare the SQL statement for execution.
$statement = $connection->prepare($sql);
/*
* Execute the prepared statement. When executed, any parameter markers
* which exist will automatically be replaced with the appropriate data.
*/
$executed = $statement->execute();
// Get the result set from the prepared statement.
$result = $statement->get_result();
// Fetch data.
$n_anjuranItems = array();
if ($result->num_rows > 0) {
$n_anjuranItems = $result->fetch_all(MYSQLI_ASSOC);
}
/*
* Free the memory associated with the result. You should
* always free your result when it is not needed anymore.
*/
$result->close();
/*
* Close the prepared statement. It also deallocates the statement handle.
* If the statement has pending or unread results, it cancels them
* so that the next query can be executed.
*/
$statement->close();
// Close the database connection.
$connection->close();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<!-- ======================================= -->
<!-- CSS resources -->
<!-- ======================================= -->
<!-- Font-Awesome -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css" rel="stylesheet" />
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
<!-- ======================================= -->
<!-- JS resources -->
<!-- ======================================= -->
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<div class="row page-header">
<div class="col-xs-12">
<h1>
Demo
</h1>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<form name="form" action="Page2.php" method="post">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<i class="fa fa-exclamation-circle"></i> <?php echo $error; ?>
</div>
<?php
}
} elseif (isset($recordSaved) && $recordSaved) {
?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<i class="fa fa-check-circle"></i> New record successfully saved. <a href='view.php?id=<?php echo $lastInsertId; ?>'>View record</a>.
</div>
<?php
}
?>
<div class="form-group">
<label for="microphones">Microphones</label>
<input type="number" name="microphones" value="<?php echo !$recordSaved && isset($microphones) ? $microphones : 0; ?>" class="form-control">
</div>
<div class="form-group">
<label for="amplifiers">Amplifiers</label>
<input type="number" name="amplifiers" value="<?php echo !$recordSaved && isset($amplifiers) ? $amplifiers : 0; ?>" class="form-control">
</div>
<div class="form-group">
<label for="loudspeakers">Loudspeakers</label>
<input type="number" name="loudspeakers" value="<?php echo !$recordSaved && isset($loudspeakers) ? $loudspeakers : 0; ?>" class="form-control">
</div>
<div class="form-group">
<label for="mixers">Mixers</label>
<input type="number" name="mixers" value="<?php echo !$recordSaved && isset($mixers) ? $mixers : 0; ?>" class="form-control">
</div>
<div class="form-group">
<label for="catatan">Catatan *</label>
<textarea name="catatan" placeholder="Complete catatan..." rows="3" class="form-control"><?php echo !$recordSaved && isset($catatan) ? $catatan : ''; ?></textarea>
</div>
<div class="form-group">
<label for="n_anjuran">Dept/Kelab/Anjuran *</label>
<select name="n_anjuran" class="form-control">
<option value="">- SILA PILIH -</option>
<?php
if ($n_anjuranItems) {
foreach ($n_anjuranItems as $n_anjuranItem) {
$selected = (!$recordSaved && isset($n_anjuran) && $n_anjuran == $n_anjuranItem['kd_dept']) ? 'selected' : '';
?>
<option value="<?php echo $n_anjuranItem['kd_dept']; ?>" <?php echo $selected; ?>>
<?php echo $n_anjuranItem['desc_dept']; ?>
</option>
<?php
}
}
?>
</select>
</div>
<div class="form-group text-center">
<button type="submit" id="submitButton" name="submitButton" class="btn btn-success" aria-label="Submit" title="Submit">
<i class="fa fa-check" aria-hidden="true"></i> Submit
</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Used tables
CREATE TABLE `pasystems` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`trn_date` varchar(100) DEFAULT NULL,
`microphones` int(11) DEFAULT NULL,
`amplifiers` int(11) DEFAULT NULL,
`loudspeakers` int(11) DEFAULT NULL,
`mixers` int(11) DEFAULT NULL,
`catatan` varchar(100) DEFAULT NULL,
`n_anjuran` int(11) DEFAULT NULL,
`submittedby` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `koddept` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`kd_dept` int(11) DEFAULT NULL,
`desc_dept` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
Used table values
INSERT INTO `koddept` (`id`, `kd_dept`, `desc_dept`)
VALUES
(1,1,'my dept 1'),
(2,2,'my dept 2');

I don't use procedural style, so my code may have a typo in it -- I didn't test before posting. I wrote inline comments to help explain my snippet. Valid isset() syntax permits multiple variables in it. In bind() I am assuming your columns are int-type in your database so I used i, and submittedby is a varchar/string-type. This may not fix everything, but it should put you on the right path to debugging it yourself. EDIT: I just saw that you said in your comments that amplifers should be amplifiers so I've adjusted my answer.
Untested Procedural-style Code:
session_start();
require('db.php');
include("auth.php");
if(isset($_SESSION["username"],$_POST['new'],$_POST['microphones'],$_POST['amplifiers'],$_POST['loudspeakers'],$_POST['mixers'],$_POST['catatan'])){ // check superglobals
// for debugging: var_export($_SESSION); echo "<br><br>"; var_export($_POST);
if(mysqli_connect_errno()){ // check connection for an error
echo "Connection Error: ",mysqli_connect_error(); // do not echo when live
}else{
$stmt=mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt,"INSERT INTO pasystems (`trn_date`,`microphones`,`amplifiers`,`loudspeakers`,`mixers`,`catatan`,`submittedby`) VALUES
(".date("Y-m-d H:i:s").",?,?,?,?,?,?)")){ // use prepared statement with placeholders for security/reliability and check for false
echo "Statement Preparation Error: ",mysqli_stmt_error($stmt); // do not echo when public
}else{
if(!mysqli_stmt_bind_param($stmt,"iiiiis",$_POST['microphones'],$_POST['amplifiers'],$_POST['loudspeakers'],$_POST['mixers'],$_POST['catatan'],$_SESSION["username"])){ // bind superglobal values to query and check for false
echo "Statement Bind Error: ",mysqli_stmt_error($stmt); // do not echo when public
}elseif(!mysqli_stmt_execute($stmt)){ // run and check query for false
echo "Statement Bind/Execution Error: ",mysqli_stmt_error($stmt); // do not echo when public
}else{
echo "New record created successfully";
// if you have a database-generated ID... echo "<br><br><a href='view.php?ID=",mysqli_stmt_insert_id($stmt),"'>View Inserted Record</a>";
}
}
mysqli_stmt_close($stmt);
}
}else{
echo "Insufficient/Invalid Submission";
}

Related

How to insert data to database table from $_GET value on PHP

Why I can't insert into 1 field to my database table?
I loop the data of my other table to display each data and put the result to href tag so it clickable and concatenate with it's id so it will put the id result after the link like this:
<a href="scheduling.php?CID=<?php echo $rows['docID']; ?>">
Here is how I loop my data using php on page1:
<?php
$sel = "SELECT * FROM doctors ORDER BY docID";
$result = $conn->query($sel);
if($result->num_rows>0)
{
while($rows = $result->fetch_array())
{
?>
<a href="scheduling.php?CID=<?php echo $rows['docID']; ?>">
<div class="doc_item" style="width:310px; border:4px solid #009973;display:inline-block; margin-top:40px; margin-right:20px;">
<img src="images/ft-img.png" style="width: 300px;">
<div class="item-lvl" style="width: 100%; background:#009973; color:#fff; height:70px; padding-top:10px;">
<h4 style="font-size:20px; font-weight:bold;">Dr. <?php echo $rows['docFname']; ?></h4>
<span><?php echo $rows['docType']; ?></span>
</div>
<div style="width: 100%; background:#00664d;padding-top:15px; padding-bottom:20px;">
<h3 style="color:#fff;">Make a Schedule!</h3>
</div>
</div>
</a>
<?php
}
}
?>
Then I want to add the value of CID to my database table using this code on page 2:
<?php
if (isset($_POST['btn-submit'])) {
$cusID = $customerID;
$docID = $_GET['CID'];
$checkupType = $_POST['checkupType'];
$schedTime = $_POST['schedTime'];
$contact = $_POST['contact'];
$ins = "INSERT INTO schedule
(customerID, docID, checkupType, schedTime, contact)
VALUE ('$cusID','$docID','$checkupType','$schedTime','$contact')";
if($conn->query($ins)===TRUE) {
header('location:success_sched.php');
}else{
echo "SQL Query: " . $ins . "->Error: " . $conn->error;
}
}
Now, this code insert data to my database table except $docID which is the value is $_GET['CID'];
docID column is intiger.
please correct my code, this is my school project.
Form code on page 2:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div class="sign-u">
<div class="sign-up1">
<h4>Form of Checkup* :</h4>
</div>
<div class="sign-up2">
<label>
<input type="radio" value="Virtual" name="checkupType" required>
Virtual Checkup
</label>
<label>
<input type="radio" value="Facetoface" name="checkupType" required>
Face to Face Checkup
</label>
</div>
<div class="clearfix"> </div>
</div>
<p style="color:gray;">*Take note that virtual checkup will require a you stable internet for better communication.</p>
<div class="sign-u">
<div class="sign-up1">
<h4>Date and Time* :</h4>
</div>
<div class="sign-up2">
<input type="date" name="schedTime" id="date" required>
</div>
<div class="clearfix"> </div>
</div>
<p style="color:gray;">*Please provide Skype id as a contact information if <span style="color:#ff5c33">Virtual Checkup</span> is your choice.</p>
<div class="sign-u">
<div class="sign-up1">
<h4>Contact Information :</h4>
</div>
<div class="sign-up2">
<input type="text" name="contact">
</div>
<div class="clearfix"> </div>
</div>
<div class="sub_home" style="text-align: right;">
<input style="background: #339966;" type="submit" name="btn-submit" value="Submit">
<div class="clearfix"> </div>
</div>
</form>
Please understand that when you submit a form, that is a new request to the server. It has a new URL. Your page 2 form submits to $_SERVER['PHP_SELF']; - which is the current URL but without the querystring variables. Therefore your GET parameter is not passed in the form submit. (If you use the "View Source" feature of your browser to examine the "action" attribute of the form after it's rendered, you'll see exactly what URL it makes the request to when submitting. You can also see the same thing by looking at your browser's Network tool, or your webserver's access logs.)
There are a couple of ways around that, but I'd suggest adding the value as a hidden field in the form, and populating it with the value of the GET parameter during the previous request.
e.g.
<input type="hidden" value="<?php echo $_GET["CID]; ?>" name="CID">
and then in the PHP, retrieve it via $_POST like all the other variables:
$docID = $_POST['CID'];
Finally, please ensure you update your code to use prepared statements and parameters, as recommended in the comments, so that you are protected against both SQL injection attacks and unexpected syntax errors. You can get more info and examples here

Keep the form open when sending data to the table

I have this code with multiple forms within the same page:
test1 page:
<select id="mudar_produto">
<option value="#produto_1">Novo Produto Higiene</option>
<option value="#produto_2">Entrada de Produtos Higiene</option>
<option value="#produto_3">Novo Produto Nutricia</option>
</select>
<section class="hide-section" id="produto_1">
<form id="form3" action="./teste2" method="POST" onsubmit="return form_validation()">
<fieldset>
<h1>
<legend>
<center>
<strong>Produtos de Higiene</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Nome do Produto">Nome do Produto</label></strong>
<input type="text" id="DescricaoProd" name="DescricaoProd" required="" style="width:350px">
</div>
<div class="campo">
<strong><label for="Unidade">Unidade</label></strong>
<input type="text" id="DescricaoUnid" name="DescricaoUnid" style="width:160px" required="" size="120">
</div>
</fieldset>
<button type="submit" name="submit" class="botao submit">Registo</button>
</form>
</section>
<section class="hide-section" id="produto_2">
<form name="form4" action="./teste2" method="POST" onsubmit="return form_validation()">
<fieldset>
<h1>
<legend>
<center>
<strong>Entrada de Produtos de Higiene</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Data Entrada">Data Entrada</label></strong>
<input id="DataEntrada" type="date" name="DataEntrada" required="" style="width:180px" value="<?php echo date("Y-m-d");?>">
</div>
</fieldset>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Produto">Produto</label></strong>
<select id="first_dd" name="Produto" style="width:250px" required>
<option></option>
<?php
$sql = "SELECT * FROM centrodb.ProdHigieneteste WHERE Ativo = 1 ORDER BY DescricaoProd ASC";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['IDProd'].'"> '.$ln['DescricaoProd'].'</option>';
$valencia[$ln['IDProd']]=array('DescricaoUnid'=>$ln['DescricaoUnid'],'DescricaoUnid'=>$ln['DescricaoUnid']);
}
?>
</select>
</div>
<div class="campo">
<strong><label for="Unidade">Unidade</label></strong>
<select id="second_dd" name="Unid" style="width:150px" required>
<option></option>
<?php
foreach ($valencia as $key => $value) {
echo '<option data-id="'.$key.'" value="'.$value['DescricaoUnid'].'">'.$value['DescricaoUnid'].'</option>';
}
?>
</select><br>
</div>
</fieldset>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Quantidade">Quantidade</label></strong>
<input type="text" id="Quantidade" name="Quantidade" style="width:80px" required="" size="40">
</div>
<div class="campo">
<strong><label for="Preço">Preço</label></strong>
<input type="text" id="Preco" name="Preco" style="width:100px" value="0.00">
</div>
</fieldset>
<button type="submit" name="submit1" class="botao submit">Registo</button>
</form>
</section>
<section class="hide-section" id="produto_3">
<form id="form3" name="form3" action="./teste2" method="POST" onsubmit="return form_validation()" >
<fieldset>
<h1>
<legend>
<center>
<strong>Produtos de Nutricia</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Nome do Produto">Nome do Produto</label></strong>
<input type="text" id="ProdNutricia" name="ProdNutricia" style="width:350px" required="" size="120" />
</div>
</fieldset>
<button type="submit" name="submit2" class="botao submit">Registo</button>
</form>
</section>
In the page teste2 I make the insertion of the data in the table of the database:
<script language="javascript" type="text/javascript">
document.location = "teste1";
</script>
<?php
if(isset($_POST['submit'])){
$name = $_POST['DescricaoProd'];
$unid = $_POST['DescricaoUnid'];
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
<?php
if(isset($_POST['submit1'])){
$data = $_POST['DataEntrada'];
$produto = $_POST['Produto'];
$unidade = $_POST['Unid'];
$quantidade = $_POST['Quantidade'];
$preco = $_POST['Preco'];
$sql = "INSERT INTO regEntradahigieneteste (DataEntrada,Produto,Unid,Quantidade,Preco)
VALUES ('$data','$produto','$unidade','$quantidade','$preco')";
if ($conn->query($sql) === TRUE);
$sql1 = "UPDATE StockHigieneteste SET Quantidade = Quantidade +" . $quantidade . " WHERE StockHigieneteste.IDProd =" . $produto;
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
<?php
if(isset($_POST['submit2'])){
$name = $_POST['ProdNutricia'];
$sql = "INSERT INTO ProdNutriciateste (ProdNutricia)
VALUES ('$name')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockNutriciateste (ProdNutricia)
VALUES ('$name')";
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
Everything is working correctly with the insertion of data in the table, but when I do the insertion and does the header ("Location: teste1"); closes the form I was filling out and I want to keep it open, since I may have to insert several types of products on the same form.
Some explanation to start with:
I have cleaned up your HTML markup. You may have gotten the look you desired, but the markup is badly broken. A good editor will help you with making a well-formed document that validates.
I've used Bootstrap for styling. Foundation is another good choice.
JQuery is used as the basis for Javascript event monitoring and AJAX
This is not copy and paste code. It's untested; it's purpose is to point you in the right direction.
The code is commented to help you understand what it's doing.
Since this is how SO is showing the code, we start off with the javascript and the HTML:
// this delays execution until after the page has loaded
$( document ).ready(function() {
// this monitors the button, id=submit-form-1, for a click event
// and then runs the function, submitForm1()
$('#submit-form-1').on('click', function() {
submitForm('#form1');
});
// could be repeated for another form...
$('#submit-form-2').on('click', function() {
submitForm('#form2');
});
});
// this function does an AJAX call to "insert.php".
// it expects a reply in JSON.
function submitForm(whichForm) {
var datastring = $(whichForm).serialize();
// see what you're sending:
alert('You would be sending: ' + datastring);
$.ajax({
type: "POST",
url: "insert.php",
data: datastring,
dataType: "json",
success: function(data) {
if(data.status=='success') {
alert('successfully uploaded');
} else {
alert('failed to insert');
}
},
error: function() {
alert("This example can't actually connect to the PHP script, so this error appears.");
}
});
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="produto_1">
<!--
note that the form is identified with id="form1".
"id" has to be unique. Nothing else can have id="form1".
There are no action nor method attributes,
since AJAX is submitting the form contents.
-->
<form class="form-horizontal" id="form1">
<!--
field named "action" will be used in PHP script
-->
<input type="hidden" name="action" value="insert_form_1" />
<!-- use CSS for styling, not <center>, <strong>, etc. -->
<h1 class="text-center">Produtos de Higiene</h1>
<div class="form-group">
<label for="DescricaoProd" class="col-sm-2 control-label">Nome do Produto</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="DescricaoProd" name="DescricaoProd" required />
</div>
</div>
<div class="form-group">
<label for="DescricaoUnid" class="col-sm-2 control-label">Unidade</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="DescricaoUnid" name="DescricaoUnid" required />
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<!--
button type is button, not submit.
Otherwise the form will try to submit.
We want the javascript to submit, not the form.
-->
<button type="button" id="submit-form-1" class="btn btn-success">Registo</button>
</div>
</div>
</form>
</section>
<!-- set up another form in the same way... -->
<form id="form2">
<input type="hidden" name="action" value="insert_form_2" />
...
<button type="button" id="submit-form-2">submit form 2</button>
</form>
The above markup and javascript should make an AJAX POST request to insert.php, and listen for a reply.
insert.php
<?php
/**
* note: It is a good practice to NEVER have anything before the <?php tag.
*
* Always try to separate logic from presentation. This is why you should
* start with PHP on the top, and never do any output until you are done
* with processing. Better yet, have separate files for logic and presentation
*
*/
// if $_POST doesn't have ['action'] key, stop the script. Every request will have
// an action.
if(!array_key_exists('action', $_POST)) {
die("Sorry, I don't know what I'm supposed to do.");
}
// database initialization could (should) go on another page so it can be reused!
// set up PDO connection
// this section credit to https://phpdelusions.net/pdo
// use your credentials here...
$host = '127.0.0.1';
$db = 'your_db_name';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
// helpful initializations, such as default fetch is associative array
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// instantiate database
$pdo = new PDO($dsn, $user, $pass, $opt);
// end database initialization
// whenever you have to do something over again, break it out into a function
// this function prevents warnings if the variable is not present in $_POST
function get_post($var_name) {
$out = '';
if(array_key_exists($var_name,$_POST)) {
$out = $_POST[$var_name];
}
return $out;
}
// assign variables
$action = get_post('action');
$name = get_post('DescricaoProd');
$unid = get_post('DescricaoUnid');
// All output of this script is JSON, so set the header to make it so.
// There can be NO output before this!
// Not even a blank line before the <?php start tag.
header('Content-Type: application/json');
// take action based on value of "action".
if($action=='insert_form_1') {
$error = false;
$output = array('message' => 'success');
// Use placeholders, never (NEVER NEVER NEVER) php variables!
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
$pdo->prepare($query);
$result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
if(!$result) { $error = true; }
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
$pdo->prepare($query);
$result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
if(!$result) { $error = true; }
// note, I just repeated myself, so this probably should be refactored...
// send a message back to the calling AJAX:
if($error) {
$output = array('status' => 'failed');
} else {
$output = array('status' => 'success');
}
print json_encode($output);
die; // nothing more to do
}
// you could have additional actions to perform in the same script.
// or, you could use different files...
if($action=='insert_form_2') {
// do insert for form 2
}
// etc.

Even when DB has records, while trying to edit records, code does not work

I am trying to update records in 'pantry-info' table. Code goes to the if loop instead of else
The code is mentioned below, what am I doing wrong?
DB connection is:
require 'config/connectDB.php';
session_start();
$id = $_GET['id'];
$sql = 'SELECT * FROM temp WHERE'. " pan_id = '$id'";
$result = mysqli_query($conn,$sql);
Trying to read DB table values in form as follows:
<?php
if(mysqli_num_rows($result1) == 0)
{
echo '<h2>This record already exists. Do you want to delete it?</h2>';
} else { ?>
<h4>Edit the record here:</h4>
<br>
<form name="pantryinfo" id="pantryForm" method = "post" action="update.php" data-toggle="validator" role="form">
<?php while ($row = mysqli_fetch_array($result1,MYSQLI_ASSOC)) { ?>
<div class="control-group form-group">
<div class="controls">
<input type="hidden" class="form-control" id="panid" name="panid" value="<?php echo $row['pan_id'];?>">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Name</label>
<input type="text" class="form-control" id="name" name="name" value="<?php echo $row['pname'];?>" required>
<p class="help-block"></p>
</div>
</div>
</form>
<?php
}
}
?>
Similar code works fine on a different page retrieving values from another DB table. Please help. Thanks in advance.
I resolved the issue. In the SQL query I used $result as a variable and in the if-else code I was using result1.
Thank you Fred for pointing it out.

Validate Data & insert data into mysql

I am making a helpdesk page where i have page to raise a ticket. I have form where i want Issue Type & Query field to be filled mandatory & validate data for extension no. i.e it should be in no. only.
I have tried code to get it via ajax & form validation but not able to execute the code & values are not getting inserted into the mysql db.
Please Help !
Ticket.php
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Raise Ticket</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.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
// Form validation.
if ($('.validate-issue').val() === '') { $('.issue-error').fadeIn(); }
if ($('.validate-query').val() === '') { $('.query-error').fadeIn(); }
// Grab form values
var formData = {
'ename' : $('input[name=ename]').val(),
'date' : $('input[name=date]').val(),
'ext' : $('input[name=ext]').val(),
'issue' : $('select[name=issue]').val(),
'query' : $('input[name=query]').val(),
'upload' : $('input[name=upload]').val()
};
if($('.validate-issue').val().trim()) &&($('.validate-query').val().trim()){
// Ajax form submit.
$.ajax({
type: "POST",
url: "insertticket.php",
data: formData,
success: function()
{
alert('Ticket has been raised');
}
});
} else { alert('Please enter the mandatory fields'); } });
});
</script>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><h1 align="center">Helpdesk-Support</h1></div>
<hr>
<div class="panel-body" align="center">
<h2>Raise Ticket!</h2>
<form class="form-horizontal" role="form" enctype="multipart/form-data" method="post">
<div class="form-group">
<label class="control-label col-sm-2" for="text">Name:</label>
<div class="col-sm-10">
<input type="text" disabled class="form-control" id="text" name="ename" value="<?php echo ucwords($_SESSION['usr_name']); ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="date">Date:</label>
<div class="col-sm-10">
<input type="text" class="form-control" disabled id="date" name="date" value="<?php date_default_timezone_set("Asia/Calcutta"); echo date('Y-m-d H:i:s')?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="ext">Extension No.:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="ext" name="ext" placeholder="Enter Extension No.">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="issue">Issue Type:</label>
<div class="col-sm-10">
<select class="form-control" id="validate-issue" name="issue"><span class="issue-error">Enter Issue Type</span>
<option>Select an option</option>
<option>Hardware Issue</option>
<option>Network Issue</option>
<option>Software Issue</option>
<option>ERP</option>
<option>CRM</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="query">Query:</label>
<div class="col-sm-10">
<textarea rows="5" class="form-control" id="validate-query" name="query" placeholder=" Enter Query here"></textarea><span class="query-error">Enter Detailed Query</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Upload File:</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="filetoupload" name="upload" >
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<div class="panel-footer" align="center">&copy Copyright <?php echo date("Y");?></div>
</div>
</div>
</body>
</html>
insertticket.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="helpdesk"; // Database name
// Connect to server and select database.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$emp_name = mysqli_real_escape_string($conn, $_POST['ename']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$issue_type = mysqli_real_escape_string($conn, $_POST['issue']);
$query = mysqli_real_escape_string($conn, $_POST['query']);
$ext_no. = mysqli_real_escape_string($conn, $_POST['ext']);
$attachment = mysqli_real_escape_string($conn, $_POST['upload']);
$sqli="select * from user where name='$emp_name'";
$result=mysqli_query($conn,$sqli);
while($row=mysqli_fetch_array($result))
{
$emp_code=$row['emp_code'];
$dept=$row['dept'];
$location=$row['location'];
$emailid=$row['emailid'];
$contact_no.=$row['contact_no.'];
}
$sql="INSERT INTO ticket (ticket_no.,emp_code,emp_name,dept,location,emailid,contact_no.,date,issue_type,query,ext_no.,attachment)
VALUES('','$emp_code','$emp_name','$dept','$location','$emailid','$contact_no.','$date','$issue_type','$query','$ext_no.','$attachment')";
if (mysqli_query($conn,$sql))
{
echo "Record added";
}
else
{
die('Error: ' . mysqli_error());
}
?>
Your triggering your script on its first load only. You can try .submit() of jQuery.
I'm not also certain if you can upload files just by getting its content by name/class/id.
Isn't .trim() just for removing extra spaces, and not for checking content?
What is up with those dots(.) in your column names anyway?
You should use $_FILES["upload"]["name"] instead of $_POST["upload"] for getting the file name attached by the user
Where is your code for uploading the file?
You can try required attribute of HTML for the meantime:
<input required="true" type="text" disabled class="form-control" id="text" name="ename" value="<?php echo ucwords($_SESSION['usr_name']); ?>">
And why don't we try .submit() in your case:
First, we have to give a unique data attribute for your <form> by adding an id attribute.
<form id="form-submission" class="form-horizontal" role="form" enctype="multipart/form-data" method="post">
Then for your script:
$(document).ready(function(){
$("form#form-submission").submit(function(){ /* WHEN THE FORM IS SUBMITTED */
var formData = new FormData($(this)[0]); /* ALL THE DATA IS IN HERE INCLUDING THE FILE ATTACHED */
$.ajax({ /* CALL AJAX */
url: "insertticket.php", /* THE FILE WHERE THE DATA WILL GO */
type: "POST", /* TYPE OF METHOD TO BE USED TO PROCESS THE DATA */
data: formData, /* THE DATA TO BE PROCESSED */
contentType: false, /* TYPE OF DATA TO BE PASSED; FOR FILE PURPOSES THAT IS WHY IT IS SET TO FALSE */
processData: false, /* PREVENT AUTOMATIC PROCESSING */
success: function(result){ /* IF DATA IS PROCESSED SUCCESSFULLY */
alert(result); /* ALERT THE RETURNED DATA FROM inserticket.php */
}
});
return false;
});
});
You're also already using mysqli_, so its easier to convert your code to prepared statement instead.
This is your insertticket.php:
<?php
$conn = new mysqli("localhost", "root", "", "helpdesk");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT emp_code, dept, location, emailid, contact_no FROM user WHERE name = ?")){ /* PREPARE YOUR QUERY */
$stmt->bind_param("s", $_POST["ename"]); /* BIND THIS DATA TO YOUR QUERY, REPLACING ? WITH $_POST["ename"]; s STANDS FOR STRING TYPE */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($emp_code, $dept, $location, $emailid, $contact_no); /* BIND THE RESULTS TO THESE VARIABLES CORRESPONDINGLY */
$stmt->fetch(); /* FETCH THE RESULT */
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
if($stmt = $con->prepare("INSERT INTO ticket (emp_code, emp_name, dept, location, emailid, contact_no, date, issue_type, query, ext_no, attachment) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")){
$stmt->bind_param("sssssssssss", $emp_code, $_POST["ename"], $dept, $location, $emailid, $contact_no, $_POST["date"], $_POST["issue"], $_POST["query"], $_POST["ext"], $_FILES["upload"]["name"]);
$stmt->execute();
$stmt->close();
echo 'Record added';
}
move_upload_file($_FILES["upload"]["tmp_name"], "/system/uploads/".$_FILES["upload"]["name"]); /* UPLOAD THE FILE TO /system/uploads/ FOLDER; JUST REPLACE YOUR DESIRED DIRECTORY */
?>
Always take a look at your browser's console log for errors
You should also consider renaming the uploaded file by the user through your code so that it will be unique inside your folder and database. To prevent duplicate file name that would lead to overwriting of files

How to change class after the user has stopped typing?

So I have this form set-up which looks exactly like this : http://i.imgur.com/z8zI2aJ.png The thing I am trying to do is change the form field's class after the user has stopped typing, as shown below after checking in my database if the username/email already exists. This should be done without reloading the page. How can I do this? Preferably with jQuery's (ajax?)
register.php
<?php
require_once 'connect.inc.php';
require_once 'core.inc.php';
?>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="styles.css" type="text/css">
<link rel="stylesheet" href="animate.min.css">
</head>
<body>
<div class="container">
<div class="middlebox">
<h1 class="logo">codeforum+</h1>
<h3 class="welcometext">Create an account on codeforum+</h3>
<h6>Please fill out all the provided fields to continue with your registration.</h6>
<h6 style="font-size:10px;">Note : You can only register once on this forum, so make it count. Any further registrations will be prohibited, because your IP address will be in our database.</h6>
<hr class="linestyle">
<form action="" method="post">
<div class="form-group">
<div id="username_form" class="input-group <?php // IF USERNAME EXISTS ADD CLASS 'has-warning' ELSE ADD 'has-success' ?>">
<span class="input-group-addon"><i class="fa fa-user fa-fw"></i></span>
<input class="form-control" type="text" placeholder="Enter your username here..." name="username">
</div>
</div>
<div class="form-group">
<div class="input-group <?php // IF EMAIL EXISTS ADD CLASS 'has-warning' ELSE ADD 'has-success' ?> ">
<span class="input-group-addon"><i class="fa fa-envelope fa-fw"></i></span>
<input class="form-control" type="text" placeholder="Enter your email here..." name="email">
</div>
</div>
<div class="form-group">
<div class="input-group <?php // IF PASSWORD HAS NUMBERS,LETTERS, ETC.. ADD CLASS 'has-warning' ELSE ADD 'has-success' ?> ">
<span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
<input class="form-control" type="text" placeholder="Enter your password here..." name="password">
</div>
</div>
<div class="form-group">
<div class="input-group <?php // IF THIS MATCHES THE PASSWORD ADD CLASS 'has-warning' ELSE ADD 'has-success' ?> ">
<span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
<input class="form-control" type="text" placeholder="Retype your password here..." name="password_retype">
</div>
</div>
<hr class="linestyle">
<p>Which comparison operator is used to compare variables/values in PHP?</p>
<div class="form-group">
<input class="form-control" type="text" placeholder="Answer the question here..." name="question">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="checkbox">I agree to the rules of this forum.
</label>
</div>
<p class="rules" style="font-size:10px;">Breaking the rules by any means will result in a permanent ban.</p>
<input class="btn btn-success fullwidth" type="submit" value="Register">
</form>
<?php
if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['password_retype']) && isset($_POST['question']) && isset($_POST['checkbox'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$password_retype = $_POST['password_retype'];
$question = $_POST['question'];
$checkbox = $_POST['checkbox'];
if(!empty($username) && !empty($email) && !empty($password) && !empty($password_retype) && !empty($question) && !empty($checkbox)) {
$sql = "SELECT id FROM users WHERE username='$username'";
if($sql_run = mysql_query($sql)) {
$sql_num_rows = mysql_num_rows($sql_run);
if($sql_num_rows==1) {
// if username exists change class of the form
} else {
// if username doesnt exist - continue
$sql = "SELECT id FROM users WHERE email='$email'";
if($sql_run = mysql_query($sql)) {
$sql_num_rows = mysql_num_rows($sql_run);
if($sql_num_rows==1) {
// if email exists change class of the form
} else {
// if email doesnt exist - continue
}
} else {
// if query failed
}
}
} else {
// if query failed
}
} else {
// if fields are empty
}
}
?>
<p class="small" style="margin-top:10px;">Already have an account?</p>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
connect.php
<?php
$mysql_error = mysql_error(); // change to 404 when finished
$mysql_database = 'codeforum';
$mysql_host = '127.0.0.1';
$mysql_user = 'root';
$mysql_pass = '';
if(!mysql_connect($mysql_host, $mysql_user, $mysql_pass) || !mysql_select_db($mysql_database)) {
die($mysql_error);
}
?>
Your question might have been easier to answer if you took more time to reduce it to a manageable scenario, but here you go anyway:
you'll need a PHP endpoint that checks for username availability.
to prevent that endpoint abuse, you'll need to require a PHP session, and store the number of attempts in the last 20 minutes or so in that. If there are too many attempts for your liking it should error out.
you'll need a JS handler for making an AJAX request to above endpoint; it will apply your className if the endpoint didn't respond with a error.
hook up your JS to fire on "change" and use a helper function to setTimeout to do the same on "keyup", so you don't hammer your PHP endpoint every time the user releases a key but rather only after a grace period, of say 100ms.
go back and implement informative messages for your error conditions, such as "name exists", and "too many attempts".

Categories