I'm gonna make this too complicated, just going to break it down to the main parts.
I have a form that changes the boolean of a variable when the form gets submitted, however it gets called by a function, the function has to change the variable.
class updates
{
var $yesno = false;
function updateBool()
{
$this->yesno = true;
}
}
So when the form gets submitted, it will call $up->updateBool() to change the boolean to true. When I do var_dump($up->yesno), it says false when it should be true. If I do this:
class updates
{
var $yesno = false;
function updateBool()
{
$this->yesno = true;
var_dump($this->yesno); // <-- outputs true
}
}
So how come I cannot get the variable to print out true in a seperate script?
EDIT:
$sql = "SELECT boolean
FROM config
WHERE boolean = 'true'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
$up->updateBool();
}
else
{
header("Location: index.php?d=none");
}
This is part of the code where it gets called. I can confirm there are more than 1 record in the SQL statement.
So when the form gets submitted, it will call $up->updateBool() to change the boolean to true
You seem to be switching to a new page, where $up will be a new object. Objects do not persist across requests. PHP "loses its memory" when you call a new page, and all variables are started from scratch.
To persist values across page requests, you would need to use something like sessions.
class updates
{
public $yesno;
function __construct(){
$this->yesno = false;
}
function updateBool()
{
$this->yesno = true;
}
}
Related
So I've built a small conditional to evaluate which button is pressed in my form (as there are 2). This works fine and fires off the correct method and writes the appropriate data to the DB, however my redirect is not working. It saves() to the DB and then simply stays on the page designated as the POST route.
I suspect the problem has something to do with my conditional and the use of $this.
Here is my check_submit method:
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
$this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
$this->invoice_complete();
}
}
Here is one of the 2 methods which I am currently testing:
public function invoice_add_item()
{
$input = Request::all();
$invoice_items = new Expense;
$invoice_items->item_id = $input['item_id'];
$invoice_items->category_id = $input['category'];
$invoice_items->price = $input['price'];
$invoice_items->store_id = $input['store'];
if(Input::has('business_expense'))
{
$invoice_items->business_expense = 1;
}
else{
$invoice_items->business_expense = 0;
}
$invoice_items->save();
return redirect('/');
}
Perhaps there is a better way of handling this in my routes(web) file, but I'm not sure how to go about this.
You should add the return to the check_submit() method. Something like
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
return $this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
return $this->invoice_complete();
}
}
Better yet, you should probably return a boolean on invoice_add_item() and based on that, redirect the user to the correct place (or with some session flash variable with an error message)
I’m building a system that captures info from a POST method and adds them into a PHP $_SESSION. The basic logic I want to follow is:
Check the method and call the relevant function
Check if $_SESSION data already exists via a function
Check if the $post_id variable is already in the $_SESSION's array via a function
Based on the outcomes on these functions, add to the array, create a new array, or do nothing
Here is the code I have written to handle this logic so far. I am looking to get just the add_to_lightbox() function working first, and will move onto the other two after.
session_start();
// set variables for the two things collected from the form
$post_id = $_POST['id'];
$method = $_POST['method'];
// set variable for our session data array: 'ids'
$session = $_SESSION['ids'];
if ($method == 'add') {
// add method
add_to_lightbox($post_id, $session);
} elseif ($method == 'remove') {
// remove method
remove_from_lightbox($post_id);
} else ($method == 'clear') {
// clear method
clear_lightbox();
}
function session_exists($session) {
if (array_key_exists('ids',$_SESSION) && !empty($session)) {
return true;
// the session exists
} else {
return false;
// the session does not exist
}
}
function variable_exists($post_id, $session) {
if (in_array($post_id, $session)) {
// we have the id in the array
return true;
} else {
// we don't have the id in the arary
return false;
}
}
function add_to_lightbox($post_id, $session) {
if (!session_exists($session) == true && variable_exists($post_id, $session) == false) {
// add the id to the array
array_push($session, $post_id);
var_dump($session);
} else {
// create a new array with our id in it
$session = [$post_id];
var_dump($session);
}
}
It's stuck in a state where it's always getting to add_to_lightbox() and following the array_push($session, $post_id); each time. I’m unsure whether this code I’ve written is possible because of the nested functions, and how I can refactor it to get the functionality working.
Correction from before, seems like $session is an array of ids..
The problem you are having is that you're modifying the local copy of that array within add_to_lightbox function. You don't need to specifically instantiate the variable as an array, you can just use the following.
$_SESSION['ids'][] = $post_id;
I use Bootstrap and I would like to save the current state of collapse (open or close) in a session variables PHP (not in a cookie).
Could you give me :
- an example code to save the current state in a session variable PHP.
- and an example code to open or not the collapse (depends on the state stored in the session variable) when the page loads.
Thank you very much
First of all, do you really need to store it into session? Does some PHP script work with that value?
Both cases:
You must store somewhere in JavaScript variable the state of collapsed items:
var collapsed = false; // the default value
$('.collapse').on('hide.bs.collapse', function () {
collapsed = true; // on hide, collapsed is true
})
$('.collapse').on('show.bs.collapse', function () {
collapsed = false; // on show, collapsed is false
})
Yes, i need to store it into session:
At each request, you must add the collapsed variable and pass it for example trhough GET method:
$('a').on('mousedown', function() {
var c = collapsed ? 1 : 0;
var href = $(this).attr('href');
if(href.indexOf('?') !== -1) {
$(this).attr('href', href + '&collapsed=' + c);
else {
$(this).attr('href', href + '?collapsed=' + c);
}
});
And somehow save it to session
$_SESSION['collapsed'] = $_GET['collapsed'];
No, i don't need to store into session:
Most modern browsers now have localStorage variable, which is something like session in JavaScript.
Save into variable (in event handlers for example):
if(typeof(Storage)!=="undefined")
{
window.localStorage.setItem('collapsed', collapsed); // saves with no expiration
code.sessionStorage.setItem('collapsed', collapsed); // saves until browser is closed
}
else
{
// Sorry! No Storage support..
}
Load in some startup script:
if(typeof(Storage)!=="undefined")
{
collapsed = window.localStorage.getItem('collapsed'); // again choose one
collapsed = code.sessionStorage.getItem('collapsed');
if(collapsed) {
$('.collapse').collapse('show');
} else {
$('.collapse').collapse('hide');
}
}
else
{
// Sorry! No Storage support..
}
There may be other solutions, but these are the only i can think about. :)
All codes require jQuery
I would do something like this on the PHP side of things. It allows for storing and retrieving the state of multiple ID:s. Session handling is not included; the functions assume there is an active session going. Also, the functions are static since there is no real need to instantiate a class. And it makes for simpler usage.
class Collapse
{
public static function set_state($id = null, $state = null)
{
if ($id === null || $state === null || !is_numeric($state)) {
return false;
} else {
$state = ($state == 0 ? 0 : 1);
$_SESSION['collapse_state'][$id] = $state;
}
}
public static function state($id = null)
{
if ($id === null) {
return false;
} else {
return $_SESSION['collapse_state'][$id];
}
}
}
// --- Sets the state for chosen ID.
Collapse::set_state('info', 0);
// --- Returns the state of the ID.
Collapse::state('info');
Use this class together with the JavaScript proposed by Tomáš Tomíík Blatný and you'll be able to save your states. I'd probably use POST instead of GET though, to make the URL:s look a bit nicer. This can be done by populating a hidden form field or by sending an AJAX request to a PHP-script that only handles the collapse states.
I would like to do these actions step by step:
first DB update
copy file
unlink file
second DB update
It is working, but I don't know if my code is correct/valid:
$update1 = $DB->query("UPDATE...");
if ($update1)
{
if (copy("..."))
{
if (unlink("..."))
{
$update2 = $DB->query("UPDATE ...");
}
}
}
Is it possible to use if statement this way?
I found that it is usually used with PHP operators and PHP MySQL select, for example:
$select = $DB->row("SELECT number...");
if ($select->number == 2) {
...
}
Sure, your ifs work fine. What would look and flow better would be using a function like this:
function processThings() {
// make sure anything you use in here is either passed in or global
if(!$update1)
return false;
if(!$copy)
return false;
if(!$unlink)
return false;
if(!$update2)
return false;
// you made it!
return true;
}
make sure you call $DB as a global variable, plus pass in whatever strings you need etc etc
I have build a website in Drupal, and I am trying to create a fun way to get members involved with the site by building a userpoint system, the system is all in place, but I'm trying to make a shop where they can buy 'titles'.
This is the script I wrote for the shop, with a bit of error handling, but I'm stuck with a problem,
In my JavaScript, I have the function buyitem( ) with 2 variables, which I want to use in my PHP functions which check everything in my database, is there a way to get those variables from JavaScript to the PHP function I wrote without going to an external PHP file?
<?php
include "php-scripts/DBConnection.php";
$con = getconnection();
mysql_select_db("brokendi_BD", $con);
function getKarma()
{
$result = mysql_query("SELECT * FROM userpoints WHERE uid='getUID()'");
$row = mysql_fetch_array($result);
$currentkarma = (int)$row['points'];
return $currentkarma;
}
function getUID()
{
global $user;
if ($user->uid)
{
$userID=$user->uid;
return $userID;
}
else
{
header('Location: http://brokendiamond.org/?q=node/40');
}
}
function hasRole($roleID)
{
$usersid = getUID();
$returnValue = false;
$result = mysql_query("SELECT * FROM users_roles");
while ($row = mysql_fetch_array($result))
{
if ($row['uid'] == $usersid)
{
if ($row['rid'] == $roleID)
{
$returnValue = true;
break;
}
}
}
return $returnValue;
}
function enoughKarma()
{
if ( getKarma() >= $requiredKarma)
{
return true;
}
else
{
return false;
}
}
function buyRole()
{
$currentKarma = getKarma();
$newkarma = $currentKarma - $requiredKarma;
$userID = getUID();
mysql_query("UPDATE userpoints SET points = '$newkarma' WHERE uid='$userID'");
mysql_query("INSERT INTO users_roles (uid, rid) VALUES ($userID, $roleID)");
}
?>
<script type="text/javascript">
buyItem(1 , 0);
function SetStore()
{
}
Function buyItem(itemID,reqKarma)
{
if (<?php enoughKarma(); ?>)
{
<?php buyRole(); ?>
}
else
{
alert('You do not have enough Karma to buy this title.');
}
}
</script>
PHP is a server side script and javascript is a client side, server side scripts are executed before the page loads, meaning your javascript cannot pass variables to it, BUT you can how ever pass php variables to your js.
Best solution in your case is to use ajax to send those variables to php and have the php set variables on it's side, this doesn't quite solve your problem, but with some creativity in your code you can make it happen.
you can either reload the page (which I doubt is what you'r looking for) or make an ajax call to your php script sending the 2 variables.
if you're using jQuery, this should give you an idea of how to do this