Multiple button form with each routing to different action - php

I have a form that generates multiple buttons based on a MySQL Table. All buttons have unique id and names. How can I check if any of the buttons are pressed and then check which button is pressed and based on it perform some action. Below is the logic I want to achieve :
<div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
$dbhost=DB_Host;
$dbuser=DB_User;
$dbpass=DB_Pass;
$dbname=DB_Name;
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (any button pressed)
{
if($_POST['aButton'])
{
$_SESSION['hello']=1;
// big logic here
}
if($_POST['bButton'])
{
$_SESSION['hello']=2;
// big logic here
}
}
else
{
$selectquery="SELECT * FROM systems";
$result=mysqli_query($conn,$selectquery);
$rowcount=mysqli_num_rows($result);
if ($rowcount>=1)
{
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
?>
<button id="<?php echo $row['type']."Button"; ?>" name="<?php echo $row['type']."Button"; ?>" >Select</button>
<?php } } } ?>
</form>
</div>

You can do something like that.
Here is the form
<form action="process.php" method="POST">
<button name="first" type="submit" value="1">First</button>
<button name="second" type="submit" value="1">Second</button>
</form>
Give the buttons different name attribute.
Now when you click any of these buttons it submit the form to process.php
In process.php you can check which button was pressed by checking the name of submitted button like this:
if( isset($_POST["first"]) and $_POST["first"] == 1 ) {
// First button was pressed
}
if( isset($_POST["second"]) and $_POST["second"] == 1 ) {
// Second button was pressed
}
You will need to adjust this code to your needs but it should do the trick

Related

Refresh a PHP page after checking/unchecking a checkbox

I'm pretty new with PHP, so help please.
I need a web page in php with a checkbox. That page should refresh itself each time I do an action to the checkbox (so for both check or uncheck). Once it’s refreshed the page should keep the latest value of the checkbox.
I tried the following example modifying another code I took from StackOverflow, but it doesn’t works as I wish.
Any suggestion?
<?php
session_start();
$checked = "";
if($_SESSION['myaction'] != $_SESSION['value'])
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
echo ":(";
}
$_SESSION['myaction'] = $_SESSION['value'];
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
echo "checked='checked'";
}
$myaction = 2;
print ">";
?>
</form>
<form method='POST'>
<input name='sharks' type='checkbox' value='1' id='sharks' />
</form>
Some simpple, vanilla, Javascript that makes use of the localStorage ( or sessionStorage ). The click handler will set the checked status and on page load that value will help re-check, or not, the checkbox. Javascript is intended for this sort of purpose - though it is entirely possible to use PHP to re-check the checkbox when the page reloads provided it has some means to check a value against a stored value or a form submission.
document.addEventListener('DOMContentLoaded',()=>{
let chk=document.querySelector('input[type="checkbox"][name="sharks"]');
chk.checked=localStorage.getItem( chk.name )==null || localStorage.getItem( chk.name )=='false' ? false : true;
chk.addEventListener('click',e=>{
localStorage.setItem( chk.name, chk.checked )
location.reload();
});
});
Don't use a checkbox if you don't want the behaviour of a checkbox.
If you are submitting data, use a submit button. Users expect submit buttons to trigger a reload of the page.
<?php
$current_state = get_state_from_database_or_session_or_whatever();
if (isset($_POST['new_state'])) {
if ($_POST['new_state']) == "on") {
$current_state = "off";
} else {
$current_state = "on";
}
update_datebase_or_session_or_whatever_with_new_state($current_state);
}
$other_state = "off";
if ($current_state == "off") {
$other_state = "on";
}
?>
<p>The current state is <?php echo $current_state; ?></p>
<form method="post">
<button name="state" value="<?php echo $other_state; ?>">Set state to <?php echo $other_state; ?></button>
</form>
What you need to is pretty simple- assuming you are submitting the form on the same page.
<?php
$filterUsers=array();
if(isset($_GET['users'])){
foreach($_GET['users'] as $key){
$filterUsers[]=$key;
}
function valueInFilter($value){
if(in_array($value, $filterUsers)){
echo "checked";
}else{
echo "";
}
}
?>
<html>
<head>Filter </head>
<body>
<form method="get" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="checkbox" name="users[]" value="john" id="1" <?php
valueInFilter("john",$filterUsers) ?>>
<label for="1"> John doe</label><br>
<input type="checkbox" name="users[]" value="john" id="2" <?php
valueInFilter("mayor",$filterUsers) ?>>
<label for="2"> John Mayor</label><br>
</form>
</body>
</html>
This is not an job for PHP like Professor Abronsius wrote.
Write it in JavaScript like this:
(() => {
// on page reloaded
const checkboxNode = document.getElementById('sharks')
if (localStorage.getItem('sharkCheckBox')) {
// the checkbox is stored as CHECKED
// e.g. check the checkbox again or what ever:
checkboxNode.checked = true
} else {
// the checkbox is stored as NOT checked
}
// handle the click
checkboxNode.addEventListener('click', function() {
// get the checkbox status
const isChecked = this.checked
// store the checked status inside the browser cache
localStorage.setItem('sharkCheckBox', isChecked)
// there are several ways to to an page reload. Here an example
// see details here https://stackoverflow.com/a/39571605/7993505
location.reload()
})
})()

can't access value of input when i have it inside foreach loop (using post method)

I have a form contains one input (type button) and one image.
when i click on the button it supposed to delete the image (submit the form and get the value of the input which is the id of the image, using post method).
But i can't access the value of the input when i have it inside foreach loop.
because every input created inside foreach has the same name.
https://i.imgur.com/ed9Vv9m.png
i tried var_dump and there is just null value.
this is the form inside the camera view:
foreach($data['galleries'] as $gallery) :
?>
<div align=center>
<form action="<?php echo URLROOT; ?>/gelleries/camera"
method="post">
<input type="button" class="button" name="delete" id="abc"
value="<?php echo $gallery->galleryId; ?>" onclick="return
Deleteqry(<?php echo $gallery->galleryId; ?>);">
</div>
</form>
<?php endforeach; ?>
and this is the controller:
<?php
class Galleries extends Controller {
$this->galleryModel = $this->model('Gallery');
}
$galleries = $this->galleryModel->hiFive();
$datashow = [
'galleries' => $galleries
];
.....
public function camera(){
if (isset($_POST['delete']) && !empty($_POST["delete"])){
$imgid = $_POST["delete"];
$this->galleryModel->deleteimg($imgid);
echo "deleted!";
exit;
}
else
echo "error";
$this->view('/galleries/camera', $datashow);
}
and this is the model where i execute the queries:
<?php
class Gallery {
private $db;
public function __construct(){
$this->db = new Database;
}
.....
public function deleteimg($id){
$this->db->query("DELETE FROM galleries WHERE id = :id");
$this->db->bind(':id', $id);
if($this->db->execute()){
return true;
} else {
return false;
}
}
}
The Deleteqry inside onclick event of the button it's just a function where i check if i get the id of the image when i click on the button:
function Deleteqry(id)
{
if(confirm("Are you sure you want to delete this row?")==true)
window.location="http://localhost:8001/camagru/galleries/camera?
&del="+id;
return false;
}
Add hidden input field in your form block with value of gallery ID, like this:
<form ...>
<input type="button" class="button" name="delete" value="DELETE NOW">
<input type="hidden" name="GallID" value="<?php echo $gallery->galleryId;?>" >
</form>
And in your controller read that value from hidden field:
if (isset($_POST['delete']) && isset($_POST['GallID']) && !empty($_POST["delete"])){
$imgid = $_POST["GallID"];
$this->galleryModel->deleteimg($imgid);
echo "deleted!";
}
This works completly without javascript.

How to make Textarea and submit button in .php file hide for every row in database?

been working on some database data calling into a .php file.
The php file contains an "Add" button, a "textarea" and an "submit" button.
I did added some J Query script to it to make the "textarea and submit" button to hide until "add" button is clicked, and both "textarea and submit" to hide when "submit" button is clicked making "add" button reappear.
Ever thing is working fine but only glitch is, the script is only working for first row in the table, leaving the rest of rows uneffected.
I think i should use a loop or something.. spent couple of hours but couldn't able to figure it out by myself.
my script goes as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "the_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT * FROM input";
$result = $conn->query($sql);
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js">
</script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$().ready = function() {
$('#text').hide();
$('#textsubmit').hide();
$("#addanswer").click(function() {
$('#addanswer').hide();
$('#text').fadeIn('slow').focus();
$('#textsubmit').fadeIn('slow');
});
$('#text').blur(function(){
$('#text').hide();
$('#textsubmit').hide();
$('#addanswer').fadeIn('slow');
});
}();
});//]]>
</script>
</head>
<body>
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<button class="addanswer" id="addanswer"><B>Add Answer</B></button>
<form name="answer" method="post" action="output.php">
<textarea type="text" class="text" name="text" required id="text" placeholder="Please type your question here.."></textarea>
<button type="submit" id="textsubmit" class="textsubmit"><B>Submit</B></button>
</form>
<?php }
} else {
echo "0 results";
}
$conn->close();
?>
</body>
Since you cannot have multiple occurrences of the same ID, you could do something like this.
<?php
foreach( $your_data as $index => $data ){
echo '<button class="addanswer" id="addanswer_'.$index.'"><B>Add Answer</B></button>';
echo '<form style="display:none;" name="answer_'.$index.'" method="post" action="output.php">'; // I dont think openning form from row to row would be nice!
echo '<textarea style="display:none;" type="text" class="text" name="text" required id="text_'.$index.'" placeholder="Please type your question here.."></textarea>';
echo '<button style="display:none;" onClick="addanswer('.$index.');" type="submit" id="textsubmit_'.$index.'" class="textsubmit"><B>Submit</B></button>';
echo '</form>';
}
... Other code stuff.
Now the each row is having a different ID because we have used $index variable. And also we pass the $index to the javascript function as well. So the javascript can do what ever based on the $index value.
You can have your javascript function, something like this.
<script type='text/javascript'>
function addanswer(index){
$('#addanswer_' + index).hide();
$('#text_' + index).fadeIn('slow').focus();
$('#textsubmit_' + index).fadeIn('slow');
}
</script>
Note: I havent checked this code by running it. I think you will get some understanding with this.
Thanks

Submit form redirect variable

I'm trying get a form to redirect to a certain page depending on what option is chosen in a select div. When I press submit, it redirects to the home page. I realize it's because it doesn't change $industry_choice until after the I press the button... is there a method to change this the moment you select a value?
Let's say I choose banking, and $industry_choice = "banking".
if(empty($_POST['industry'])) {
$industry_choice = "";
} else {
$industry_choice = $_POST['industry'];
}
<form method="post" action="http://localhost:8888/wordpress/<?php echo $industry_choice ?>">
<select name="industry">
(lots of options here)
</select>
<input type="submit" class="select-industry" value="Select">
</form>
You are doing it wrong. I think you are not clear with the action attibute of the form.
<?php
if(empty($_POST['industry'])) {
$industry_choice = "";
} else {
$industry_choice = $_POST['industry'];
header('Location: http://localhost:8888/wordpress/'.$industry_choice);
}
?>
<form method="post" action="">
<select name="industry">
(options)
</select>
<input type="submit" class="select-industry" value="Select">
</form>
action attribute will redirect to the page you processed the input. After that you will redirect it to targeted location.

php validation on a empty field

hi guys i am kinda new to php and i am trying to add validation on to the form. i want it so the form will not submit if it is empty.
<form id="form1" name="form1" method="post" action="category_created.php">
Enter a New Category Name :
<label for="cat"></label>
<input type="text" name="cat" id="cat" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
and the form is being submitted to the file where the contents is being submitted to the database:
<?php
//category name received from 'new_category.php' is stored in cariable $cat
$cat=$_POST['cat'];
$qry=mysql_query("INSERT INTO category(category)VALUES('$cat')", $con);
if(!$qry)
{
die("There Was An Error!". mysql_error());
}
else
{
echo "<br/>";
echo "Topic ".$cat." Added Successfully";
echo "<br/>";
}
?>
any help will be appreciated
thanks
use onsubmit and validate like below
<form onsubmit="return validate()" id="form1" name="form1" method="post" action="category_created.php" >
.....
</form>
and in javasctipt
<script>
function validate(){
if(document.getElementById('cat').value.length<1)
{
alert('Please enter the Category Name');
return false;
}
else
{
return true;
}
}
</script>
or you could submit the form via ajax, in the db-file you check whether the fields are empty, ifso echo an error message and print it via javascript. By doing this you can style everything the way you want to :)

Categories