i need js insert mysql if button value is checked - php

<script type="text/javascript">
$('.next').click(function () {
var radio_check_val = "";
for (i = 0; i < document.getElementsByName('<?php echo $result['id']; ?>').length; i++) {
if (document.getElementsByName('<?php echo $result['id']; ?>')[i].checked) {
radio_check_val = document.getElementsByName('<?php echo $result['id']; ?>')[i].value;
}
}
if (radio_check_val == "1")
{
<?php
$res1 = mysqli_query($con, "INSERT INTO quiz_log (email,question,answer_choose,answer_correct,category,level) VALUES ('$email','$question','$a1','$answerko','$category','$qlevel')");
?>
} else if (radio_check_val == "2"){
<?php
$res2 = mysqli_query($con, "INSERT INTO quiz_log (email,question,answer_choose,answer_correct,category,level) VALUES ('$email','$question','$a2','$answerko','$category','$qlevel')");
?>
}
});
</script>
It insert both SQL query. if the radio button is checked it insert also the other SQL query. I need insert query if the radio button 1 is checked, and if the radio button 2 is checked the sql query will insert.

PHP is executed on the server before the browser executes JavaScript. So both SQL queries will already be done before the visitor can see the result. He could chose for example one of the results, you can show/hide something using JavaScript and send a choice back to the server.
It looks, as you want to depend on visitors choice, wich query will be done. In this case you have to present a form to the browser, send back the form data and then process the query on another PHP-page.
<?php if(array_key_exists('myradio', $_GET)): ?>
<?php if($_GET['myradio'] === '1'): ?>
First option has been selected.
<?php endif ?>
<?php if($_GET['myradio'] === '2'): ?>
Second option has been selected.
<?php endif ?>
<?php endif ?>
<form method="get" action="">
<input type="radio" name="myradio" value="1"> Option 1
<input type="radio" name="myradio" value="2"> Option 2
<input type="submit">
</form>
In this example the form data is sent back to the same PHP file. You can split it into two files and give the URL of the second one into the action attribute of the <form>.

Related

How to use data when submit button is clicked for next sql query

I am trying to create an html form where i have a dropdown menu populated with data from stations table. I am able to select a station and then i want to use this station name when a button is clicked to display a table with related data. But i don't understand how i can use selected station to create another query when submit button is clicked. Below is my code:
<form method="post">
<label>Choose a station:</label>
<select name="owner">
<?php
$sql = mysqli_query($conn, "SELECT name FROM stations");
while ($row = $sql->fetch_assoc()){
?>
<option value="owner1"><?php echo $row['name']; ?></option>
<?php
}
?>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
i think onclick must be used but i don't understand what would be posted that i can use for new sql query.
When you click submit button browser send form via POST method to the same page and reload it. So you can capture the value selected in the form with this PHP code:
If (isset($_POST['owner'])) {
// mysqli query where the selected value is $_POST['owner']
}

PHP retrieving variables from a large SQL result set

I have been working on my own PHP project. I have hit an obstacle. I am trying to retrieve the results of a database and print out a form for each result set.
I then wish to interact with one particular result either be deleting it or passing it into a function etc..
Heres is my current code :
<?php
while($row = mysqli_fetch_array($result)){
echo '<div id="post">'; ?>
<form action="" method="post">
<?php
echo "<font size=4>".$row['post']."<br>";
echo "posted by : ".$row['username']."<br>";
$id = $row['p_id']; ?>
<input type="submit" name="choice" value="Y">
<input type="submit" name="choice" value="N">
</form>
<br>
</div>
}
<?php
if($_POST['choice']=="Y"){
// progress
functionA();
}
else if($_POST['choice']=="N"){
// delete or remove
functionB();
}
?>
So my goal here would be click Y to progress that particular result or N to delete/remove the result.
However currently by clicking either button all results either get deleted or progress. I do know that the id should be used to differentiate between posts but I cant quite seem to get it to work. Once the button is pressed it passes all results to either function.
First of all, I suppose you want to know the record to delete. So, add an input to your form:
<input type="hidden" name="id" value="<?php echo $row['p_id']; ?>">
Then, in your script, call:
if( $_POST['choice'] == "Y" )
{
// progress
functionA( $_POST['id'] );
}
elseif( $_POST['choice']=="N" )
{
// delete or remove
functionB( $_POST['id'] );
}
Additional problem: how you can use your db connection inside the functions? Assuming your mysqli connection is named $conn, call the function(s) in this way:
functionA( $_POST['id'], $conn );
Side note: First process $_POST values, then retrieve db records and print it.
Side note 2: take a look at prepared statement.
Read more about variable scope
Read more about prepared statements
Use two different <input type="radio">s for each item with the id in the value and let the user select which to delete and which to process.
So for an item with id 1 the outputted HTML would look like:
<input type="radio" name="items[1]" value="delete"><input type="radio" name="items[1]" value="process">
The name forces the items to go to _POST as an array with the ids as keys and the selected action as their values.
Example html: https://jsfiddle.net/gu1gkwod/

How to save entries into db on submit button click only

I have a code like this
<?php
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
} else {
echo "wrong";
}
?>
<form action="" method="post" name="myform">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="submit1">
</form>
I want to save values into db after user clicks the submit button. I have been trying different approaches, but still could not get near to it.
Any ideas/hints what I should do next or doing wrong?
After the given suggesstion below is my code :
<form action="" method="post" name="myform">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="submit1">
</form>
<?php
if(isset($_REQUEST['submit1']))
{
echo "$thismemberinfo[msurf]";
echo " $msurfclicks";
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
//$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo " not set " ;
}
}
?>
you can use isset for checking if button is clicked or not
if(isset($_REQUEST['submit1']))
{
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo "wrong";
}
header("location:".$_SERVER['PHP_SELF']);
}
You need to check if the request has come from the post submit i.e. as others pointed check $_POST['submit']
if(isset( $_POST['submit'] ) {
// your complete rest php code goes here to insert the record
}
On page refresh, it'll see the request is not a post request submitted hence won't execute the php code in the if and will just display the page.
Your code is missing a few things..
To insert entries into the database, you should think more about what tasks need to be carried out, I'll give you a list of them, you have probably done some of these.
1) Connect to the database.
2) Obtain the values entered into the form, and store them in local variables, in your case you have used POST on your form and therefore.. here's an example:
$Field1 = mysql_real_escape_string($_POST['match']); // match?? This post data comes from the name field of your form.
3) Create your query... e.g..
$sql = "INSERT INTO table_name (table_heading) VALUES ('$Field1')";
4) Run the query

How to auto submit a checkbox

Here is HTML/JavaScript:
<form method = "post" style="display: inline;" name="thisform<?php echo $employee->id; ?>">
<input type="hidden" name="user" value="<?php echo $employee->id; ?>" />
<input type="hidden" name="auto" value="<?php echo $employee->stay_live; ?>" />
<h3><input type="checkbox" name="stay_live" onclick="document.forms.thisform<?php echo $employee->id; ?>.submit();" <?php if ($employee->stay_live == '1') { echo "checked"; } ?> title="Click to Stay Live Every Day" /> <?php echo $employee->name; ?>
</form>
Here is PHP:
<?php
if(isset($_POST['stay_live'])) {
$user=$_POST['user'];
$auto=$_POST['auto'];
if ($auto == 1) {
$sql = "UPDATE users SET stay_live = 0 WHERE id = '{$user}';";
}
if ($auto != 1) {
$sql = "UPDATE users SET stay_live = 1 WHERE id = '{$user}';";
}
mysqli_query($dbconnection, $sql);
}
?>
If you see the onclick code in the form, it will auto-submit form and do PHP POST. However, the onclick only works if the checkbox is NOT checked. If it IS checked, the screen does refresh, as if it did thing, but the POST is never submitted.
So to summarize; everything works as expected when the box is not checked and it needs to be set. But to UNSET it, the server function is never called. Can anyone see why?
note: this is test code, so please no comments on sql injection
Checkbox values are not sent when they are unchecked, so $_POST["stay_live"] is not set.
<?php
if (isset($_POST["user"])) // type="hidden" will be sent regardless of checkbox
{
if (isset($_POST["stay_alive"])) echo "Checkbox checked";
else echo "Checkbox not checked";
}
?>
Using Jquery I'd do the following: You need to make a file with the functions that you want to be executed. This file will receive via POST or GET
To your onclick attribute just add an if for your action variable, if(element checked) action = unchecked --- else action = check
--Jquery function
function cBoxSubmit($employId, $action){ // call it in your onclick attribute.
$.post("submitFunction.php",{action: $action, employId: $employId, ...},function(data){ // Parameters: URL file, variables which will receive, call back function
if(data){
// On Success or in your case if checked
// add some code if needed
}
else{
// If unchecked
// add some code if needed
}
}
}
NOTE: echo == return in your php file ... This is how you return data to the call back function in your Jquery function

Disable all input buttons on page if no PHP session exists

I'm doing a site with a voting system. What i want is to disable all input buttons (the ability to vote) if the user isnt logged in (ie. a session doesnt exist). How do i do a check in PHP at the top of the page and then allow/disallow the input buttons? Would i use CSS or jQuery?
Somewhere in the code check if the session is not set:
if(!isset($_SESSION['some_key'])){
$disable = true;
}else{
$disable = false;
}
Then, in the html:
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 1
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 2
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 3
But you still have to check at the serverside before you accept the vote, if the person has voted before, because this form can be edited easily to post the data again and again.
<?php if(!isset($_SESSION['logged']))
{
echo "<script language=\"javascript\">";
echo "$(document).ready(function()
{
$('input[type=submit]').each(function() { this.attr('disabled', 'disabled') });
});</script>"
}
?>
You should dynamically generate a correct HTML code. Something like this:
<?php if(isset($_SESSION['logged'])): ?>
<form> voting form </form>
<?php else: ?>
<p>Sign in to vote</p>
<?php endif ?>
You should also check whether user is logged in before you process a form:
if (isset($_SESSION['logged']) && isset($_POST['vote'])) {
// process form
}

Categories