Make button active if session variable matches - php

Situation
I have 3 buttons that are designed to be able to switch between different company's.
I have put those buttons in a form:
echo '<form action="?" method="post">';
foreach ($_SESSION['bedrijf'] as $value) {
echo '<button type="submit" class="btn btn-default" name="bedrijf_keuze[]" value="bedrijf_keuze_'.$value.'"><img src="images/logo_'.$value.'_small.png" height="40"></button> ';
}
echo'</form>';
Thru POST I am using this as an session variable into the rest of the system:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
foreach($_POST["bedrijf_keuze"] as $key=>$value)
{
$bedrijf_keuze = trim(mysqli_real_escape_string($mysqli, $value));
$_SESSION['bedrijf_keuze'] = $bedrijf_keuze;
}
}
Now when an button is clicked the form is send and when I echo I see the correct value of $_SESSION['bedrijf_keuze']
To be able to see which company is chosen I have replaced class="btn btn-default" with if($_SESSION['bedrijf_keuze'] == "bedrijf_keuze_'.$value.'") { echo 'class="btn btn-default active"'; } else { echo 'class="btn btn-default"'; }
Problem
The button that is clicked and where the session value is set for is not shown as active.
The final code of the form is now:
echo '<form action="?" method="post">';
foreach ($_SESSION['bedrijf'] as $value)
{
echo '<button type="submit" ';
if($_SESSION['bedrijf_keuze'] == "bedrijf_keuze_'.$value.'") {
echo 'class="btn btn-default active"'; }
else {
echo 'class="btn btn-default"';
}
echo ' name="bedrijf_keuze[]" value="bedrijf_keuze_'.$value.'"><img src="images/logo_'.$value.'_small.png" height="40"></button> ';
}
echo'</form>';
When I echo $_SESSION['bedrijf_keuze'] and bedrijf_keuze_'.$value.' the values are corresponding. So what went wrong and how to solve this?

The problem you are facing is that you are comparing values that never can correspond.
"bedrijf_keuze_'.$value.'" != '"bedrijf_keuze_'.$value.'"'
Code
<?php
$value = 'foo';
echo "bedrijf_keuze_'.$value.'";
echo '"bedrijf_keuze_'.$value.'"';
Output
bedrijf_keuze_'.foo.'
"bedrijf_keuze_foo"

Related

PHP Post form not working

I can not get my form to $_POST. Does anyone have any ideas?
<?php
require_once ($_SERVER['DOCUMENT_ROOT'].'/functions/requirements.php');
if ($_SESSION['loggedin'] != true){
forceRedirect('./hub.php?page=login', 0);
}else{
$row = DB::queryFirstRow("SELECT status FROM app_vendor WHERE user_id=%i LIMIT 1", $_SESSION['user_id']);
$status = ($row['status'] - 1);
if (isset($_POST['submit'])){
echo "worked";
//forceRedirect('./hub.php?page=dashboard', 0);
//die();
}else{
include ($_SERVER['DOCUMENT_ROOT'].'/vendor_template/top.php');
function label($url,$file){
$html =<<<EOF
<li>
<img width="250" height="300" alt="---Non Viewable PDF DOCUMENT---"" src="$url" />
<div class="text">
<!-- <div class="inner">Sample Caption on Hover</div> -->
</div>
<input type="text" name ="$file" id="form-field-1" placeholder="Document name" class="col-xs-10 col-sm-30">
</li>
EOF;
return $html;
}
if ($documents = DB::query("SELECT name, url FROM files WHERE user_id=%i AND status=%i", $_SESSION['user_id'] , $row['status'])){
echo '<h3> <center> Please label your documents </center> </h3>';
echo '<form method = "POST">';
echo '<ul class="ace-thumbnails clearfix">';
foreach ($documents as $document){
$file = substr($document['name'], 0, -4);
echo label('../'.$document['url'],$file);
}
echo '</ul>';
echo '<center>';
echo '<br>';
echo '<br>';
echo '<br>';
//echo '<button type="submit" value ="submit" class="btn btn-primary" data-toggle="button" aria-pressed="false">Submit</button>';
echo '<input type="submit" name="sumbit" value="submit" />';
echo '</center>';
echo '</form>';
}
include ($_SERVER['DOCUMENT_ROOT'].'/vendor_template/bottom_label.php');
}
}else{
// not logged in
}
?>
Ask me for any questions. When I submit the form I get no return from $_POST['submit']. I hope I am missing something I over looked. Any help would be appreciated.
SOLVED. RE Wrote the code and it fixed it. Removed the function and combined the html with the php. Thanks everyone for the help!

Delete li entry in database with PHP

I am working on a website where the user can enter the money he owes a friend. On one page the user can see all the entrys he made so far and should be able to delete them aswell. All entrys are inserted in a DB. For this overview page I use following structure:
<ul class="list-group">
<?php
$isEmpty = true;
while ($data = mysql_fetch_array($res)) {
if ($data['isDebt'] == 0) {
$isEmpty = false; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<li class="list-group-item" name="Debt_ID" value="<?php echo $data['Debt_ID'] ?>"><span class="badge"><?php echo $data['value']; ?></span><?php echo $data['name']; ?>
<button name="delete" type="submit" id="delete" class="btn btn-xs btn-danger pull-right">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</li>
</form>
<?php }
}
if ($isEmpty) { ?>
<li class="list-group-item">No debt!</li>
<?php
} ?>
</ul>
One debt entry has the following values:
Debt_ID (numeric)
Name (like "pizza from jack")
Value (the price. for example "10")
The button for each li element should delete the entry in the DB via Debt_ID. I've used the following SQL statement so far:
DELETE FROM Debt WHERE Debt_ID='$debt_ID';
In PHP it looked like this:
if (isset($_GET['delete'])) {
$debt_ID = trim($_POST['Debt_ID']);
$res = mysql_query("DELETE FROM Debt WHERE Debt_ID='$debt_ID';");
if ($res) {
$errTyp = "success";
$errMSG = "Successfully deleted";
} else {
$errTyp = "danger";
$errMSG = "Error occured";
}
}
My problem right now is that I am not able to get the Debt_ID which I've entered with PHP in the li element. Does anyone know a better approach or what I am doing wrong?
I am developping with Cloud9 so I could invite someone if interested.
When you load all the debts, you can do that with a select statement and loop through the result set. In the loop you can put the id in hidden inputs in each li element:
$sql = "SELECT debt_id, name, value FROM debts WHERE user_id = " . $user_id;
$result = $conn -> query($sql);
if ($result -> num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<li>
<span>' . $row["name"] . '</span>
<span>' . $row["value"] . '</span>
<input type="hidden" value="' . $row['debt_id'] . ' name="id-to-delete">
</li>';
}
} else {
echo "no results";
}
The delete.php file should contain:
<?php
if (isset($_POST['id-to-delete'])) {
$idToDelete = $_POST['id-to-delete'];
// sql to delete a record
$sql = 'DELETE FROM debts WHERE debt_id=' . $idToDelete;
if ($conn->query($sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
?>
After the form element simply add
<input type="hidden" name="Debt_ID" value="<?php echo $data['Debt_ID'] ?>">
Then remove the same information from the li element.
When submitting a form, input elements with a name attribute are what gets passed along to the next page.

php condition on button

I have this problem:
on the following code i made a form with a condition, where if the "profileid" is in array friends then print the button "add to friends" else "remove to friends" but the second condition don't work it don't prints anything and when i load the page for the first time, there is ever the button "add to friends" either if there's already the "friend id" in the array.
Here is my code:
<?php
$userid = $_SESSION['userid'];
$profileid = $_SESSION['profileID'];
$compressed_friends=mysql_query("SELECT friends FROM users WHERE id LIKE '$userid'");
$friends = explode (',',$compressed_friends);
if(isset($_POST['addFriends']))
{
$compressed_friends=$profileid.','.$compressed_friends;
mysql_query("UPDATE users SET friends='$compressed_friends' WHERE id='$userid'");
}
elseif(isset($_POST['removeFriends']))
{
array_filter($friends,$profileid);
$compressed_friends=implode(',', $friends);
mysql_query("UPDATE users SET friends='$compressed_friends' WHERE id='$userid'");
}
else
{
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<?php
if(!in_array($profileid, $friends))
{
echo' <button type="submit" name="addFriends" class="btn btn-primary col-lg-3">Add to friends</button>';
}
elseif(in_array($profileid, $friends))
{
echo '<button type="submit" name="removeFriends" class="btn btn-danger col-lg-3">Remove to Friends</button>';
}
?>
</form>
<?php } ?>
Let me try to answer as I am a beginner in PHP.
I found there is the problem on echo. You used ' to cover the ".
echo' <button type="submit" name="addFriends" class="btn btn-primary col-lg-3">Add to friends</button>';
You can try this out, perhaps it will solve your problem.
echo "<button type='submit' name='addFriends' class='btn btn-primary col-lg-3'>Add to friends</button>";
Thanks!

textarea content auto clears whenever i click the form submit button [PHP]

I have a textarea with a form submit button. Whenever I click the submit button, the content on my textarea clears. but i dont want to clear the content of my textarea. here is my code
codepage.php
<?php
$ans = "hello";
if (isset($_POST['textcode'])) {
{
if ($_POST['textcode'] == $ans) {
echo "<div id=errorPlace>proceed to next lesson</div>";
}
else
{
echo "<div id=errorPlace>Error</div>";
}
}
}
?>
<form method="POST" name="validatePHP">
<textarea name="textcode"></textarea>
<input type="submit" class="btnSubmit" title="Submit Code" name="add" value=""></input>
</form>
thanks for the answers! It worked. now i have another question, what if the textarea has already a preloaded text in it and when I type in another text in it and click the submit button, the textarea should have now have the text that i inputted and the preloaded text in the textarea.
here is my updated code
<?php
$ans = "hello";
if (isset($_POST['textcode'])) {
{
if ($_POST['textcode'] == $ans) {
echo "<div id=errorPlace>proceed to next lesson</div>";
}
else
{
echo "<div id=errorPlace>Error</div>";
}
}
}
?>
<form method="POST" name="validatePHP">
<textarea name="textcode"><?php if(isset($_POST['textcode'])) {
echo htmlentities ($_POST['textcode']); }?>hell</textarea>
<input type="submit" class="btnSubmit" title="Submit Code" name="add" value=""></input>
</form>
Try render content after submit
<textarea name="textcode"><?= $_POST['textcode']; ?></textarea>
<textarea name="textcode">
<?php if(isset($_POST['textcode'])) {
echo htmlentities ($_POST['textcode']); }?>
</textarea>
Maybe you could do it with $_SESSION?
at the top of your page type session_start();
then inside
if ($_POST['textcode'] == $ans) {
echo "<div id=errorPlace>proceed to next lesson</div>";
}
add the code $_SESSION['textareaMsg'] = $_POST['textcode']; like this...
if ($_POST['textcode'] == $ans) {
echo "<div id=errorPlace>proceed to next lesson</div>";
$_SESSION['textareaMsg'] = $_POST['textcode'];
}
then where your text area is set just replace it with this.
<?php
if(isset($_SESSION['textareaMsg'])){
echo '<textarea name="textcode">'.$_SESSION['textareaMsg'].'</textarea>';
}else{
echo '<textarea name="textcode"></textarea>';
}
?>
This works by saving the text area as a session variable when you submit the form, and checking if its set when you load the form, if it is then it will replace the contents of the text area with what is set in the session. Hope this helps!
Try following code
<?php
$ans = "hello";
$textcode = ""; //declare a variable without value to avoid undefined error
if (isset($_POST['textcode'])) {
{
$textcode=$_POST['textcode']; //assign the value to variable in you if statment
if ($textcode == $ans) { //useing variable in if statment
echo "<div id=errorPlace>proceed to next lesson</div>";
}
else
{
echo "<div id=errorPlace>Error</div>";
}
}
}
?>
<form method="POST" name="test.php">
<!--echo user input -->
<textarea name="textcode"><?php echo $textcode; ?></textarea>
<input type="submit" class="btnSubmit" title="Submit Code" name="add" value=""></input>
</form>

Checkbox onChange submit form

What i have is a array of items from my mySQL database and each item has a checkbox. i am trying to make it so when you click on the checkbox it will submit the information to the database for the item that got checked or unchecked. have i have it is unchecked = 1 and checked = 0. this is for where i want to display the item.
Now my issue is I can't seem to get anything to submit into my database, I don't understand jQuery enough to be able to write a function for it, so i need some help. here is what i got for my code.
if(isset($_POST['submit'])){
foreach($_POST['id'] as $id){
$value = (isset($_POST['location'][$id]) && $_POST['location'][$id]=="0" ? '0' : '1');
$insert = mysql_query("UPDATE items SET location='$value' WHERE id='$id'") or die('Insert Error: '.mysql_error());
}
}
echo '<form id="form1" method="post"><input type="submit" name="submit" value="Submit">';
$result = mysql_query("SELECT * FROM items")
or die("Query Failed: ".mysql_error());
$counter = 0;
echo '<div class="specialcontainer">';
while($row = mysql_fetch_array($result)){
list($id, $item_info, $item_img, $price, $sale, $location) = $row;
if($location == '0'){
$set_checked = ' checked="checked" ';
}else{
$set_checked = '';
}
if($counter % 5==0) {
echo '</div>';
echo '<div class="specialcontainer">';
}
echo '<div class="special"><img src="../images/items/'.$item_img.'" width="130" /><br />';
echo $item_info.'<br />';
echo 'Reg. $'.$price.'<br />';
echo 'Sale $'.$sale.'<br />';
echo 'Slide Show: <input type="checkbox" id="ch" value="0" name="location['.$id.']"'.$set_checked.' /><br />';
echo '<input type="button" value="Edit" name="edit" onclick="window.location.href=\'specials.php?action=edit&id='.$id.'\'">';
echo '<input type="button" value="Delete" name="Delete" onclick="window.location.href=\'specials.php?action=delete&id='.$id.'\'">';
echo '<input type="hidden" name="id[]" value='.$id.' />';
echo '</div>';
$counter++;
}
echo '</div>';
echo '<input type="submit" name="submit" value="Submit"></form>';
so as you can see, i do have the submit button there, but my plan is to remove it for the onChange submit. I've tried the onchange="this.form.submit();" in the checkbox parameter but it don't work properly. so i just want it to submit anytime a checkbox gets clicked on kinda thing.
Would an Ajax solution like this work?
$('ch').click(function() {
//this is what goes into $_POST
var data = 'id='+ $(this).attr('name') +'&checked=' + $(this).is(':checked');
$.ajax({
//This would be the url that would handle updating the MySQL Record
url: my_mysql_handler.php,
cache: false,
type: 'POST',
data: data,
success: function(response) {
alert(response); //or whatever you want to do with the success/fail notification
}
});
});
You should try document.getElementById('form1').submit() in the onchange method of your checkbox

Categories