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!";
}
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.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
This script has form where user data get entered in this form there a check box which is used to mark if that user is a team leader. And I use a another script to check if that team has team leader or not if that team has a leader the team leader check box will be disabled.
This is the form:
<?php
/**
* Created by PhpStorm.
* User: SiNUX
* Date: 4/6/2017
* Time: 3:41 PM
*/
session_start();
include_once("../iConnect/handShake.php");
$getUserRole = "SELECT * FROM userroles ORDER BY urId ASC";
$getUserRoleQuery = $dbConnect -> query($getUserRole);
?>
<html>
<head>
<title>Timer User Creation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Style Sheets -->
<link rel="stylesheet" type="text/css" href="../../CSS/main.css">
<!-- Java Scripts -->
<script language="JavaScript" type="text/javascript" src="../../jScripts/jquery-3.2.0.min.js"></script>
<script language="javascript" type="text/javascript" src="../../jScripts/svrTimeDate.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/reload.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/setMsg.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/userCreatFunctions.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/multiScript.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/getIds.js"></script>
</head>
<body onload="pauseLoad4()">
<div id="divCenter" class="box">
<label id="userName">Hello <?php echo $_SESSION["fName"]." ".$_SESSION["lName"]; ?></label><br><br>
<label id="uId" hidden>1</label>
<div style="width: 166px; position: absolute; left: 642px; top: 20px; height: 44px;">
<img src="../../images/logo.png" width="142" height="33">
</div>
<label for="date">Date:</label>
<label id="date" style="margin-left: 50px;"></label><br><br>
<label for="fName">First Name:</label>
<input type="text" id="fName" name="fName" style="margin-left: 10px;" onkeyup="checkEmpty();">
<label for="lName" style="margin-left: 8px;">Last Name:</label>
<input type="text" id="lName" name="lName" style="margin-left: 10px;" onkeyup="checkEmpty();" disabled>
<label for="uName" style="margin-left: 8px;">User Name:</label>
<input type="text" id="uName" name="uName" style="margin-left: 7px;" onkeyup="checkEmpty();" disabled><br><br>
<label for="pWord1" style="margin-left: 8px;" >Password:</label>
<input type="password" id="pWord1" name="pWord1" style="margin-left: 17px;" onkeyup="checkLength();" disabled>
<label for="pWord2" style="margin-left: 8px;">Confirm Password:</label>
<input type="password" id="pWord2" name="pWord2" style="margin-left: 8px;" onkeyup="checkPass();" disabled>
<label for="uTeam" style="margin-left: 8px;">Team</label>
<select name="uTeam" id="uTeam" style="width: 170px;" onchange="teamId(this.id);enableRoles();" disabled>
<option></option>
</select>
<input type="text" name="uTeamId" id="uTeamId" hidden><br><br>
<div id="userRoles">
<label for="userRoles">User Role:</label><label for="uAttrib" style="margin-left: 250px;">User Attributes:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" class="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>" disabled><?php echo $row["userRole"]; }?>
<input type="checkbox" id="tl" name="tl" value="yes" style="margin-left: 120px;" disabled>Team Leader
</div>
<label id="msgID" hidden></label>
<div id="msg"></div>
<div id="sbmBtns">
<input type="button" value="Reset" name="reset" id="reset" class="btn" onclick="resetForm()">
<input type="button" value="Submit" name="submit" id="submit" class="btn" onclick="pauseLoad3();" disabled>
</div>
</div>
</body>
</html>
All the data collected is directed to my PHP processing page this page also has 2 parts first query executes and users details in to a database called userlogin.
Second parts is executed after the first one which take the last added id from userlogin database then it will be updated in my teams database where user ID and set a value to designate if that particular team has a leader or not.
My first part executes with out any error but the second part throws and error "invalid parameter number number of bound variables does not match number of tokens in".
I tried echoing all the data which is set in side that if function all was echoed but still this gives me that error I really can't find what I'm doing wrong please can some help me below is my PHP code.
PHP:
<?php
/**
* Created by PhpStorm.
* User: SiNUX
* Date: 4/7/2017
* Time: 12:15 PM
*/
include_once("../iConnect/handShake.php");
if (isset($_REQUEST["tl"])){
//Have to use the intermediate variable as work around to warning massage
// Strict standards: Only variables should be passed by reference
$intPword = md5($_REQUEST["pword"]);
$addUser = "INSERT INTO userlogin (uCreateDate, createdBy, fName, lName, uName, pWord, uTeam, uRole) VALUES (:uCreateDate, :uId, :fName, :lName, :uName, :pWord, :uTeam, :uRole)";
$addUserQuery = $dbConnect -> prepare($addUser);
$addUserQuery -> bindParam(':uCreateDate', $_REQUEST["udate"]);
$addUserQuery -> bindParam(':uId', $_REQUEST["uId"]);
$addUserQuery -> bindParam(':fName', $_REQUEST["fName"]);
$addUserQuery -> bindParam(':lName', $_REQUEST["lName"]);
$addUserQuery -> bindParam(':uName', $_REQUEST["uName"]);
$addUserQuery -> bindParam(':pWord', $intPword);
$addUserQuery -> bindParam(':uTeam', $_REQUEST["team"]);
$addUserQuery -> bindParam(':uRole', $_REQUEST["uRole"]);
if ($addUserQuery -> execute()){
$lastUid = $dbConnect -> lastInsertId();
if (isset($lastUid)){
$addTl = "UPDATE teams SET tlName = :tlName, tlSet = :tlSet WHERE tId = :tId";
$addTlQuery = $dbConnect -> prepare($addTl);
$addUserQuery -> bindParam(':tId', $_REQUEST["team"]);
$addUserQuery -> bindParam(':tlName', $lastUid);
$addUserQuery -> bindParam(':tlSet', $_REQUEST["tl"]);
echo $lastUid. " Last ID<br>";
echo $_REQUEST["tl"]. " TL<br>";
echo $_REQUEST["team"];
if ($addUserQuery -> execute()){
echo "1";
}else{
echo "11";
}
}
}else{
echo "10";
}
}else{
echo "3";
}
UPDATE: This is not DUPLICATE of some other post as marked look at content it was a mistake which I over saw I was binding values to the wrong query first of you people need read this before flagging. And mentioned link didn't solve my issue it's not even close to what I'm asking. Error is the same but the problem differs.
UPDATE: I just want to say sorry for making a big rant in comments section yesterday I'm really sorry acted very immature I was frustrated that led to this I'm sorry again.
The error is with this code. You are binding the params to different query object.
$addTl = "UPDATE teams SET tlName = :tlName, tlSet = :tlSet WHERE tId = :tId";
$addTlQuery = $dbConnect -> prepare($addTl);
$addUserQuery -> bindParam(':tId', $_REQUEST["team"]);
$addUserQuery -> bindParam(':tlName', $lastUid);
$addUserQuery -> bindParam(':tlSet', $_REQUEST["tl"]);
echo $lastUid. " Last ID<br>";
echo $_REQUEST["tl"]. " TL<br>";
echo $_REQUEST["team"];
if ($addUserQuery -> execute()){
echo "1";
}else{
echo "11";
}
You need to update the $addUserQuery to $addTlQuery
I created a login form that should direct the user to the page after sending the form but it just shows me a blank page
with a link of **http://localhost/Cisu/AccHolder/holderlogin.php
Login Form
<?php
session_start();
?>
<!DOCTYPE html>
<html >
<head>
<title>Login</title>
<link type="text/css" rel="stylesheet" href="css/login.css">
</head>
<body>
<form method="" action="holderlogin.php">
<div class="container">
<div class="profile">
<button class="profile__avatar" id="toggleProfile">
<img src="images/sbma.png" alt="Avatar" />
</button>
<div class="profile__form">
<div class="profile__fields">
<div class="field">
<input type="text" id="user" name="user" class="input" required pattern=.*\S.* />
<label for="username" class="label">Username</label>
</div>
<div class="field">
<input type="password" id="pass" name="pass" class="input" required pattern=.*\S.* />
<label for="password" class="label">Password</label>
</div>
<div class="profile__footer">
<input id="Submit" name="Submit "type = "Submit" class="btn"/>
</div>
</div>
</div>
</div>
</div>
<script src="javascript/login.js"></script>
</form>
</body>
</html>
holderlogin.php
<?php
ob_start();
session_start();
include('dbconn.php');// Database connection and settings
// checking the user
if(isset($_POST['Submit'])){
$user = mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "select * from tbl_accholder where accholder_Username='$user' AND accholder_Password='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user==1){
while ($row = mysqli_fetch_array($run_user)) {
$run_ID = $row['accholder_ID'];
$run_user = $row['accholder_Username'];
}
$_SESSION['accholder_Username']= $user;
$_SESSION['accholder_ID']= $run_ID;
header( 'Location: MainMenu.php');
} else
echo "please wait while redirecting...";
echo "<script> alert('Log-In Failed!'); </script>";
echo "<script> document.location.href = 'Login.php' </script>";
ob_end_flush();
}
?>
You are checking whether $_POST['Submit'] is set.
However, in your form, the name attribute is Submit with an extra space:
<input id="Submit" name="Submit "type = "Submit" class="btn"/>
This might be the cause of the problem, since you said it shows me a blank page.
also - you have no method listed for your form, but are checking the $_POST array to check for "Submit". It should be:
<form method="POST" action="holderlogin.php">
Don't know if its causing your problem, but you have a leading space before the php declaration - this can be cause problems to the php rendering if you are setting header requests later in the code - there can be no characters rendered before the header request.
<?php
also you list the action of the form as "holderlogin.php"
but list the name of the file as "Holderlogin.php" - this might just be a typo when entering the code here but worth checking.
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".
I'm trying to submit values to a database using jquery. I'm new to ajax but I'm required to do it with ajax.
This is what I've done so far my php code is
function insertSeries()
{
$options = array(
'user' => $_POST['user'],
'email' => $_POST['email'],
'summary' => $_POST['summary'],
'due_date' => $_POST['due_date'],
'problem_type' => $_POST['problem_type'],
'status' => $_POST['status']
);
$sql = "insert into ticket_summary('user','email','summary','due_date','problem_type','status') Values (?,?,?,?,?,?)";
$result = mysql_query($sql, $options) or die('Could not insert data');
}
My html code is
<?php
include 'eric_api.php';
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="js/jquery.js"></script>
<script src="js/api_calls.js"></script>
<link rel="stylesheet" href="css/normalizer.css" />
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="wrapper">
<h1>Ticketing System</h1>
<div>
<div id="ticket_form_wrapper">
<form id="insert_ticket" method="post" action="">
<p>
<label for="user">User</label>
<br />
<input type="user" id="user" class="post_fields" />
</p>
<p>
<label for="email">Email</label>
<br />
<input type="email" id="email" class="post_fields" />
</p>
<p>
<label for="summary">Summary</label>
<br />
<input type="summary" id="summary" class="post_fields" />
</p>
<p>
<label for="due_date">Due Date</label>
<br />
<input type="due_date" id="due_date" class="post_fields" />
</p>
<p>
<label for="problem_type">Problem Type</label>
<br />
<input type="problem_type" id="problem_type" class="post_fields" />
</p>
<p>
<label for="status">Status</label>
<br />
<input type="status" id="status" class="post_fields" />
</p>
<p>
<input type="submit" id="submit" value="Submit" />
<input type="button" onclick="window.location='index.php'" value="Go to List"/>
<div class="form_result"> </div>
</p>
</form>
</div>
</div>
</body>
</html>
And here's my ajax using jquery
$('#insert_ticket').submit(function(e){
var postData = $(this).serialize();
alert(postData);
$.ajax({
type: 'POST',
url: 'http://localhost/api/eric_api.php?q=insertseries',
data: postData,
success: function(response){
$('#insert_ticket').find('.form_result').html(response);
},
error: function(){
alert('error');
}
});
e.preventDefault();
});
I don't know what I'm doing wrong. Any help would be greatly appreciated
Instead of interfering with the form's submit event, interfere with a click event instead. To make minimal changes to your existing setup, just add the click handler to the form submit button. First thing inside of the handler, call e.preventDefault(). You'll have to explicitly select the form inside the handler to serialize the data. Then, move your existing ajax call into that handler, and it should work fine. Also, make sure that you are actually calling insertSeries() somewhere in your PHP code.
Cheers
Please reply to some of the comments so we can help figure out what the issues is. This is how your function would look with proper mysqli syntax.
How to make the connection:
$mysql = new mysqli(...)
How to prepare the statement: $stmt = $mysqi->prepare(....)
How to bind the parameters: $stmt->bind_param(...)
Execution: $stmt->execute()
Note: you were making your insert string like it was to be used for mysqli but your parameter binding was more similiar to pdo. I wasn't sure which one you were wanting to use so I chose mysqli. I personally prefer PDO, though... so I can re-write this using that if you want. Link to the PDO Prepare Function that also shows some binding.
// this is your database connection for mysqli
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
function insertSeries($mysqli)
{
$options = array(
'user' => $_POST['user'],
'email' => $_POST['email'],
'summary' => $_POST['summary'],
'due_date' => $_POST['due_date'],
'problem_type' => $_POST['problem_type'],
'status' => $_POST['status']
);
$sql = "insert into ticket_summary('user','email','summary','due_date','problem_type','status')
Values (?, ?, ?, ?, ?, ?)";
if ( $stmt = $mysqli->prepare($sql) )
{
$stmt->bind_param("ssssss", $options['user'], $options['email'],
$options['summary'], $options['due_date'],
$options['problem_type'], $options['status']);
$success = $stmt->execute();
if ($success) { print "query worked"; }
else { print "query failed"; }
}
}