1 - addlist.php
In this page, I've only a text input. I can scan a barcode, that gives me a text result in the input (ex: "banana").
2 - validaiton.php
This page connect my SQL DataBase and checks if value put in the textbox of my other page (addlist.php) is in my DB.
3 - addlist.php
If the value exists in DB, set a message and put the value in a list. If not, set an other message and do nothing.
/!\ For information: I've a barcode scanner, so I couldn't press a button or to display value in the list. So I chose to set a timer and every 800ms, it takes value and clears. With that, I can scan a value, display and clear it dynamically without touch my keyboard. /!\
addlist.php
<input type="text" id="IDAlim">
<div class="col-md-6">
<section>
<li id="demo"></li>
</section>
</div>
<script src="js\jquery.js"></script>
<script type="text/javascript">
var list = document.getElementById('demo');
$(document).ready(function()
{
putIn();
function putIn() {
var focused = $(':focus');
$("#IDAlim").focus();
focused.focus();
var IDAlim = document.getElementById('IDAlim').value;
var quantite = "1";
var entry = document.createElement('li');
if(IDAlim != "")
{
$.post('validation.php',{IDAlim: $('#IDAlim').val()}, function(data){
if(data.exists){
alert('Is in DB');
$("#demo").append('<li class="list-group-item">'+IDAlim+' '+quantite+'x'+'</li>');
}else{
alert('Re-Scan please');
}
}, 'JSON');
setTimeout(function(){ putIn() }, 800);
$("#IDAlim").val('');
}
else
{
entry.appendChild(document.createTextNode(IDAlim));
setTimeout(function(){ putIn() }, 800);
$("#IDAlim").val('');
}
}
})
</script>
validation.php
<?php
//set the headers to be a json string
header('content-type: text/json');
//no need to continue if there is no value in the POST IDAlim
if(!isset($_POST['IDAlim']))
echo json_encode(array('non' => 'POSTError'));
//Variable for db connection
$host="localhost";
$user="root";
$pass="";
$dbname="aliments";
try
{
$dbcon = new PDO("mysql:host={$host};dbname={$dbname}",$user,$pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$query = $dbcon->prepare('SELECT nom FROM tblaliments WHERE nom = :nomAlim');
$query->bindParam(':nomAlim', $_POST['IDAlim']);
$query->execute();
//return the json object containing the result of if the IDAlim exists or not. The $.post in my jquery will access it.
echo json_encode(array('exists' => $query->rowCount()));
}
catch (Exception $e)
{
echo json_encode(array('non' => 'PDOError'));
}
?>
I would update my quantity when I scan a same value, in my case, I put pending "1" for "quantite" (=quantity in french) to show you an example.
That's my problem
What I would like to have
Thank you in advance to help me and sorry for my bad english (I speak french)
Related
I want to manipulate the value that it is stored in this variable $result[]. Specifically i want to return that value from php file to my html file. What should i do? Can you give me some reference code when i want to return things from server side to client side for further manipulation?
My php file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result[]=$row['site_id'];
}
// Close connection
mysqli_close($link);
?>
My html file:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}while(flag1!=false);
$("#user_id").val(selection)
//$("#user_id").val(prompt("Give the User Id:"))
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}while(flag2!=false);
$("#book_id").val(selection2)
//$("#book_id").val(prompt("Give the Book Id:"))
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}while(flag3!=false);
$("#game_id").val(selection3)
//$("#game_id").val(prompt("Give the Game Id:"))
}
var fieldNameElement = document.getElementById('outPut');
if (fieldNameElement == 4)
{
window.alert("bingo!");
}
</script>
</head>
<body>
<form name="LoadGame" id="LoadGame" method="post" action="http://127.0.0.1/PHP/mine1.php" enctype="multipart/form-data">
<input type="submit" value="Load" id="load" onclick="load3()" class="button12" />
<input type="hidden" name="user_id" id="user_id">
<input type="hidden" name="book_id" id="book_id">
<input type="hidden" name="game_id" id="game_id">
<input type="hidden" name="site_id" id="site_id">
</form>
</body>
</html>
Note that this answer is making use of jQuery notation, so you will need to include a jQuery library in your application in order to make this example work:
<script src="/js/jquery.min.js" type="text/javascript"></script>
Since you have your HTML and PHP in separate files, you can use AJAX to output your HTML in an element you so desire on your HTML page.
Example of jQuery AJAX:
<script>
function submitMyForm() {
$.ajax({
type: 'POST',
url: '/your_page.php',
data: $('#yourFormId').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
alert('bingo!');
}
else {
alert('No!');
}
}
});
}
</script>
Note that I encapsulated the AJAX function in another function that you can choose to call onclick on a button for example.
<button id="mySubmitButton" onclick="submitMyForm();">Submit form!</button>
Step-by-step:
What we do in our AJAX function, is that we declare our data type, just like you would do with a form element. In your PHP file I noticed that you used the POST method, so that's what I incorporated in the AJAX function as well.
Next we declare our URL, which is where the data will be sent. This is the same page that your current form is sending the data to, which is your PHP page.
We then the declare our data. Now, there are different ways of doing this. I assume you are using a form currently to POST your data to your PHP page, so I thought we might as well make use of that form now that you have it anyways. What we do is that we basically serialize the data inside your form as our POST values, just like you do on a normal form submit. Another way of doing it, would be to declare individual variables as your POST variables.
Example of individual variables:
$.ajax({
type: 'POST',
url: '/your_page.php',
data: {
myVariable : data,
anotherVariable : moreData
//etc.
},
success: function (html) {
//do something on success?
$('#outPut').html(html);
}
});
A literal example of a variable to parse: myVariable : $('input#bookId').val().
The operator : in our AJAX function is basically an = in this case, so we set our variable to be equal to whatever we want. In the literal example myVariable will contain the value of an input field with the id bookId. You can do targeting by any selector you want, and you can look that up. I just used this as an example.
In the success function of the AJAX function, you can basically do something upon success. This is where you could insert the HTML that you wish to output from your PHP page into another element (a div for example). In my AJAX example, I am outputting the html from the PHP page into an element that contains the id outPut.
We also write a condition in our success function (based off comments to this answer), where we check for a specific substring value in the div element. This substring value is defined through the variable bingoValue. In my example I set that to be equal to 4, so whenever "4" exists inside the div element, it enters the condition.
Example:
<div id="outPut"></div>
If you make use of this example, then whatever HTML you structure in your PHP file, making use of the PHP values in your PHP file, will be inserted into the div element.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result=$row['site_id'];
echo $result.' ';
}
// Close connection
mysqli_close($link);
?>
Your form also no longer needs an action defined as all of that is now taken care of by the AJAX function.
So change:
<form name="LoadGame" id="LoadGame" method="post" action="http://127.0.0.1/PHP/mine1.php" enctype="multipart/form-data">
to:
<form name="LoadGame" id="LoadGame" method="post" enctype="multipart/form-data">
And make sure that your button: <button id="mySubmitButton" onclick="submitMyForm();">Submit form!</button> is outside of your form tag, as buttons without a defined type attribute will have type="submit" by default inside a form tag.
If you need anything elaborated, let me know. :)
First of all: remove the script tag from your php.
Secondly: Why are you executing the sql statement two times?
To your question:
You have to send a request to your PHP script via AJAX: (Place this inside <script> tags and make sure to include jquery correctly)
$(() => {
$('form').on('submit', () => {
event.preventDefault()
$.ajax({
type: 'POST',
url: '<your-php-file>', // Modify to your requirements
dataType: 'json',
data: $('form').serialize() // Modify to your requirements
}).done(function(response){
console.log(response)
}).fail(function(){
console.log('ERROR')
})
})
})
Your PHP-Script which needs to return JSON:
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
// Execute Query
$res = mysqli_query($link,$query) or die(mysqli_error($link));
// Get Rows
while($row = mysqli_fetch_assoc($res)){
$result[] = $row['site_id'];
}
// Return JSON to AJAX
echo json_encode($result);
Take a look at your developer console.
Haven't tested it.
i'm working on this site that allows to students to book seats for training sessions by selectiong theme on a drop down list and clincking on a button. i created a javascript(ajax) script that contains a function which calls a php script that reduces the number of seats on my database.
But unfortunately it's not working... i need your help guys :
here's my javascript :
<select name="Branche" name="clock" id="clock" onchange="count()"></select>
<a onclick="count()" class="button">
<span class="user">Réserver une place</span>
</a>
<script>
function count(){
var place = document.getElementByTagName(clock);
var option = place.options[place.selectedIndex].id;
alert(option);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "count.php?place=" + place,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var reponse = xmlhttp.responseText;
if(reponse == "yes") {
alert("Votre place a été réservé");
} else {
alert("Vous êtes arrivé trop tard !");
}
}
}
}
</script>
and here's my php script :
try {
$db = new PDO('mysql:host=localhost;dbname=projet','root','',array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch(Exception $e){
echo $e->getMessage();
die();
}
$nom = $_GET['place'];
$sq="SELECT place FROM formation WHERE nom='$nom'";
$re = $db->query($sq);
$i = $re->fetch(PDO::FETCH_ASSOC);
if($i > 0){
$sqq="UPDATE formation SET place = place - 1 WHERE nom='$nom'";
$res = $db->query($sqq);
echo 'yes';
} else {
echo 'no';
}
The first errors are in this line:
var place=document.getElementTagName(clock);
You need to find the element by it's id, not its tag name. Also click is an non-existing variable; you should use "clock" with quotes:
var place=document.getElementById("clock");
That way place will be the select element. But then later you use this in building the URL parameter:
xmlhttp.open("GET","count.php?place="+place,true);
But place is not the selected value; it is the select element, so that will not work right. Instead you should send the value you have in the option variable:
xmlhttp.open("GET","count.php?place="+option,true);
This is assuming that the value of option is correct. Without seeing the HTML and your database table content, this is impossible to say at this moment.
The PHP script has an error here:
$i = $re->fetch(PDO::FETCH_ASSOC);
if($i>0){
You use $i as if it is the selected value, but that is not true. fetch() returns an array with values, in this case an array with one value. The comparison as you have it will always return true, even if the selected place value is 0.
Furthermore you should alter your PHP script so you do not concatenate values into an SQL string, as it makes you vulnerable to SQL injection. Instead use prepared statements.
Also, your PHP script is not working well when there is a lot of concurrency. Imagine that there is one seat left and two make the PHP call at the same time, then both will see there is one place left before the other one has decreased the count, and both will get a "yes".
Instead you should first perform the update and check for availability within the update statement. Then check if the statement updated a record. If not, then there were no places left. As an update statement locks the record during the update, only one process can do it at a time.
Suggested PHP code after database connection is established:
$stmt = $db->prepare("UPDATE formation
SET place = place - 1
WHERE nom = ?
AND place > 0");
$stmt->execute(array($_GET['place']));
echo $stmt->rowCount() ? 'yes' : 'no';
I have a progress bar and a button.
When it reaches 100%, I use JQuery AJAX to check if the user already has an active giftcode in database or he doesen't. If he doesen't, I generate a new giftcode and insert it into the database.
The generating and inserting is working just fine. My problem is, I need the user account ID in the JQuery script. I'm currently using the hidden input method and it returns my account ID 0 every time, no matter which account I use.
This is the code on main page:
<div id ="resultDiv" style="text-align:center;"></div>
<input type="hidden" id="hdnSession" data-value="#Request.RequestContext.HttpContext.Session["ID"]" />
This is the JQuery file (where I check if user has active giftcode using AJAX):
$(function() {
var timer = 0;
$('#code').click(function () {
clearInterval(timer)
var value = 0;
timer = setInterval(function () {
value++;
$('.progress-bar').width(value + '%').text(value + '%');
if (value == 100) {
clearInterval(timer);
var sessionValue= $("#hdnSession").data('value');
$.post("checkcode.php",
{
ID: sessionValue
},
function(data)
{
$("#resultDiv").hide().html(data).fadeIn(1000);
});
}
}, 10);
})
});
And this is the .php file which does the checking:
<?php
include_once ('connect.php');
if(isset($_POST['ID']))
{
if(!empty($_POST['ID']))
{
$id = $_POST['ID'];
$select_user = "SELECT * from giftcodes WHERE UserID='$id'";
$query = mysqli_query($con, $select_user);
$row = mysqli_num_rows($query);
if(!$row) {
$randomcode = substr(md5(uniqid(mt_rand(), true)), 0, 8);
$insert_code = "INSERT INTO giftcodes (UserID, Giftcode) VALUES ('$id', '$randomcode')";
$query = mysqli_query($con, $insert_code);
echo'<br><hr><h1 style="color: #5cb85c;">Your generated gift code:</h1><br><pre><kbd style="background-color: #5cb85c; color: #000;">'.$randomcode.'<kbd></pre><hr><p class="small" style="font-weight:bold;">You can generate a new code in 24 hours.</p>';
} else {
echo 'You already have an active gift code!';
}
}
}
?>
So the problem is, var sessionValue= $("#hdnSession").data('value'); returns 0 every time although I'm sure the user $_SESSION['ID'] is set. If I generate a gift code, the UserID will get set to 0 every time.
If your "main page" is a php page you can use this (getting from php the $_SESSION['ID'] value and assign to value for the hidden input field
<div id ="resultDiv" style="text-align:center;"></div>
<input type="hidden" id="hdnSession" value="<?php echo $_SESSION['ID']; ?>" />
I can just use $_SESSION['ID'] in the PHP file.. don't know why I tried to get this so complicated. Sorry.
I run a website for a youth sports program that features schedules, standings, and score reporting using simple PHP scripts that manipulate data stored in a MySQL database.
After a game is played, the winning coach will access the score reporting form for that particular game, enter the information, and click submit to update the schedule and standings accordingly. They are then automatically redirected to the schedule page that they came from.
However, several times a season, a coach will unintentionally duplicate a score submission (sometimes creating as many as three or four instances) which does not affect the result posted on the schedule, but does throw the data in the standings out of whack. I'm not sure how exactly this is being accomplished, but I'm trying to fix the problem.
I've been reading up as much as possible on here and the web and believe that I need to implement some sort of token system to the reporting script, but I'm unsure how to exactly write the code? Any advice here would be GREATLY appreciated. Here is the script itself:
<?php
// Connect to the database:
require ('../mysqli_connect.php');
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} elseif ($_POST['school'] != $_POST['away_team'] && $_POST['school'] != $_POST['home_team']) {
echo "Your school does not match one of the two on file for this game.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
// Validate the password:
if (empty($_POST['pass'])) {
echo "You forgot to enter your password.<br>";
$validate = 'false';
} else {
$pass = mysqli_real_escape_string($db, trim($_POST['pass']));
$validate = 'true';
}
// Validate the away score:
if (!isset($_POST['away_score'])) {
echo "You forgot to enter the away score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['away_score'])) {
echo "You entered an invalid score for the away team.<br>";
$validate = 'false';
} else {
$away_score_confirm = mysqli_real_escape_string($db, trim($_POST['away_score']));
$validate = 'true';
}
// Validate the home score:
if (!isset($_POST['away_score'])) {
echo "You forgot to enter the home score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['$home_score']) && $_POST['$home_score'] < 0 ) {
echo "You entered an invalid score for the home team.<br>";
$validate = 'false';
} else {
$home_score_confirm = mysqli_real_escape_string($db, trim($_POST['home_score']));
$validate = 'true';
}
// Determine the winner and loser, and set variables:
if ($_POST['away_score'] > $_POST['home_score']) {
$winner = mysqli_real_escape_string($db, trim($_POST['away_team']));
$winner_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
$loser = mysqli_real_escape_string($db, trim($_POST['home_team']));
$loser_score = mysqli_real_escape_string($db, trim($_POST['home_score']));
$tie = 'no';
} else if ($_POST['away_score'] < $_POST['home_score']) {
$winner = mysqli_real_escape_string($db, trim($_POST['home_team']));
$winner_score = mysqli_real_escape_string($db, trim($_POST['home_score']));
$loser = mysqli_real_escape_string($db, trim($_POST['away_team']));
$loser_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
$tie = 'no';
} else if ($_POST['away_score'] == $_POST['home_score']) {
$tie = 'yes';
$tie1 = mysqli_real_escape_string($db, trim($_POST['away_team']));
$tie2 = mysqli_real_escape_string($db, trim($_POST['home_team']));
$tie_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
}
// Declare remaining hidden inputs as variables:
$league = $_POST['league'];
$table = mysqli_real_escape_string($db, $_POST['table']);
$game_id = mysqli_real_escape_string($db, $_POST['game_id']);
$sport = $_POST['sport'];
// Declare remaining hidden inputs as variables:
$standings_league = $table . "_standings";
// If all conditions are met, process the form:
if ($validate != 'false') {
$q1 = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass='$pass')";
$r1 = mysqli_query($db, $q1);
$num = mysqli_num_rows($r1);
if ($num == 1) {
// Get the game ID:
$q2 = "SELECT $game_id FROM $table";
$r2 = mysqli_query($db, $q2);
// Get the row for the game ID:
$row = mysqli_fetch_array($r2, MYSQLI_NUM);
// Perform an UPDATE query to modify the game scores:
$q3 = "UPDATE $table SET home_score='$home_score_confirm', away_score='$away_score_confirm' WHERE game_id=$row[0]";
$r3 = mysqli_query($db, $q3);
if (mysqli_affected_rows($db) == 1) {
$confirm = 'true';
} else {
$confirm = 'false';
}
// Update the winning team in the standings:
$q4 = "SELECT school_id FROM $standings_league WHERE school_name='$winner'";
$r4 = mysqli_query($db, $q4);
// Get the row for the school:
$row2 = mysqli_fetch_array($r4, MYSQLI_NUM);
$q5 = "UPDATE $standings_league SET games=games + 1, win=win + 1, pts_for=pts_for + '$winner_score', pts_against=pts_against + '$loser_score' WHERE school_id=$row2[0]";
$r5 = mysqli_query($db, $q5);
$q6 = "UPDATE $standings_league SET pct=(win / games), avg_for=(pts_for / games), avg_against=(pts_against / games) WHERE school_id=$row2[0]";
$r6 = mysqli_query($db, $q6);
// Update the losing team in the standings:
$q7 = "SELECT school_id FROM $standings_league WHERE school_name='$loser'";
$r7 = mysqli_query($db, $q7);
// Get the row for the school:
$row3 = mysqli_fetch_array($r7, MYSQLI_NUM);
$q8 = "UPDATE $standings_league SET games=games + 1, loss=loss+1, pts_for=pts_for + '$loser_score', pts_against=pts_against + '$winner_score' WHERE school_id=$row3[0]";
$r8 = mysqli_query($db, $q8);
$q9 = "UPDATE $standings_league SET pct=(win / games), avg_for=(pts_for / games), avg_against=(pts_against / games) WHERE school_id=$row3[0]";
$r9 = mysqli_query($db, $q9);
if ($confirm != 'false') {
header('Location: schedules_' . $sport . '_' . $league . '.html?league=' . $league .'&table=' . $table);
} else {
echo "The scores could not be reported due to a system error. Apologies for the inconvenience. If this problem continues, please contact us directly.";
}
} else {
echo "Your school and password combination do not match those on file for this game.";
}
}
mysqli_close($db);
?>
My guess is that these coaches are simply clicking the submit button multiple times while the form is waiting for a response from the server. You could use JS to disable (or hide) the button after the first click:
var button = document.querySelector('input[type=submit]'); // Use whatever selector is appropriate here
button.addEventListener('click', function(ev) {
if (!button.classList.contains('submitting')) { // If this is our first click...
button.className += ' submitting';
} else { // Otherwise prevent submission
ev.preventDefault();
}
});
If you have jQuery available to you, you could also just handle the entire submission process via JS and block it there.
You should be aware of presenting some sort of feedback onto the screen to let the user know that a submission is currently in progress, that'll help alleviate some button mashing as well.
One solution is to add a unique value to the form and when its submitted, add the value to a session. If they hit submit button more than once ( probably what is happening ), it will accept only one submition
Example:
<form>
<input type="hidden" name="submit_id" value="<?php echo mt_rand(); ?>">
// rest of the form
</form>
Php file recieving:
<?php
session_start();
if ( isset( $_POST['submit_id'] ) ) {
if ( !isset( $_SESSION['submit_id'] ) ) {
$_SESSION['submit_id'] = array();
}
if ( !in_array( $_POST['submit_id'], $_SESSION['submit_id'] ) ) {
// validate posted values
// when data is valid, register form as submitted
$_SESSION['submit_id'][] = $_POST['submit_id'];
// add the submitted form data to database
}
else {
echo 'Your data has already been submitted';
}
}
I don't want to read your code so I'll suggest a strategy.
I agree with #relic. Your coach is probably double-clicking the button.
If you can assume that different users will never submit two forms in the same second, then you can "filter" your table to accept only one entry for any given second. Make an index for the (new) seconds column, and make it unique. This will prevent insertions of rows to that table if an entry already exits for that second.
If this leads to conflicts, you can introduce restrictions that enforce every entry to be unique for a combination of other fields in the table. This is called compound keys (SQL). You formulate something like, for this game and user, there can only be one score registration.
MySQL:
create table scores (game_id int, user_id int, score int );
alter table scores add unique index uniq_gus (game_id, user_id, score);
insert into scores (game_id, user_id, score) values (1, 1, 10);
insert into scores (game_id, user_id, score) values (1, 1, 10);
ERROR 1062 (23000): Duplicate entry '1-1-10' for key 'uniq_gus'
In addition, you may want to prevent double-submissions (assuming jQuery):
(function($){
var btn = $('button[type="submit"]');
btn.click(function(event){
event.preventDefault();
btn.attr('disabled','disabled');
$.ajax({
url: 'http://foo.bar/form-endpoint.php',
success: function (data, status, xhr) {
btn.removeAttr('disabled');
},
})
})
})(jQuery);
I am trying to create a signup form that checks if the user exists in the database, I inserted a sample user and when I tried signing up with that user it didn't say its already been taken. What have I done wrong?
The JavaScript:
function formSubmit()
{
document.getElementById('email_valid').innerHTML = '';
var temail=document.forms["signup_form"]["temail"].value.replace(/^\s+|\s+$/g, '');
var atpos=temail.indexOf("#");
var dotpos=temail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=temail.length)
{
//alert("Not a valid e-mail address");
setTimeout(function(){document.getElementById('email_valid').innerHTML = '<br/>Email must be valid...';},1000);
var temailsub=0;
}
else
{
$.post('/resources/forms/signup/email.php',{email: temail}, function(data){
document.getElementById('email_valid').innetHTML = data;
if(data.exists){
document.getElementById('email_valid').innetHTML = '<br/>The email address you entered is already in use.';
var temailsub=0;
}else{
var temailsub=1;
}
}, 'JSON');
}
if(temailsub==1e)
{
setTimeout(function(){document.getElementById("signup_form").submit();},1000);
}
else
{
return false;
}
}
The PHP file (email.php):
<?php
header('content-type: text/json');
require_once $_SERVER['DOCUMENT_ROOT']."/resources/settings.php";
$query = $pdo->prepare("SELECT * FROM users WHERE email=:email");
$query->execute(array(
":email"=> $_POST['email']
));
echo json_encode(array('exists' => $query->rowCount() > 0));
?>
I have checked and double checked the code, I still cannot see why its not detecting that the email has already been used... what do i need to do to fix this and avoid this in the future?
The problem is that PDOStatement::rowCount() returns the number of rows affected by the last SQL statement. You are performing a SELECT so this value will always be 0. SELECT does not affect any rows. Instead you need to count the number of rows:
$query = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email=:email");
$query->execute(array(
":email"=> $_POST['email']
));
$rows = $query->fetchColumn();
echo json_encode(array('exists' => $rows);
Also from jtheman's comment above, you should replace innetHTML with innerHTML in your JavaScript.