I have to press the submit button twice (PHP) - php

This code is used to put a data in the database once the button is activated and then take it off and replace it by(Question save!). The problem is it take me two attempts to make it disappear(the button). $numofrow is used to verify if the action was once made(the action of the submit button). The problem is not the database,query,etc, its really the button. Thanks for your time.
This is my code:
if(isset( $real_domaine)){
$tt = "SELECT*FROM uniwix.table0 WHERE id= '$id' ";
$rr = mysqli_query($database,$tt);
while($rows = mysqli_fetch_assoc($rr)){
[rows call...]
$md = "SELECT*FROM uniwix.table1 WHERE usern='$us' and question='$sujet'";
$ao = mysqli_query($database,$md);
$numofrow = mysqli_num_rows($ao);
if($numofrow == 0){
echo '<form action="" method="POST">
<input type="submit" name="sauvegarder" value="Save the question"/>
</form>';
if(isset($_POST['sauvegarder'])){
$qu = "INSERT INTO database (usern,question) VALUES('".$us."','".$sujet."')";
$sm = mysqli_query($database,$qu);
}
}else{
echo 'Question saved!';
}
//end of while loop
}
// end of if(isset( $real_domaine))
}

The problem is not the database,query,etc, its really the button.
The button is almost passive, all it does is to send the data to the server when it is pressed. The error is in the (lack of) logic of the PHP code.
When the script runs for the first time, $numofrow is 0. It runs the echo that generates the form with the button then it checks if $_POST['sauvegarder'] is set. It is not set, of course, because when the page is loaded for the first time, the GET method is used.
The user presses the button, the data is submitted using POST and the code runs again. $numofrow is still 0 (no data was inserted in the database yet), the form is displayed again but this time $_POST['sauvegarder'] is set and the data received from the browser is saved into the database.
You need to rethink the logic of you page.
More, the form is empty. Maybe it works but this is not the correct way to write forms. The input fields you want to send to the server must stay in the form.
Even more, and the most important of all, your database code is a candidate for SQL injection. Don't build queries using string concatenation. Use prepared statements. Also read about how prevent SQL injection in PHP.

Related

Is it possible to add a timer to a button?

I have a button that performs an action, is it possible to create a timer so the button can only be used every 6 hours or so?
Would need to be for each specific user, so if one user presses the button, it won't affect another user's cooldown or ability to press it.
Here's the form
<html>
<body>
<form action="addgold.php">
<input type="submit" name="Add gold" value="Work" onclick="addgold()" />
</form>
And here's the action that the button performs if it is needed
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
include("header.php");
include("connect.php");
if(isset($_SESSION['userlogin'])){
$username = $_SESSION['userlogin'];
$sql = "SELECT stats.id, stats.gold, users.id, users.username FROM stats, users WHERE users.username = '$username' AND stats.id = users.id";
$retval = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($retval, MYSQL_ASSOC))
{
echo "Gold :{$row['gold']} <br> ".
"--------------------------------<br>";
}
$row = mysqli_fetch_row($retval);
$result = $row[0];
echo "Back to main page";
}else{
?>
<?php
echo "fail";
}
?>
I found a similar answer to this in another Stackoverflow question (this site has everything) that said it can only be done in javascript, which is fine besides I haven't a clue about javascript!
There was some code he/she put with it
window.setTimeout(function() {
document.forms['form_name'].submit();
}, 1000);
But where do I put that? into my php page? if so, where?
It is really important how you want the button will work.
1) Is it only for registered users
Save it to database. And then just check the DB time difference.
2) For everyone
If it does not have to be 100 % accurate you can use a session or you can also save the information to DB and then check the difference.
If you put your limiter in javascript, it will be done client-side, which means if a user knows about programming, he'll easily be able to go around that protection.
If you really want to enforce a time limit between clicks, it should be done server-side, but that means that the server must be able to recognize clients. What is generally done is using the IP address (even if it's not perfect), which you can get by checking the $_SERVER['REMOTE_ADDR'] variable in PHP.
If you want to compel observance of time limit between clicks surely you would need to use $_SESSION[] in php(server side) for this purpose and save the information to the database.
Assuming your app has authentication in place, which identifies each user uniquely, you can create a table in your DB (or add a column to your users table) which stores the last time a user has pressed the button as a DATETIME type.
Then all you have to do when the page is requested is calculate the difference between the current time and the one stored in your DB. Using mysql:
SELECT HOUR(TIMEDIFF(NOW(),last_pressed)) AS time_passed FROM my_table
If the difference is less than 6 hours you simply remove or disable the button. Do note that removing the button is not enough and you have to block the action on the server side as well, because a seasoned user can send the request via the browser's URL bar or using curl without using the button.
If you don't have proper session authentication, you can resort to #ploutch's solution, and save the IP address instead of the user ID. This is not perfect because the headers sent to the server can be tampered with by the client.
Try setTimeout function in javascript
<input type="button" value="click" id="click" onclick="foo(this);"/>​
in javascript
function foo(obj) {
obj.disabled = true;
setTimeout(function() {
obj.disabled = false;
}, 2000);
}​

How can I send data to another page without javascript, jquery, or an HTML form?

I'm very new to web programming and everything I learn I basically learn from looking up documentation online. I have a website running a type of game with an inventory and such. I can't seem to think of a clean way of giving items to the user. It currently uses a JavaScript function, but I realized the user could just call the function from the URL bar and exploit the system.
On a given page, this is the code that calls for an item to be given. The user will click a button like the "Get Hat" button, and will be redirected to another page:
<script>
function giveitem(name, quant)
{
document.getElementById("itemnamefield").value=name;
document.getElementById("itemquantfield").value=quant;
document.itemform.submit();
}
</script>
<form id="itemform" name="itemform" action="./itemget.php" method="post">
<input type="hidden" id="itemnamefield" name="itemnamefield" value="">
<input type="hidden" id="itemquantfield" name="itemquantfield" value="">
</form>
<input type="button" onClick="javscript: giveitem('Hat',1);" value="Get Hat"><br>
itemget.php then executes this function using the post data from the previous page. $id is the user's ID number stored in a cookie, $name is the title of the item, $quant is the desired quantity of the items.
function additem($id, $name, $quant){
include 'sqlconnect.php';
$result = mysqli_query($con, "SELECT * FROM inventory WHERE id='$id' AND name='$name'");
if ($row = mysqli_fetch_array($result)){
mysqli_query($con, "UPDATE inventory SET quant=quant+'$quant' WHERE id='$id' AND name='$name'");
}
else{
$subresult = mysqli_query($con, "SELECT name FROM itemdef WHERE name='$name'");
$subrow = mysqli_fetch_array($subresult);
mysqli_query($con,"INSERT INTO inventory (id, quant, name) VALUES ('$id', '$quant', '$subrow[name]')");
}
}
itemget.php then displays what items the user received.
So I can't use javascript because that's exploitable. I'm not really intent on using jquery or anything besides standard HTML and PHP (I'm trying to keep it simple because I'm so inexperienced). Is my only alternative to create a new form for every "give x item" button?
You can use javascript, forms, or just simple hyperlinks.
The trick is to let the server know which possibilities the user has. So when you generate the page, you can store in the user's session on the server that you generated the 'get hat' link, so 'get hat' therefor is a valid command.
If you receive a command that is not valid, the user may be cheating, or they clicked 'back' and executed a command from an outdated page. Anyway, you can then ignore the command or display a message instead.
So the trick is to keep the validation on the server. That way, they cannot cheat, because everything other than the commands you provided are blocked.
So talking techniques, you can just write the game logic and session handling in PHP and use plain HTML (hyperlinks) to render the commands. If you like, you can use Javascript/JQuery or forms as well, if you think it is easier or makes your gameplay better. As long as you do the checking on the server, you should be fine.
Small example. When you send data to a .php file for the information be processed further, always, and I mean always be panicked(not like bad panic, but just be carefull) and don't trust user info. If you know that the variable $x is supposed to be only integer, then use an if condition to make sure it is an integer so bad/malicious data won't be a problem.
Use PHP Sessions initialized by <?php session_start(); ?>, then you can store information stored on server referenced by a cookie with a session id.
For example don't store user's id in a cookie, use sessions: <?php $_SESSION['user_id'] = 1; ?>
Then, for example you can store available items in that session, too.
game.com/view-x.php
<?php
session_start();
...
$_SESSION['items_available'] = array('hat', 'shoe');
?>
When for example a user requests a an item via html form, link, ...:
game.com/item-add.php?item=stone
<?php
session_start();
...
if (in_array($_GET['item'], $_SESSION['items_available'])) {
..
}
else {
// 'stone' is not an available item
}
...

How to put a PHP 'not null' condition on mysql insert statement?

I have a page with two forms on it (and two submit buttons), and the forms link the page back to itself with action="" for the INSERT INTO statements. One of the INSERT INTO statements is:
<?php
$sql="INSERT INTO panelProduct (length_mm, width_mm, aperture)
VALUES ('$_POST[p_length_mm]','$_POST[p_width_mm]','$_POST[p_aperture]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
One of the reasons I have put the form and the INSERT statements on the same page is that the form allows users to add products to an order, and there may be several products (so I thought the user could keep submitting until they're done...). The other reason was that I need to use a $_POST value sent from the previous page to do something else with the products they enter, and I don't know how to send it to more than one page.
Anyway, the problem I have found is that a new row is inserted into the database every time the page is refreshed, containing NULL values. This makes sense to me as the PHP will execute the statement above every time it encounters it. My question therefore is how I can make some sort of condition that will only execute the INSERT statement if the user enters something in the form and 'Submits'?
you could use the empty() method of PHP to check for null values in each of the variables.
Something like:
if(!empty($_POST['p_length_mm']) && !empty($_POST['p_width_mm']) && !empty($_POST['p_aperture']))
{
//execute your query here
}
else
{
//if there's an alternative you would like to happen if values are null, or just leave out.
}
Hope that does the trick.
You have to check if data come from your form. I'd suggest this approach - name your submit button (i.e. <input type="submit" name="my_submit_button" value="Whatever" /> and this condition to your insert code:
if( isset( $_POST['my_submit_button']) ) {
.. process your post data
}
Also, always remember not to trust user provided data. Verify if all data expected are present in$_POST and format matches requirements (i.e. you ask for number and received letters etc). If all test passed, then you are ready to commit your data to DB.
You need a condition like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) {
// a form was posted
}
Of course, you still need to check whether your post actually contains the right stuff:
isset($_POST['p_length_mm'], $_POST['p_width_mm'], $_POST['p_aperture'])
Even better is to use filter_input_array() to sanitize your incoming data; your current code is open to SQL injection attacks. Using PDO or mysqli and prepared statements is the way to go.

php stop form from posting

Basically i have a form where a studentID is inputted, i then want to check id the inputted studentID is in the database, if it is post the form to the next page. If not then display an error on the page where you input studentID
Don't really know where to start
Cheers
is this what you want?
<form id = "form" action = "./?page=markandfeedback" method = "post">
<br>
Mark for:
<INPUT id="stud" onkeypress="return isNumberKey(event)" type="text" name="stud" value="Enter Student Number">
<input type="submit" value = 'Continue'>
<?
$studID = $_POST['stud'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql);
// echo $_SESSION['module'];
if ($result == NULL) { // nothing found
echo "the student id you entered is not in the database";
}
else {
$_SESSION['student'] = $studID;
Header("Location: http://www.whereever.com/"); // send the browser where you want
exit();
}
?>
EDIT:
I went over the other answers. I assume you check for mysql injection properly. I recommend implementing AJAX AFTER everything works and is secure. The idea behind my solution was to solve the problem as simple as possible. If you want to make something fancy out of it you could:
generate the whole form via php and tell the user in the input field, that the id wasn't found
tell your Javascript to present the information in some fancy way
Use AJAX. Everybody loves forms with AJAX.
You could, as suggested, assume that the user entered a valid id. You would check on the "whereever" page wether the id is actually valid. If it weren't, you would simply send the user back to the form and tell the php to output an error message (maybe via get). This possibility is not usual, I am not sure if it has any advantages.
the mysql_num_rows hint is nice, too, if you don't want any data from the user. I thought you wanted to do something with the data because of the SELECT *.
Make a seperate controller that does the checking of the username.
Use ajax to check if user input is valid or not.
So you'll have something like this:
<input id="stud" onchange="checkStudentId(this)" />
<script>
function checkStudentId(inputElement) {
var id = inputElement.value();
$.ajax({
url: "test.html",
context: {id:id}
}).done(function() {
// Check the return result
});
}
</script>
Here is a reference to jquery ajax
http://api.jquery.com/jQuery.ajax/
You actually have to connect to the server in some fashion to figure out of the student exists. What you'd normally do in this situation is submit the form to the server and do validation server-side. If the student exists, you return the "next" page. If the student doesn't exist, then you return (or redirect to using a Location header) the same form again with an error message.
Another popular method would be to use an AJAX request to check asynchronously (which I see many other people are recommending). I'd only recommend this way if you're actually doing validation right as they've finished entering the student id and are showing an error message in real-time, effectively. In this way, AJAX is a nice-to-have to provide quick user feedback, but not a real solution. Keep in mind that regardless of this, you need to check for and handle this when the form is submitted anyway, or at the least, consider what will happen when the form is submitted with an invalid id.
People can bypass this check (EVERY request from the client side is considered hostile, you can't implicitly trust anything)
Another user may have deleted the student ID between the time the check was done and the form was submitted
There could be an error in your code that causes validation to falsely pass or not to recognize a negative response
Doing AJAX onsubmit makes no sense, because effectively you're doubling the amount of work by making the server handle two separate requests in a row. It's simply the wrong answer to the problem.
The biggest trouble with this implementation is the PHP code can quickly get quite hairy and hard to follow as you have everything mixed together.
This is where you probably start to tip over using PHP like a templating language (mixed php code and html markup) and start getting into using a framework where your views (the HTML) are decoupled from your PHP code (if you're using the very-populate MVC pattern, this code is called your controller -- precisely because it controls how the server responds). This is how any professional developer will work. Kohana, CakePHP, and Zend are all examples of fairly popular MVC frameworks, all of which are used professionally.
You can do this in two different ways
AJAX - make ajax call to your server and check the ID if its exist display the error else go to the next page
PHP - put a hidden input in your form and make the action of the form to the same page and check everything their and keep the values of the input fields is the $_POST['field_name'];
And you can make the action into another page and return back variable or make a session to hold the error message
Try this:
<?
if(isset($_POST['stud'])){
$studID = $_POST['stud'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$host="hostname";//your db host
$user="user";//your db user
$pass="pass";//your db pass
$conn=mysql_connect($host,$user,$pass);
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql,$conn);
if(mysql_num_rows($result)>0){//the id was found in the DB, do whatever here...
echo $_SESSION['module'];
$_SESSION['student'] = $studID;
Header("Location: http://www.whereever.com/");//redirect to wherever
$error=false;
}
else{//id was not found
$error=true;}
}//end of isset
?>
<? if($error===true){?> <div> The id was not found.... </div> <?}?>
<form id = "form" action = "<? echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; ?>" method = "post">
<br>
Mark for:
<INPUT id="stud" onkeypress="return isNumberKey(event)" type="text" name="stud" value="Enter Student Number">
<input type="submit" value = 'Continue'>
So what this does is: When the user hits submit, conects to the DB, and checks if the ID exists...if it does, then it redirects it to wherever.com (see comments) and if it don't an error messege will show up. Be sure to change the db variable values to your own ($host, $user, $pass).

Using PHP to flag a form for insert or update function

wondering what the the best way to achieve something is.
To summarise, I have a form that I load by ajax which I use for to both update and insert new rows into a database. To determine whether it is an update or an insert I use the below code (updated forms use the mysql query to populate the form fields).
My code seems sloppy and not best practice. Are there any other suggestion on what would be the best way to do this?
<?
require_once("config.php");
$insert = false;
$update = false;
$targID = 0;
if(isset($_POST['targID'])){
$targID = $_POST['targID'];
$targRow = mysql_fetch_array(mysql_query("select * from events where eventid=$targID"));
$update = true;
}else{
$insert = true;
}
?>
<script type="text/javascript">
var insert = <? echo $insert; ?>+0;
var update = <? echo $update; ?>+0;
......javascript button events, validation etc based on inssert/update
</script>
You already know in the client whether it is an update or an insert, by the fact that you send or do not send the POST data item. So I would write JS in the original page to control the submit and what to do with the data that is sent back. It's difficult to write code without seeing the rest of the page, but at pseudo-code level, you could do the following:
use onsubmit() to catch original submit action
look to see if targID provided
if yes, send update request to server. When row data comes back, fill out form details and display form (you can 'show' a hidden DIV containing the form, for example)
if no - do you need to send anything? - just reveal an empty form (again, show a previously hidden DIV)
Hope this is useful in some way.
You should use native mySQL:
INSERT ... ON DUPLICATE KEY UPDATE
See:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
What's the point in determining that on the client side? Does it make any difference?
For the server side I'd use $targID passed from the hidden field. if it's greater than zero - update, otherwise - insert.

Categories