I am receiving a var from a php page like:
$myId = sanitize_key( $_POST['varPostId'] );
$myId = (int) $myId;
That sets a query:
query_posts(array(
'post__in' => array($myId)
));
Thing is this is an edit page, which means I will be able to change some input data on the page, but when I click the update button the page looses $myId and the query won't work, which means I get an empty page.
I thought to save the id in localStorage but I still didn't get the right logic nor I know if it's the best way. So I am looking into a php or a js solution.
You can save it in a session variable.
That way it should be accessible ad long as the session is alive.
// Start session
session_start();
// Your code
$myId = sanitize_key( $_POST['varPostId'] );
$myId = (int) $myId;
// If session value exist don't do anything
// If not save $myId as session variable
if(!isset($_SESSION["myId"])) $_SESSION["myId"] = $myId;
// Use session variable in query
query_posts(array(
'post__in' => array($_SESSION["myId"])
));
Just keep in mind the session_start. It needs to be started at every page you need to access the variable.
Related
suppose i have a web page with PHP and HTML CSS JavaScript.
values in database are inserted through PHP.
cookies are set using PHP.
cookies are fetched using JavaScript.
cookies of the page
i have an array of subjects stored in cookies. cookies also contain index varible with initial value 0. and arraySize varible with value 9.
At the very first time i fetch the first subject
and take some form response from the user associated to that subject using POST method . when the user click the submit button . the index variable is incrementing at runtime and next subject(next value of array) is inserted in the database.
that is when user clicks the submit button , my code is first updating the subject and then insert the form data into the database.
suppose i have a subject array : subject = {'a' , 'b' , 'c'};
let form variables be subject , class .
i fill the form for subject 'a' and when click the submit button subject inserted is 'b' and class inserted is what user write.
the following JavaScript i have written for incrementing the subject(i increment the index of subject) after submitting the form :
(let say it code1.)
<script>
function incrementCookie() {
var i = document.cookie.indexOf('index');
let currentIndexValue = document.cookie[i + 6] -'0';
document.cookie='index='+(++currentIndexValue);
}
incrementCookie();
</script>
code2: (inserting form variables into the database)
if (isset($_POST['insert']))
{
$co1 = $_POST['co1'];
$co2 = $_POST['co2'];
$co3 = $_POST['co3'];
$co4 = $_POST['co4'];
$co5 = $_POST['co5'];
if($GLOBALS['cols'] == 6)
$co6 = $_POST['co6'];
else
$co6 = 0;
echo "aayush";
$sb1 = $_POST['sb1'];
$sb2 = $_POST['sb2'];
$sb3 = $_POST['sb3'];
$sb4 = $_POST['sb4'];
$sb5 = $_POST['sb5'];
$id1 = $_SESSION['id'];
$sub = $_POST['subject'];
$uname = mysqli_query($con,"select email from users where id = $id1");
$result1 = mysqli_fetch_assoc($uname);
$usersemail = $result1['email'];
$sql1 = "select email from faculty where subjectalloted = '$sub1' and section = (select section from users where id= '$id1')";
$result2= mysqli_query($con , $sql1);
$row1 = mysqli_fetch_assoc($result2);
$facultyemail = $row1['email'];
co1='$co1',co2='$co2',co3='$co3',co4='$co4',co5='$co5',co6='$co6',sb1='$sb1',sb2='$sb2',sb3='$sb3',sb4='$sb4',sb5='$sb5' where id= (select max(id) from respone)");
$sql = "INSERT INTO `respone` (`subject`,`usersemail`,`facultyemail`, `co1`, `co2`, `co3`, `co4`, `co5`, `co6`, `sb1`, `sb2`, `sb3`, `sb4`, `sb5`) VALUES ('$sub1', '$usersemail', '$facultyemail','$co1', '$co2', '$co3', '$co4', '$co5', '$co6', '$sb1', '$sb2', '$sb3', '$sb4', '$sb5')";
mysqli_query($con, $sql);
}
code3: (fetching the subject)
$data = json_decode($_COOKIE['subjectArrayCookie'], true);
$index = $_COOKIE['index'];
global $sub;
$sub = $data[$index];
$_POST['subject'] = $sub;
i have tried writing code2 before code1 so that form responses inserted into database first and then
index cookie update. but due to dynamic nature of JavaScript it increments the index cookie and
subject is updated to next subject before inserting the form variables into the database.
i am expecting that, when the user clicks the submit button firstly form data for that subject will insert into the database with their correct subject name and after then same form will open for next subject in the array.
Put your PHP database insertion code at the very top of the file—before everything else, particularly the database query. Allow it to execute first.
Here's why...
all the written code above on the same page.
And from comments:
first i have fetched the subject array from the database
then insert into the cookie
after that i created the form with the submit button
then wrote the code2(inserting into database)
then code1(iincrement index cookie).
All the PHP in the entire file is executed on the server BEFORE any Javascript is executed or HTML rendered.
The result of PHP execution creates a text file containing—ONLY—HTML and Javascript. This text file is sent to the browser. NO PHP is sent to the browser therefore NONE of the PHP is executed in the browser. Only HTML is rendered and Javascript is executed in the browser.
So the order of execution, according to the 1-5 sequence above, is:
ON THE SERVER:
PHP gets data from the database and writes the cookie instructions. (The cookie not yet registered in the browser.)
PHP writes the form HTML code to be sent to the browser. (The HTML is not yet rendered in the browser.)
Upon initial requests of the page if (isset($_POST['insert'])) is NOT executed since there is no $_POST array yet. However, when this file is requested by posting form data to it PHP inserts the posted data into the database.
The Javascript code block text is added to the text file to be sent to the browser. (Javascript is NOT executed here.)
The text file containing cookie instructions, form HTML, and Javascript cookie increment code is sent to the browser.
IN THE BROWSER:
The cookie, written in SERVER step 1, is registered.
The form HTML is rendered.
The Javascript cookie code is executed and increments the cookie.
I'm creating an ticket booking application. I'm trying to create a basic cart using PHP and Ajax, When i click on the add to cart button, It sends the seat number to the "seatchecker.php" file using Ajax which checks if the seat is available, Then if it's available, It sends that seat number to the "seatadder.php" file using Ajax which should add the seat number to the Session array. But each time i click "Add to cart" it just displays the new value, Rather than showing the whole cart. May be it's overwriting the session variable each time? any help would be appreciated. Thanks
<?php
session_start();
// Getting the value sent by checkseats.php using ajax
$seat_added = $_GET['seatadd'];
// ARRAY OF SESSION VARIABLE
$_SESSION['seat_add'] = array();
function multiple_seats_adder($getseat){
array_push($_SESSION['seat_add'],$getseat);
// TESTING
print_r($_SESSION['seat_add']);
// TESTING
echo sizeof($_SESSION['seat_add']);
}
echo multiple_seats_adder($seat_added);
?>
The Problem seems to stem from the Fact that you are initializing the seat_add Key to an Empty Array each time the Script is called. Most likely, that is not what you want. Consider the Code below:
<?php
session_start();
// Getting the value sent by checkseats.php using ajax
$seat_added = $_GET['seatadd'];
// ONLY INITIALIZE THIS TO AN EMPTY ARRAY IF IT DOESN'T EXIST AT ALL:
if(!isset($_SESSION['seat_add'])){
// ARRAY OF SESSION VARIABLE
$_SESSION['seat_add'] = array();
}
function multiple_seats_adder($getseat){
array_push($_SESSION['seat_add'], $getseat);
// TESTING
print_r($_SESSION['seat_add']);
// TESTING
echo sizeof($_SESSION['seat_add']);
}
multiple_seats_adder($seat_added);
I have two tables: trade and user_pokemon_db
I want to copy a specific rows from user_pokemon_db, when an event occurs.
Html code:
echo "<a href='tradecenter.php' onClick='document.write(".trade($db_id).")' >Put in Trade</a>";
When the user clicks on the link, the php function is called which consists on sql query to copy the row.
$sql = " INSERT INTO trade (trade_id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
SELECT (id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
FROM user_pokemon_db WHERE user_id = '".$id."' AND id = '".$db_id."' ";
Problem maybe due to improper writting of the query.. or maybe due to improper formatting of the href!??
What should I do?
I don't know the content of your php function trade() but it seems that you are confusing javascript and PHP.
Keep in mind that in most of case, once the web page is sent to the user browser, the PHP execution is finished. If you want to do a SQL request after a link click, you need to load a new page or to use something like Ajax to run some PHP code again.
The simplest way to do what you want is to pass the pokemon id as a GET variable (= in the URL)
and check this variable on another page and generate the good SQL query :
echo '<a href="trade.php?pokemon_id='.$id.'" >Trade </a>' ;
And the trade.php would do something like that :
$id = $_GET['pokemon_id'] ; // Be Aware of SQL Injections !!
trade($id);
Have a look at this page for more information about forms : http://www.w3schools.com/php/php_forms.asp
( And if you are using GET or POST variables in your SQL query, be aware of SQL Injections )
If you want to run your PHP function without reloading the page, you should use AJAX. Check this page to understand how it works. A very easy way to use it is to use jQuery
I need to be able to retrieve the list of request URLs that are displayed in the browser console, i.e: GET http://mydomain.com/index.php?p=1&curr=GBP&cat=Food. 200. Users can click around my app and apply different filters and scrolls through pages and I need some way of tracking this so that I always know what data has already been loaded for that users session.
I had thought about using PHPs $_SERVER['REQUEST_URI'] and saving them in a session but then I don't know how I would access this session from my JQuery as its JQuery that constructs the URLs.
Has anyone any idea how I can access this data from the console? Is this possible? If not can anyone suggest a workaround?
The PHP / JQuery mess I have so far:
<?php
session_start();
//keep track of requests.
if (!isset($_SESSION['requests'])) {
$_SESSION['requests'] = array();
} else {
if (!in_array( $_SERVER['REQUEST_URI'], $_SESSION['requests'])) {
$_SESSION['requests'][] = $_SERVER['REQUEST_URI'];
}
}
$requests = json_encode($_SESSION['requests']);
print_r($_SESSION['requests']);
print_r($requests); //these both have values
?>
//further down the page is the javascript
$('.filter a').click(function(e) {
var $this = $(this);
var $optionSet = $this.parents('.option-set');
var group = $optionSet.attr('data-filter-group');
filters[ group ] = $this.attr('data-filter-value');
//***more code for filtering etc******/
var paginate_url = $('.paginate a').attr('href');
//THIS IS PART I CANNOT GET WORKING
var visited_urls= <?=$requests?>;
//console.log($.parseJSON(visited_urls));
console.log(visited_urls); //is always empty
var pageno = ''; //somehow check to see if the URL that has been clicked exists int he requests array, if so get the page number and increment.
var next_url = UpdateQueryString(paginate_url, pageno, group, encodeURIComponent(filter_qry));
I'm not completely sure what you're trying to do but I think you can skip the PHP and just use JavaScript and sessionStorage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage or localStorage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage (depending on how persistent you want the data to be)
For example if I want to listen for all clicks on 'a' tags and track whether those hrefs have been visited (and how many times)
$(document).ready(function() {
// store an empty object in session storage when the page loads
sessionStorage.visited = JSON.stringify({});
});
$('a').on('click', function() {
var storage = JSON.parse(sessionStorage.visited),
href = $(this).attr('href');
// when we get a click check to see if this has been clicked before
if (!storage[href]) {
// if not save it and set the count to 1
storage[href] = 1;
} else {
// otherwise increment the count
storage[href]++;
}
sessionStorage.visited = JSON.stringify(storage);
});
If you want to save the urls from your ajax calls the same principle applies but listen for the ajaxSuccess event and store the url from the request in the callback: http://api.jquery.com/ajaxSuccess/
This is my suggestion:
PHP + Javascript Implementation:
In PHP, use $_GET['curr'] and $_GET['cat'] to retrieve the arguements from the URL.
Use $_SESSION['curr'] = $_GET['curr']; to save them per the session.
On your Javascript/jQuery use var curr = "<?php echo $_SESSION['curr']; ?>" to make the PHP session variables available to your Javascript.
Basically the key to have a good PHP/Javascript persistent memory is that you can set PHP content into a Javascript variable by using:
var x = <?php echo '123';?>;
console.log(x); //output '123' to Javascript console
If you need to have a list of all visited urls, you can save them in a PHP array and transfer it to Javascript as well.
On PHP side:
if (!isset($_SESSION['visited'])) $_SESSION['visited'] = array();//initialize the array if doesn't exist
if (!inarray( $_SERVER['REQUEST_URI'], $_SESSION['visited']) { //check if current URL is not in array
$_SESSION['visited'][] = $_SERVER['REQUEST_URI'];//push it to the array
}
On Client side:
//this will convert the PHP array to a Javascript array using json_encode
var visited_urls= <?php echo json_encode($_SESSION['visited']); ?>;
Don't forget to use session_start() on every page you need the session variables.
Javascript Only Implementation:
Use localStorage and keep everything on the client side.
EDIT: Note that localStorage is only supported in IE8 and up, so if versions prior to IE8 must be supported, you will need to use Cookies instead of localStorage.
$(document).ready(function() {
var urls = JSON.parse(localStorage["visited"]) || [];//get the visited urls from local storage or initialize the array
if (urls.indexOf(document.URL) == -1) {//if current url does not exist in the array
urls.push(document.URL);//add it to the array
localStorage["visited"] = JSON.stringify(urls);//save a stringifyed version of the array to local storage
}
});
Hope this helps!
It's unclear what you want to achieve with this feature. You state:
Users can click around my app and apply different filters and scrolls through pages and I need some way of tracking this so that I always know what data has already been loaded for that users session.
What do you want to achieve with this, why isn't the browser's cache enough for you?
My idea for a solution would be to sync server session array with an object inside the Browser via some sort of WebSocket (http://en.wikipedia.org/wiki/WebSocket).
UPDATE2:
It is possible to use localStorage as cache storage as Abel Melquiades Callejo suggests and then read from it bypassing HTTP requests. I would choose what content to save to that cache differently, no server involved:
add a custom attribute data-* to every HTML element you want cached (http://html5doctor.com/html5-custom-data-attributes/);
make a querySelectorAll (https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll) for all HTML elements with that attribute;
storing and retrieving documents from localStorage should be easy now, you need a convention for naming files for easy finding;
storing images implies doing a base64 transformation which increases the size of the data by 34% (image with 64kb will take 86kb in localStorage).
you need a way to find when data in localStorage is obsolete and you need to make requests to the server (perhaps another data-age attribute to specify when should it expire).
However, this localStorage solution is limited to a small amount of data, see this issue https://github.com/RemoteStorage/remoteStorage.js/issues/144. So, although I now see that what you are asking is possible, because of this size limitation to localStorage, I strongly recommend the solutions in my UPDATE1, below.
UPDATE1: The point is that caching mechanisms are incredibly complex. A better alternative would be to use the default browser caching mechanisms:
1. HTML5 cache manifest
Go offline with application cache
http://html5doctor.com/go-offline-with-application-cache/
LET’S TAKE THIS OFFLINE http://diveintohtml5.info/offline.html
Using the application cache
https://developer.mozilla.org/en/docs/HTML/Using_the_application_cache
A Beginner's Guide to Using the Application Cache http://www.html5rocks.com/en/tutorials/appcache/beginner/
2. Server's response headers to HTTP requests
Optimize caching - Leverage browser caching
https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
HTTP Caching FAQ https://developer.mozilla.org/en/docs/HTTP_Caching_FAQ
I need to write a application that checks database from external server every 10 seconds to see if there is new data. Currently I have a javascript that checks if data has changed server by comparing two JSON (the old JSON and the new fetched from server) and if it has alerts user. But that is not what I need in this application. User should be alerted only when data is new, not when it has changed.
I was thinking that maybe I could do this with a PHP code that queries MYSQL and if query num_results is 0 loop until num_results is more than 0 when user gets notified. In this application it doesn't matter whether the new data is available for user in 0,1 second or 10 seconds, just as long as user gets it. This is how I tried to do the MYSQL check, but it isn't working:
<?php
include 'config.php';
if(isset($_GET['ID'])) {
$maxLoop = 20;
while($maxLoop--) {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sth = $dbh->prepare('select * from testit where id = :id');
$sth->bindParam(':id',$_GET['ID'],PDO::PARAM_INT);
$sth->execute();
if($sth->rowCount()>0) {
$results = $sth->fetchAll(PDO::FETCH_OBJ);
echo '{"key":'. json_encode($results) .'}';
exit; // Found new data, end loop and script
}
} catch(PDOException $e) {
break;
}
sleep(3);
} // end while
} // end if
So how can I alter this code to make it work, or should I just try to write some javascript that would do this? And if so, how can I check whether data is new or not, instead of just checking whether it has changed or not?
How do you record 'new' data? is there a timestamp? an auto_increment primary key field?
The easiest method for polling is to simply keep track of the last known id/timestamp and see if there's anything with a higher id/newer timestamp.
As is, your method is quite inefficient. You select ALL records in the table, forcing mysql/pdo to start fetching that data from disk, etc... then simply throw it away after getting the row count. A more efficient method is do to a select count(*) ... and checking that value. This keeps mysql from having to start fetching actual row data from disk. And on some table types (myisam in particular), a count(*) operation is VERY quick.
If you want your application to check for changes every 10 seconds, you will have to use AJAX to make asyncronous requests to a php file on the server. In the php file, you only have to select * from testit where condition=false and you will get your "new data". Here's a link from where you can learn the basics of AJAX :
http://www.w3schools.com/ajax/default.asp