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">© 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
Related
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.
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";
}
I am a little stuck at the moment and could use some help please.
I have a calendar which is being used by multiple departments to enter their schedule in. Each user is asked to complete 1x select and 2x input fields which are divided into FORM 1 and FORM 2
FORM 1:
department code (onclick submit event)
FORM 2:
name
date
submit button
After the user has selected his/her department code, the calendar will refresh and fetch the entries for this specific department only (meaning it will filter all records for the department code). After that, the user has to enter his username and select a date, followed by pressing the submit button (form 2).
Now, the problem is that in order for FORM 2 to submit correctly, I need to know the department code from Form 1. Additionally, I am having troubles preventing the calendar from refreshing (Form 1) when pressing the submit button for Form 2.
In short, how can I clearly distinguish the ($_POST) between form 1 and form 2, while accessing both form's data?
PHP
<?php
// SHOULD BE EXECUTED AFTER THE SUBMIT BUTTON WAS CLICKED
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['type']) && ($_POST['type']=='new_entry')) {
// include connection details
include '../../plugins/MySQL/connect_db.php';
// Open a new connection to the MySQL server
$con = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
// Output any connection error
if ($con->connect_error) {
die('Error : ('. $con->connect_errno .') '. $con->connect_error);
}
// define variables
$table = 'calendar';
$type = mysqli_real_escape_string($con,$_POST['type']);
$holidex = mysqli_real_escape_string($con,$_POST['holidex']);
if($type == 'new_entry')
{
// define variables and query
$mod_property = mysqli_real_escape_string($con,$_POST['holidex']);
$mod_name = mysqli_real_escape_string($con,$_POST['mod_name']);
$mod_date = date('Y-m-d',strtotime($_POST['mod_date']));
$sql = "INSERT INTO calendar (`title`, `startdate`, `enddate`, `allDay`, `color`, `holidex`) VALUES ('$mod_name','$mod_date','$mod_date','true','','$mod_property')";
print($sql);
$result = $con->query($sql) or die('<p>Could not submit new MOD record into database: ' . MYSQLI_ERROR() . '</p>');
$result->free();
}
$con->close();
}
?>
<form name="form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<!-- <form name="mod_form" action="../../plugins/MySQL/ajax_action.php?type=new_entry" method="POST"> -->
<!-- Property -->
<div class="col-md-4">
<label>Property</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-server"></i></span>
<select name="holidex" id="holidex" class="form-control select2" style="width: 100%;" data-placeholder="Select your property" onchange="this.form.submit();" method="POST" <?php if($_SESSION['Access']=='User') { echo "disabled"; } ?>>
// get all my departments and their respective codes
<option value="1">Dept. 1</option>
<option value="2">Dept. 2</option>
<option value="3">Dept. 3</option>
</select>
</div>
<!-- /btn-group -->
</div>
<!-- /.property -->
</form>
<form name="form2" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<!-- MOD Name -->
<div class="col-md-4">
<label>MOD Name</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<select name="mod_name" id="mod_name" class="form-control select2" style="width: 100%;" data-placeholder="Select a name">
<option value=""></option>
<option value="1">User1</option>
<option value="2">User2</option>
<option value="3">User3</option>
</select>
</div>
<!-- /.input-group -->
</div>
<!-- /.mod name -->
<!-- MOD Date -->
<div class="col-md-3">
<label>MOD Date</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-server"></i></span>
<input type="date" class="form-control" name="daterangepicker" id="daterangepicker" />
<!-- <input type="date" id="mod_date" name="mod_date" class="form-control" style="width: 100%;"> -->
</div>
</div>
<!-- /.mod date -->
// hidden input field to determine the type and help differentiate the $_POST submissions
<input type="hidden" class="form-control" name="type" id="type" value="new_entry"/>
<!-- Submit button -->
<div class="col-md-1 text-center">
<label> </label>
<button type="submit" name="btnSubmit" class="btn btn-primary btn-block" onclick="this.disabled=true; this.value = 'Wait...'; this.form.submit(); return true;">Submit</button>
</div>
<!-- /.submit button -->
</form>
<!-- /.form 2 -->
Following SiteThief's suggestion, I am skipping the <form> approach altogether and am submitting the results via AJAX to my php handler file. Works like a charm without the pesky form submission problems.
JS
<script>
// SAVE NEW DEPARTMENT RECORD - SAVE BUTTON
$("#SubmitButton").click(function() {
// check that input fields are not empty
if($("#holidex").val()!="" && $("#mod_name").val()!="" && $("#mod_date").val()!="") {
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"mod_calendar",type:"new_entry",holidex:$("#holidex").val(),mod_name:$("#mod_name").val(),mod_date:$("#mod_date").val()},
dataType: "html",
success: function(data) {
$('#mod_output').html(data);
drawVisualization();
},
});
} else {
//notify the user they need to enter data
alert("Please choose a hotel, staff name and MOD date from the list.");
return;
}
// close modal and refresh page
setTimeout(function(){location.reload()}, 1000);
return;
});
</script>
So I have my form which I have supplied pictures of below. The left side picture is a normal border color but then the red outline on the right is when the form input is invalid.
How would I do this through PHP? Here's the corresponding code
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
exit($e->getMessage());
}
// Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
// Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)) {
echo "Complete all fields";
}
// Password match
if ($password != $password1) {
echo $passmatch = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo $emailvalid = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
}
if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
?>
And my HTML form
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
So if the input satisfies the if statement how would I display the color?
When your form has errors, you need to re-display it. It's hard to give a recommendation without knowing your code structure, but I will assume that your HTML is rendered via a call to php. Generally, I have done something like
$error = false
//this $_GET['submit'] variable could be part of the URL of your submitted form.
//alternately, you could check the HTTP method of the page request
if ($_GET['submit']) {
//run your form logic
//if you have success, run your php query and then redirect
//to your "success" page using a 302 (using a header("Location:... sort of call)
//you would also want to call die() or something right here
}
//if you make it this far, display your page including the bits about errors
//your form's action goes right back to the same page that rendered it, but with
//some change to the url to let the script know that you want to process the form
With PHP5 and with warnings about undefined variables turned on, you would need to define all of your error message variables before checking whether or not the form is being submitted.
Asuming you are using twitter bootstrap since you have form-control all over the place, (assuming >= 3.0.0), you can use (for the graphical side of things) has-suceess, has-error, etc like shown here: http://getbootstrap.com/css/#forms-control-validation.
When you re-display the form due to bad data, pass along your error messages to whatever renders your html. An example with your thing would be (assuming your form has access to $passmatch, $emailvalid,$passlength):
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
</div>
<div class="form-group <?php if (!empty($emailvalid)) { echo 'has-error'; } ?>">
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
</div>
<div class="form-group <?php if (!empty($passmatch) || !empty($passlength)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group <?php if (!empty($passmatch)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
I would recommend using a templating engine or something to separate the view from the actual code.
As for the help text, you can use something like this after the elements with errors:
<div class="form-group <?php if (!empty($yourVariable)) { echo 'has-error'; }?>">
<input type="text" class="form-control" />
<span class="help-block"><?php echo $yourVariable; ?></span>
</div>
The fun part is, if you have no error message, the help block won't even be shown because that variable won't have anything in it.
EDIT
Example page: http://content.kevincuzner.com/register.php
Example source: https://gist.github.com/kcuzner/11323907
I would handle this on the client side with JavaScript. On submission of the form, you can check whether the input is valid or not and then just update the border color using JavaScript.
The <?php ?> you can fill in above (if you want to go this route) can just depend on some variable that checks validity:
echo "Complete all fields";
$fieldsValid = false;
border-color: <?php $fieldsValid ? 'blue' : 'red' ?>
But you need to do a full page reload for this to work. JavaScript is a better route:
document.forms[0].addEventListener("submit", function () {
var usernameInput = document.querySelector("[name=username]");
if (!usernameInput.value) {
usernameInput.style.borderColor = "red";
}
});
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm trying to make a registration form. If you can give me some tips if my code is wrong or not proper
it still showing me this prepare
($sqlinsert); $user = $_POST['user']; $pass = $_POST['pass']; $email = $_POST['email']; $lname = $_POST['lname']; $fname = $_POST['fname']; $stmt->bind_param($user, $pass, $email, $lname, $fname); $stmt->execute(); $rowcount = $stmt->affected_rows; if ($rowcount > 0) { echo "Success!"; } else { echo "Error!"; } //CLOSE EXECUTE $stmt->close(); ?>
Here is my code:
<?php
$mysqli = new mysqli('local','root','','dbtform');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
$sqlinsert = "INSERT INTO tblform (user, pass, email, lname, fname)
VALUES ('sssss',?,?,?,?,?)";
$stmt = $mysqli->prepare($sqlinsert);
$user = $_POST['user'];
$pass = $_POST['pass'];
$email = $_POST['email'];
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$stmt->bind_param($user, $pass, $email, $lname, $fname);
$stmt->execute();
$rowcount = $stmt->affected_rows;
if ($rowcount > 0)
{
echo "Success!";
}
else
{
echo "Error!";
}
//CLOSE EXECUTE
$stmt->close();
?>
<head>
<title>Animated Form Switching with jQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="description" content="Expand, contract, animate forms with jQuery wihtout leaving the page" />
<meta name="keywords" content="expand, form, css3, jquery, animate, width, height, adapt, unobtrusive javascript"/>
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon"/>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/cufon-yui.js" type="text/javascript"></script>
<script src="js/ChunkFive_400.font.js" type="text/javascript"></script>
<script type="text/javascript">
Cufon.replace('h1',{ textShadow: '1px 1px #fff'});
Cufon.replace('h2',{ textShadow: '1px 1px #fff'});
Cufon.replace('h3',{ textShadow: '1px 1px #000'});
Cufon.replace('.back');
</script>
</head>
<body>
<div class="wrapper">
<h1>Rythreion</h1>
<h2>Demo: click the <span>orange links</span> to see the form animating and switching</h2>
<div class="content">
<div id="form_wrapper" class="form_wrapper">
<form class="register">
<h3>Register</h3>
<div class="column">
<div>
<label>First Name:</label>
<input type="text" name="fname" />
<span class="error">This is an error</span>
</div>
<div>
<label>Last Name:</label>
<input type="text" name="lname"/>
<span class="error">This is an error</span>
</div>
</div>
<div class="column">
<div>
<label>Username:</label>
<input type="text" name="user"/>
<span class="error">This is an error</span>
</div>
<div>
<label>Email:</label>
<input type="text" name="email"/>
<span class="error">This is an error</span>
</div>
<div>
<label>Password:</label>
<input type="password" name="pass" />
<span class="error">This is an error</span>
</div>
</div>
<div class="bottom">
<div class="remember">
<input type="checkbox" />
<span>Send me updates</span>
</div>
<input type="submit" value="Register" />
You have an account already? Log in here
<div class="clear"></div>
</div>
</form>
<form class="login active">
<h3>Login</h3>
<div>
<label>Username:</label>
<input type="text" name="user" />
<span class="error">This is an error</span>
</div>
<div>
<label>Password: Forgot your password?</label>
<input type="password" name="pass" />
<span class="error">This is an error</span>
</div>
<div class="bottom">
<div class="remember"><input type="checkbox" /><span>Keep me logged in</span></div>
<input type="submit" value="Login"></input>
You don't have an account yet? Register here
<div class="clear"></div>
</div>
</form>
<form class="forgot_password">
<h3>Forgot Password</h3>
<div>
<label>Email:</label>
<input type="text" name="email" />
<span class="error">This is an error</span>
</div>
<div class="bottom">
<input type="submit" value="Send reminder"></input>
Suddenly remebered? Log in here
You don't have an account? Register here
<div class="clear"></div>
</div>
</form>
</div>
<div class="clear"></div>
</div>
<a class="back" href="http://google.com">back to the Codrops tutorial</a>
</div>
<!-- The JavaScript -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//the form wrapper (includes all forms)
var $form_wrapper = $('#form_wrapper'),
//the current form is the one with class active
$currentForm = $form_wrapper.children('form.active'),
//the change form links
$linkform = $form_wrapper.find('.linkform');
//get width and height of each form and store them for later
$form_wrapper.children('form').each(function(i){
var $theForm = $(this);
//solve the inline display none problem when using fadeIn fadeOut
if(!$theForm.hasClass('active'))
$theForm.hide();
$theForm.data({
width : $theForm.width(),
height : $theForm.height()
});
});
//set width and height of wrapper (same of current form)
setWrapperWidth();
/*
clicking a link (change form event) in the form
makes the current form hide.
The wrapper animates its width and height to the
width and height of the new current form.
After the animation, the new form is shown
*/
$linkform.bind('click',function(e){
var $link = $(this);
var target = $link.attr('rel');
$currentForm.fadeOut(400,function(){
//remove class active from current form
$currentForm.removeClass('active');
//new current form
$currentForm= $form_wrapper.children('form.'+target);
//animate the wrapper
$form_wrapper.stop()
.animate({
width : $currentForm.data('width') + 'px',
height : $currentForm.data('height') + 'px'
},500,function(){
//new form gets class active
$currentForm.addClass('active');
//show the new form
$currentForm.fadeIn(400);
});
});
e.preventDefault();
});
function setWrapperWidth(){
$form_wrapper.css({
width : $currentForm.data('width') + 'px',
height : $currentForm.data('height') + 'px'
});
}
/*
for the demo we disabled the submit buttons
if you submit the form, you need to check the
which form was submited, and give the class active
to the form you want to show
*/
$form_wrapper.find('input[type="submit"]')
.click(function(e){
e.preventDefault();
});
});
</script>
</body>
</html>
If you can give me some tips if my code is wrong or not proper
Sure.
Your code is both wrong and improper because it is using mysqli.
You have to use PDO instead.
Just a sketch to give you an idea:
first, create a connection
$dsn = 'mysql:dbname=test;host=localhost;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);
then, run your query
$sql = "INSERT INTO tblform (user, pass, email, lname, fname) VALUES (?,?,?,?,?)";
$stmt = $pdo->prepare($sql);
$stmt->execute($_POST); // you may wish to unset non-used fields from POST first
if ($stmt->rowCount())
{
echo "Success!";
}