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);
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 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.
I'm a bit stuck on how to program this: here's what I'm trying to do - I'm writing a simple chat application. There are two parts:
1.The send message part - where a message is typed into the textarea and stored into the database (I implemented this with jQuery AJAX)
**Database: There are two columns in the database, Date and Message
2.The receive message part - where new updates from the server are updated on the page without refreshing the page (I implemented this with HTML 5 SSE).
At a higher level, here's the main problem: I don't know how to write a condition - the condition being the code within the IF block running ONLY when the database has been updated compared to last time the even was fired - in other words, it should update when there is a new message only ONCE, instead of what you get below:
Here's the two code pages (I think it's better to include it all or else the context is a bit vague):
Quick summary:
chat.php - the main chat interface
messaging.php - the send button on the chat redirects here for handling
get_message.php - listens in on new messages and displays it in AJAX style
chat.php
<!-- display window -->
<div class = "message-window" id = "message-window">
Chat starts
</div>
<!-- listens in to new server updates and updates with new messages -->
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("get_message.php");
source.onmessage = function(event) {
document.getElementById("message-window").innerHTML+=event.data + "<br>";
};
} else {
document.getElementById("message-window").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
<!-- comopse message area -->
<div class = "send-wrapper">
<textarea id = "compose"></textarea>
<button type = "button" id = "send">Send</button>
</div>
<!-- event handler for click button to pass along data on the page -->
<script>
$(document).ready(function() {
$("#send").on('click', function() {
$.post(
// file
"messaging.php",
// data
{
// date: Date.toLocaleString(),
message: $("#compose").val()
},
// function after success
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
var singleMessageContent = $("#compose").val();
$("#message-window").html(
$("#message-window").html() + "<br />" + singleMessageContent
);
});
});
});
</script>
get_message.php
<?php
// get_message.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
echo "retry: 1000\n";
// Create connection
$link = mysqli_connect('localhost', 'root', 'root', 'button');
// If number of rows changed from last retry
IF BLOCK (...)
// Get the most recent row
$query = "SELECT message FROM messages ORDER BY Date DESC LIMIT 1";
$result = mysqli_query($link, $query);
// echo the message field
$most_recent_row = mysqli_fetch_row($result);
echo "data: {$most_recent_row[0]}\n\n";
IF BLOCK (...)
flush();
?>
As you can see, what I'm stuck on is the if block - the event is fired every time by the EventSource object on chat.php (this is correct I presume?), so how do I compare the database in question AT DIFFERENT times the event was fired? I need this because I'd like to write this such that messages show ONLY when the database is updated.
if(current_database_rows != old_database_rows)
Here are my thoughts:
Something to do with a global variable? In terms of setting the global variable to count the number of rows in the database at the end of each execution of the php code, run mysqli_num_rows($result), and compare to this variable. My question is - how would you create this "shared" variable that doesn't lose its value in between firing events?
If you can fill me in on a possible condition, or an alternative solution, or other ideas, I'd appreciate it. Thanks!
If you're storing the date(hopefully time?) that a message is sent, you could return the time of the last chat message then keeping sending back that updated value to your query(through ajax) to only receive chat past that time.
Upon the ideas that were mentioned by the folks kind enough to answer, the simplest way is to keep an additional field in the database when a message is added as a record. This shows whether the message has already been retrieved or not. Once it has, it's set to true, bounced back to the jQuery in chat.php to handle, and voila, it's solved. :) Thanks guys!
I'm using PHP for a simple Contact Form. I'm trying to generate an unique ID for each form submitted. For example, the first email is #001, the second #002, 3th #003 etc.
I'll use the ID in the autoreply (or autoresponse?) e-mail: "You are the #016 person to make contact.", for example.
Can be with PHP or JavaScript (can it be with JS? I don't know! But I prefer PHP!). But I have no idea about how I can do this.
I'm not using a database.
Since you're (probably) going to store received information in a kind of database, you generate id on insertion into database. Autoincrement ID field should do the trick.
edit: It also sounds reasonable to reuse google forms
You can use php's uniqid() function to generate unique id each time.
Update 1:
It's a very useful function. The probability of generating same id is really minimum. For more information please visit the link
Update 2:
You can use simple text file/csv to store one line at a time to keep track of it. When the user submit the form you generate unique id each time and reply to client and at the same time you store it to a normal text file if you like. Hope this will help.
There are several ways to do this. The most simple of those is to create a file which will store the number of form filled and you can increase its value for each form filled.
Here is the example copied from: Read and write to a file while keeping lock
//Open the File Stream
$handle = fopen("file.txt","r+");
//Lock File, error if unable to lock
if(flock($handle, LOCK_EX)) {
$count = fread($handle, filesize("file.txt")); //Get Current Hit Count
$count = $count + 1; //Increment Hit Count by 1
ftruncate($handle, 0); //Truncate the file to 0
fwrite($handle, $count); //Write the new Hit Count
flock($handle, LOCK_UN); //Unlock File
} else {
echo "Could not Lock File!";
}
//Close Stream
fclose($handle);
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