Count and display button click on page [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am looking for a very simple solution to tracking and displaying the number of clicks of a button on a webpage. I searched Google and all the solutions I found were far more complicated than what I am looking for.
Basically all I need it to do is track every time a single button is clicked, store the value of total clicks in a database and then display that value on the same page. I'm guessing I will need to use PHP/MySQL to accomplish this, can anyone point me in the right direction?
Thank you!

This can be done with PHP/MySQL/jQuery. I haven't tested any of this code and it won't be very effective at tracking bursts of fast clicks, but it should get you started:
Include jQuery in the footer of your webpage
Include click.js (below) beneath the jquery call
Set up an SQL table called click_log that contains user_id (INT) and time (DATETIME)
Include this code at the bottom of your document. It feeds the increment script a user ID (assuming you have a user's ID handy as variable):
<script>
$(function () {
// Event handler for the click
$(document).click(function(e){
// Feed the increment function the user's ID
increment(<?= $user_id ?>);
});
})
</script>
Include a counter div wherever you want the total count displayed, and include get_count.php in it:
<div id="counter">
<?php include("get_count.php?user_id=".$user_id); ?>
</div>
click.js - jQuery function to call the increment script below via AJAX
$(function () {
// Define an increment function to accept a user_id
function increment(user_id){
// Create a data object
data = {
user_id = user_id
}
// Deliver the payload
$.ajax({
type: "POST",
url: "increment.php",
dataType:"JSON",
data: data,
success:function(response){
$("#counter").empty().load("get_count.php?user_id="+user_id);
}
});
}
}
increment.php - PHP script to register a click in database from an AJAX request
<?php
// Set the header to accept JSON
header("Content-type: application/json");
// Insert your database connection here (should probably use mysqli)
$host = "localhost"; // or IP or whatever
$db_user = "admin";
$db_pass = "password";
$db_name = "your_db";
mysql_connect($servername, $db_user, $db_pass) or mysql_error();
mysql_select_db($db_name) or db_name();
// Grab user id from post data
$user_id = $_POST["user_id"];
// Write the query
$sql = "INSERT INTO click_log (user_id, time) VALUES ('".$user_id."', CURRENT_DATE());"
// Encode a JSON response if the query is successful
if(mysql_query($sql)){
echo json_encode("Success");
}
?>
get_count.php - File to load in your counter div that displays total clicks by user
<?php
// Get the user id from the URL ($_GET)
$user_id = $_GET["user_id"];
// Write the SQL to count the number of rows ('clicks') with that user
$sql = "SELECT count(*) FROM click_log WHERE user_id = '".$user_id."';";
// Run the query
$result = mysql_query($count_sql);
// Format the result and set it a variable
$total_clicks = mysql_result($result, 0);
// Print the total clicks by that user
echo $total_clicks;
?>
Hope this helps get you started! :)

Here is about as simple as it gets for saving a number on the server. http://www.w3schools.com/php/php_ajax_poll.asp Or in other words its not that simple. Try out some code and then ask a more specific question.
Note w3schools isn't the best html resource but it does give

I found a text document solution which fits my needs perfectly. I've implemented it, but the problem is that the action remains in the URL after the button is initially clicked so all you need to do to increase the count is to refresh the page. What would be the easiest way to prevent this?
PHP:
if ( ! file_exists('./count.txt'))
{
file_put_contents('./count.txt','0');
}
if (trim($_GET['action']) == 'increment')
{
counter('increment');
}
function counter($action)
{
if ($action == 'count')
{
return file_get_contents('./count.txt');
}
else
{
file_put_contents('./count.txt', (string) (((int) file_get_contents('./count.txt')) + 1));
}
return true;
}
?>
HTML:
<span id="button">Click Here</span>

Related

Delete previous row in database show the next row in database by clicking button

I need Help on this, base on what I already did: In the output every time I click the button it shows the row (comments) in database. But I want that If I click the next button it will show the row (comments) in the database and when I click it again It will delete the previous row (comments) in the database and show the next row (comments).
Here is the code:
<?php
include 'dbh.php';
$commentNewCount = $_POST['commentNewCount'];
$sql = "SELECT * FROM comments LIMIT $commentNewCount";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['id'];
}
} else {
echo "There are number!";
}
?>
This is for the button:
<script>
//jQuery code here!
$(document).ready(function() {
var commentCount = 0;
$("button").click(function() {
commentCount = commentCount + 1;
$("#comments").load("load-comments.php", {
commentNewCount: commentCount
});
});
});
</script>
You have AJAX tagged in your question, so I am assuming that you are somewhat familiar with the term. This can indeed be done by AJAX, but I don't see any AJAX attempts in your code?
Also, when you say delete, do you mean specifically delete by the literal sense, or simply that your comment display works as sort of a sliding function, removing the previous comment from display, showing the next comment in queue? I am going by the literal sense in my example, since that's what I have to assume really.
What you could do, is to have a file that handles all the comments, and displays them however you like. For instance,
<?php
$sql="SELECT * FROM comments ORDER BY id DESC";
$result_set=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_assoc($result)) {
/*
html construction of displaying comments,
echo'ing the row value that displays the comments.
echo $row['comments']; as a guess
*/
}
?>
Let's call that PHP file comments.php for the sake of referencing later on. Also note, that I chose to make an ORDER BY in a descending order. Assuming your comment id is an auto increment, then this will always display the newest comments first, since the highest id's will be the latest entries.
Then, in another file, display-comments.php as an example, you could make a document.ready function, that loads your comments into an element, <div> element for example.
The AJAX function could look like this:
$( document ).ready(function() {
function loadCommentsAjax()
{
$.ajax({
type : "POST",
url : "comments.php",
data : { },
success: function (html) {
$("#commentContainer").html(html);
}
})
}
});
What I do here, is that I encapsulate an AJAX function in a document.ready function. What this does, is that when the document is ready, it fires the AJAX function.
How the AJAX function works, is that we declare a data type. The most common are probably POST and GET. You can look up the different data types, how to handle them, and what they mean specifically. The main difference between POST and GET for instance, is that GET displays its values as parameters in the URL. Since we aren't parsing any data, we could use a GET just fine, since it will have no influence. However, should you ever need to parse sensitive data, where you don't want the user to mingle with the data, then you should use POST.
We then tell the AJAX function, which page/file it should work with. In our example, it will be the comments.php that we created earlier. It will then in the success function, paste the html content into a container that we defined. In this case, commentContainer. Note that it's an id specific targeting, which means our container element needs to have that specific id. Note, that the container is in our main file, the display-comments.php file.
An example of the container could be the following:
<div id="commentContainer"></div>
This div element will then contain the comments and html logic that we made in our comments.php file.
In your button, you can then have another AJAX function, handling the comment deletion, and call our loadCommentsAjax() function on success, to reload our comments in the appropriate fashion.
The AJAX function handling the deletion of comments, would then again have a PHP file that will perform the delete. We'll call this delete-comments.php in our example.
example of our delete AJAX function:
function deleteNewestComment() {
$.ajax({
type : "POST",
url : "delete-comments.php",
data : { },
success: function (html) {
loadCommentsAjax();
}
})
}
Our delete-comments.php will look something like this:
<?php
/*
since you are deleting the latest entry each time, what we could do,
is make an SQL query that deletes the max id from the comments table
*/
$sql="DELETE FROM comments WHERE id=(SELECT max(id) FROM comments)";
$result=mysqli_query($conn, $sql);
?>
We will then have our button call the delete function like so:
<button onclick="deleteNewestComment();">Delete latest comment</button>
Let me know if this is what you were looking for at all, or whether you really just wanted a sliding kind of logic, where you simply iterate through your comments, displaying one at a time.
But in case you did mean literally delete, then wouldn't it be better to have delete buttons linked to each comment, so that you can delete them seperately, and independantly?

Optimize jQuery triggered MySQL-Query

Hello to this great community!
I've already learned a lot by reading many of the questions and answers here. So here is my current problem:
I'm currently creating a simple code which includes PHP, MySQL and jQuery for a simple news ticker. The aim is to check the database for changes without the need of reloading the whole webpage. If there is a change in the database a javascript is executed to reload the whole webpage. With this I want to avoid, that the user has to reload the webpage manually.
This works nicely!
But there is one problem: When too many users are on the webpage a "Too many connections"-Mysql-error occurs. I think this happens because of the many parallel running updates()-functions.
Do you have an idea how to optimize this code?
<script>
function updates(){
$('#updates').load('updates.php');
}
setInterval("updates()", 1000);
</script>
<div id="updates"></div>
updates.php
<?php
// Get latest value the database
$result = mysql_query("SELECT update FROM updates_db");
$row = mysql_fetch_object($result);
// Compare the value from the database with the current value which is saved in a session
if($_SESSION['update'] != $row->update) {
// If the values do not match, update the session and reload the whole webpage
$_SESSION['update'] = $row->update;
echo '<script>
location.reload();
</script>'
}
Try something like this instead of refreshing the whole page.
PHP
<?php
header('Content-type: application/json');
$result = mysql_query("SELECT update FROM updates_db");
$row = mysql_fetch_object($result);
if (($update = $_SESSION['update']) != $row->update) {
$_SESSION['update'] = $row->update;
echo json_encode(['update' => null]);
exit;
}
echo json_encode(['update' => $update]);
Javascript
$.post('updates.php')
.done(function( data ){
if( data.update){
//update DOM with new update
}
});
And increase your timeout interval. One request/1000ms is very frequent.

PHP, Javascript, mysql, and selection lists

I'm working on a piece of some software that will grab information from a mysql database and throw it onto our form dynamically. I'm running into a couple problems, though. I'll give a quick rundown of some functionality.
When the form loads, we have a ton of selection lists. These are all populated through arrays with various keys/values in php. When I select an option from one list, we'll call it a "customers" list, on-click I need to check if that customer has a special flag (stored in the database), and update another selection list based on that data.
How I understand the core of my solution is I need to have a javascript trigger on-click, which I have. The function that is called references a php page that handles the database query through a class and it's function.
<script>
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer='+customer);
}
</script>
This function then talks to my php. The CustomerProvider class works 100%. I have tested that thoroughly on other pages. The problem arises when I try to actually get my selection list to change.
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != '')
{ ?> <script>var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';</script> <? }
else return;
}
?>
I'm coding in javascript literally for the first time ever and they kinda just threw me on this project. I know that my portion isn't being read as html or output as I intend. I know that every other part of the php and the first bit of javascript seems to be executing okay. Any help would be incredibly appreciated.
You seem to be on the right track but just for your own sanity here are a couple pointers. You shouldn't be returning Javascript from PHP for a situation like this. Instead you should be relying on Javascript promises to wait for a response containing just the data and continue the execution of your client code once you have your values returned. Take a look at this:
<script>
function setService() { // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer=' + customer, function(data) {
console.log(data + ' was returned from your php script!');
if(data.hasContract=='1')
$('#ticket_service').val('Contracted Hours');
else
$('#ticket_service').val('No Contracted Hours');
});
}
</script>
And then your PHP script will just look like this:
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){
$hasContract = 1;
}
else
$hasContract = 0;
echo json_encode(array('hasContract' => $hasContract));
}
?>
Therefore returning only the data needed for the client app to continue... not application logic
Your code isn't doing anything with the output of the PHP script. If you want the output to be inserted somewhere in the DOM, you should use .load() rather than $.get.
$("#someelement").load('thePage.php?key=setService?customer='+customer);
This will put the output into <div id="someelement">. If the output contains <script>, the script will be executed.
If you know the result is just a script, you could use $.getScript() instead of $.get. Then the output should just be the Javascript, not enclosed in HTML tags like <script>.
The problem here is that you are not using the result from the server. Your JavaScript may indeed be correct, but the browser never sees or runs it. From the docs:
Request the test.php page, but ignore the return results.
$.get( "test.php" );
Try this code, which utilizes the $.getJSON() shortcut function. I've written two versions, which you can see commented in the code. One moves the logic for determining contract status into the JS. Either should work.
PHP
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
// Default output
$output = array('hasContract' => false);
// Customer has contract
if ($s != '')
$output['hasContract'] = true;
echo json_encode($output)
// Alternative: PHP just returns getHasContract, JS determines action
// (this would replace $ouput, conditional, and echo)
// echo json_encode(array("hasContract" => $s));
}
?>
JavaScript
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.getJSON('thePage.php?key=setService?customer='+customer, function(result) {
// Alternative
// if (result.hasContract != "")
if (result.hasContract)
{
var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';
}
});
}
As others wrote, your code doesn't do a thing with the GET variables.
the element "ticket_service" doesn't exists on page and even if it was, the code has no impact on the page that sent the request, you should print/echo the result you want to display/return and then manipulate it with JS/Jquery.
since I'm against GET and pro POST which is safer method, here's an example with POST:
JS:
function postSomthing(customerID){
$.post(
'thePage.php',
{key:'setService',customer:customerID},
function(data){
if(data!='x'){
$('#ticket_service').val(data)
}
else{alert('no ticket');/*whatever you want to do*/}
});
}
PHP(thePage.php) :
if(isset($_POST['key']) && $_POST['key'] == 'setService'){
$customer = intval($_POST['customer']);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){echo 'x';/* false, or whatever you want*/}
else{echo 'Contracted Hours';}
}
notes:
you should create an element with the id "ticket_service" in the viewed page and not in the backstage one.

How to make an Excel file an interactive webpage?

How can I make my Excel file work as a web page where people can enter data and it will stay there? I am new to this!
Required technologies for this exercise: JavaScript, JQuery, PHP, AJAX and MySQL. And Excel! All this requires a minor edit, only adding 3 lines of text to the generated html page.
A running demonstration is at https://ip.jawfin.net
I'd like to state that the html of Excel Save As has been badly maligned - Excel 2013 generates a very clean html, its styles are built into the comments (so only 1 file is produced, no CSS), it's well indented and easy to read. The only down-side is the names of classes of the styles are rather arbitrary! No JavaScript, just plain html - it's a nice place to start then refine in Notepad++ or your favourite editor. Mind you, the lack of CSS may come back to bite you, for extensive use I would recommend extracting the comments to build a CSS from.
Firstly, our Excel. Here's one I made, and this is for a simple application which puts your IP in the cell you select on the screen. (My practical use of this method was for a month scheduler, this "pick a colour" is good to demonstrate all the features and I hope will be easily adaptable.) One change though, I scramble the visitor's IP as a protection.
Here's my Excel file: https://ip.jawfin.net/ip.xlsx
We don't export the whole spreadsheet, just select the cells you want which will make up the webpage. In my case: -
With the cells selected, go into File / Save As, pick your folder, Save as Web Page (*.htm), choose only the Selection, give it a Title if desired, name it index.htm and Save!!
Now, rename index.htm to index.php as we will putting php code in it. Now for the 3 lines of code to make this an interactive webpage. Between the </body> and </html> at the bottom insert these 3 lines: -
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<?php include 'excel.php';?>
<script src="excel.js"></script>
so we have: -
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<?php include 'excel.php';?>
<script src="excel.js"></script>
</html>
The 1st line importing JQuery for our AJAX to work.
The 2nd is to get the user's IP. Note, this can do a lot more if required, for instance in my implementation I use it to log into a phpBB forum and get the logged-in username and permissions. This php also shows how we can pass server php variables to the local javascript.
The 3rd line is the brains, doing all the work and communicating with the server for updating and fetching data.
(You know, this really could just be one line of code if I embedded the script lines as echo's in the php - but that loses readability in my opinion.)
For the database: on your webserver log into your panel and create a new database for this app.
Then log into your phpMyAdmin to create the table[s] your application needs.
In this case it's one table, called cell_ip. Its structure: -
field:cell; type:integer; index:primary + unique
field:ip; type:text
Or as it appears in phpMyAdmin: -
The files this project uses are: -
index.php the one we just created in Excel, goes in the web folder
excel.php the file which fetches server-side variables (note we could also use this to inject dynamically created controls)
excel.js the script running local interface, also communicates with the server
server.php the database handler on the server, deals with the AJAX requests and database manipulations
settings.php just a means of storing the database configuration in a safe place
All these files go into the root of the web folder, except settings.php which goes in home, the folder above web, where the Internet cannot see it, but our server.php can.
Note the 4 php files are all doing completely different jobs:  index.php is the web page they see, the only user visible php file.  excel.php injects code into index.php, into the webpage, where it can get server-side settings for the client.  server.php is like a program running on the server alone, an application which our webpage calls to save and load data into our server-side database.  settings.php is just a glorified ini file, a quick means of storing sensitive info out of sight from the Internet.
All the source has relevant comments explaining the processes - but I'm willing to answer any questions I can, please note though that I am not an expert. So, without further ado, the work source codes.
(Edit: As I can't fit the full source here I'll provide links. Please let me know if there is a smarter/preferred way. As it is, I renamed these to .txt so it doesn't behave like a webpage!)
index.php - This too big to include, so download, or make it yourself from instructions above.
excel.php
<?php //excel.php
//Let's create a string specific to the user without giving away private info
$ip = $_SERVER['REMOTE_ADDR']; //I'm going with hashing the md5 of their IP, then mod'ing back to 12 digits (from 38)
$hash = fmod(hexdec(md5($ip)),1e12);
echo '<script>'; //clever means of getting a php variable into javascript
echo 'var user_ip = ' . json_encode($hash) . ';'; //replace $hash with $ip you want to see the real address!
echo '</script>';
?>
excel.js
//excel.js
$.ajaxSetup({ cache: false }); //needed to stop IE/Edge from caching AJAX GET requests
var cells = document.getElementsByTagName("td"); //array of all cells, excel assigns them type HTML table cell "td"
var updating = false; //prevent flicker if writing to the dataset and a read overwrites our status messages
var reentry = false; //prevent overlapping refresh. polls 1 a sec, 5 second time-out, could lead to massive overlap!
var addingStr = ' -- Adding IP --'; //const not used for backwards compatibility, IE9 etc.
var removeStr = ' -- Removing IP --';
var replaceStr = ' -- Replacing IP --';
for (var i = 0; i < cells.length; i++) { //you can assign different aspects by the .innerHTML
cells[i].style.cursor = 'cell'; //or 'pointer' - the default is the edit caret cursor which looks ugly
cells[i].id = i; //tag our elements, but note this is happening AFTER the DCOM scan so getElementById() won't work
cells[i].onclick = function() { cellClick(this); };
}
refreshScreen();
setInterval(function() { //ajax poll, refresh every second!
refreshScreen();
}, 1000);
function cellClick(cell) {
updating = true; //don't allow the refresh to remove our status comment in the cell
var mydata = 'action=';
if (cell.innerHTML == "" || cell.innerHTML == " ") {
cell.innerHTML = addingStr;
mydata += 'c'; //write into this cell the users IP
} else {
if (cell.innerHTML == user_ip) { //let's be smart and allow them to remove their own IP :)
cell.innerHTML = removeStr;
mydata += 'd'; //clear/delete this cell
} else { //it's someone else, hijack them!!
cell.innerHTML = replaceStr;
mydata += 'u'; //update this cell
}
}
mydata += '&cell=' + cell.id + '&ip=' + user_ip; //add our parameters
$.ajax({ //JQuery ajax, so much cleaner and safer than using JavaScript ajax
url: "server.php", //our server-side worker
type: 'POST', //database changes, use POST, we don't want a webcrawler or a cache hitting a GET with parameters
data: mydata,
timeout: 5000, //5 second should be ample, but if they lose connectivity allow it to fail
success:
function(data) {
updating = false;
if (data != 1) { //no matter what, in this CRUD only 1 record should have been affected
alert('Data update error. Parameters: ' + data + '. Result: ' + data);
}
refreshScreen(); //refresh screen with new data
},
error:
function(xhr, ajaxOptions, thrownError) { //put better error handling in if this fires too often!
// alert('Data = ' + mydata + '. Error # = ' + xhr.status + '. Message = '+thrownError); //uncommend to debug
updating = false;
refreshScreen();
}
});
}
function refreshScreen() {
if (updating) return; //just wait a second
if (reentry) return; //we're already pending a refresh
reentry = true;
var mydata = 'action=r'; //we want to Read the data - stored in a varible in case we turn on our error alert
$.ajax({
url: "server.php",
type: 'POST',
data: mydata,
timeout: 5000,
// dataType: 'json', //just saves us a line of formatting text on success. !!commented out, not debug friendly
success: function(data) { //on recieve of reply
reentry = false;
if (updating) return; //they clicked between the request and the return here, just wait it out, next second!
data = JSON.parse(data); //i prefer this instead of dataType:'json' so I check server script errors in the throw
var results = []; //get our data into a 2 dimensional array (has 2 dimensions as our query returned 2 fields
for(var x in data) { //get all the data ready before we touch the screen, cut down any possibly latency
results.push(data[x]);
}
for (var i = 0; i < cells.length; i++) { //reset screen
if (cells[i].innerHTML != removeStr) { //skipping the "Remove" messages (dirty read) - will clean up below if they were removed!
cells[i].innerHTML = ""; //clear field
}
}
for (var i = 0; i < results.length; i++) { //now we stuff our cells with the IPs we have
cells[results[i][0]].innerHTML = results[i][1]; //first array element is cell number, the second is the IP
}
//as the "Remove" status was skipped above need to loop again to clear any found
for (var i = 0; i < cells.length; i++) { //backwards clean
if (cells[i].innerHTML == removeStr) { //text is here as this cell didn't come through the SELECT
cells[i].innerHTML = ""; //clear field
}
}
},
error:
function(xhr, ajaxOptions, thrownError) { //uncomment alert for debugging
reentry = false;
// alert('Query = ' + mydata + '. Error # = ' + xhr.status + '. Message = '+thrownError);
//Note that xhr.status == 200 is an OK from the server but JSON invalid, so check for that first!
}
});
}
server.php
<?php //server.php
if (!isset($_POST['action'])) exit; //no action parameter, just leave. could echo an error message if required though
$action = $_POST['action'];
if (!strpos(' crud',$action)) { //note the space out front, or else it'll fail on 'c' as it returns zero, which = false
echo("Unknown action='$action'"); // took me ages to debug that, resulting in this line of code!!!!
exit; //otherwise not one of ours, quit before SQL stuff starts
}
require "../settings.php"; //lazy place to easily store settings out of reach from the Internet, parent of the web root.
//Be aware I used ".." - if this server.php is not in the webroot then the database.php is not out of reach.
//Note this method is easier than loading an .ini file and parsing it within an array.
if ($db_server == "") { //ASSERT: this should never fire as the require would fail on not find, but can't be too sure
echo "Problem getting database settings.";
exit;
}
$connection = mysql_connect($db_server, $db_username, $db_password); // Establishing Connection with Server
if (!$connection) {
echo "Error connecting to database.";
exit;
}
$db = mysql_select_db($db_database_ip, $connection); // Selecting Database
if (!$db) {
echo "Specific database not found.";
exit;
}
if ($action == 'c') { //note this will fail if there is a blank record against this cell, so check here
$cell = mysql_real_escape_string($_POST['cell']); //extract our parameter
$ip = mysql_real_escape_string($_POST['ip']);
if ($ip == "") {
echo "Cannot add blank IP in cell '$cell'";
} else {
$query = mysql_query("INSERT INTO cell_ip(cell, ip) values ('$cell', '$ip')"); //Create Query
echo $query; //always return the result, even if its unexpected. can hold error messages for debugging
}
}
if ($action == 'r') { //JSON our database back to the client.
//Note I am using the POST protol instead of GET, tidier on this server.php keeping all my server requests in one file
$result = mysql_query("SELECT cell, ip FROM cell_ip"); //Read Query
while ($row = mysql_fetch_row($result)) {
$table_data[] = $row;
}
echo json_encode($table_data); //return the whole dataset
}
if ($action == 'u') { //pinching someone else's cell with our ip, make sure the new ip exists too
$cell = mysql_real_escape_string($_POST['cell']);
$ip = mysql_real_escape_string($_POST['ip']);
if ($ip == "") {
echo "Cannot edit to a blank IP in cell '$cell'";
} else {
$query = mysql_query("UPDATE cell_ip SET ip = '$ip' WHERE cell = '$cell'"); //Update Query
echo $query;
}
}
if ($action == 'd') { //delete this cell
$cell = mysql_real_escape_string($_POST['cell']); //extract our parameter
$query = mysql_query("DELETE FROM cell_ip WHERE cell = '$cell'"); //Delete Query
echo $query;
}
mysql_close($connection); //Note this was never opened if the caller failed the "action" validation, being polite to our sql
?>
settings.php (this goes in root home, change the values in this to suit)
<?php //settings.php
$db_server='localhost';
$db_username='root';
$db_password='root_password';
$db_database_ip='excel_ip';
?>
Things to note: -
If your database relies on the cell number they may change if you edit your Excel and republish the html.
This demo relies on the cell numbers only because it is only a demo - for instance you could put text in the cells and use that to identify your relevant cells.
If you run your server on CloudFlare and change any of your .js or .php they get cached, so you need to purge those files on the CloudFlare (Caching) after you upload them.
SECURITY!!! Your JavaScripts will be available to the end user, they cannot not be, as JS runs on the client - not matter how packaged or encrypted they can be discovered. Do not have passwords or intellectual property in them. This also means your AJAX requests can be launched maliciously, be sure to put extensive handling and filtering in your server-side php's. I would also recommend employing a token + session handler to validate the calling client.
Final note: I wrote this for 2 reasons. First I wanted to read this in 10 years time so I can see how hacky and newby I am now (this is my second day as a web developer), and secondly I do not wish anyone to go through the shameful and humiliating experience which I did when asking for help on this project on StackOverflow (you won't find my question about that though, it got deleted). I hope this post is useful to somebody, I spent a whole day on designing it :)

PHP - Is it possible to grab a dynamically generated value in one file to use in another file in an if statement?

I currently have an inventory page that is populated by a MySQL database. I'm working on a page that can update the stock of an inventory item. I have three php files:
File One: Displays a dropdown of item names, the number in stock of the currently selected item, a dropdown option asking the user if they are adding or removing from the inventory, and a textbox for the change in number in stock. This page is a form.
File Two: Takes the currently selected dropdown item and grabs its number in stock from the database, echos it out to the page, and then takes whatever number is echoed out and prints it out as the displayed number in stock in a div in File One. I'm trying to use that value--the number in stock that is returned on File One--in order to compare it to the amount changed textbox input, so users can't remove more then what is available.
File Three: The form action for File One. This is where I am attempting to code the if statement that compares the two values.
Here is the code for File Two:
$receivedString = null;
if ($_GET["item"] != ""){
$receivedString = $_GET["item"];
}
if($receivedString != null){
//Check connection
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to SOIS MySQL server with error: ' . mysqli_connect_error());
$query = mysqli_query($db, "SELECT numInStock FROM SOISInventoryList WHERE id = $receivedString");
if (!$query){
echo "Could not find query.";
}
while($row = mysqli_fetch_assoc($query)){
echo $row['numInStock'];
}
}
Here is the jQuery function for File Two:
$(document).ready(function(){
$.get( "grab-num-in-stock.php", function( data ) {
$( ".result" ).html( data );
});
});
$(function(){
$('#itemNameDropDown').change(function(){
var SelectedItem = $(this).val();
//Sending the selected item value to the php file as JSON
//Assuming that the php file is setup to consume $_GET variables
$.get('grab-num-in-stock.php', {"item": SelectedItem})
.done(function(returnedData){
//Assuming just a string is returned right now
$('.numInStockCol').text(returnedData);
});
});
});
And here is File Three:
$receivedString = null;
if ($_GET["item"] != ""){
$receivedString = $_GET["item"];
echo "test";
}
else{
echo "test failed";
}
if($receivedString != null){
//Check connection
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to SOIS MySQL server with error: ' . mysqli_connect_error());
$query = mysqli_query($db, "SELECT numInStock FROM SOISInventoryList WHERE id = $receivedString");
if (!$query){
echo "Could not find query.";
}
}
if($_POST['adjustmentDropDown'] == 'remove'){
$currentNumInStock = $row[0];
if( $currentNumInStock >= $_POST['changeAmount']){
echo "test 2";
}
else{
echo "test 2 failed";
}
}
I have attempted to use $item, $receivedString, and $row['numInStock']. I have also attempted to parse each of those from strings into ints using intval, and that did not appear to be the problem either. Any kind of help would be appreciated.
Edit:
I've updated all of the above code to address issues brought up in the comments. My current issue is figuring out why File Three's "if ($_GET["item"] != "")" statement is returning nothing; the code is not echoing "test" as it should be. Any help is appreciated.
Since posting this originally I have also tried using a jQuery function to grab whatever is outputted in File One's number in stock div, but had no success there, either. Again, any kind of help is appreciated.
If a variable is in one file, and just that one file is loaded, then that variable could be considered to be 'scoped' to that file.
In File Three, you're attempted to access a value from File Two - and you're not finding it anywhere. That's because when you hit File Three, the only stuff that gets loaded is the stuff in File Three. Does that make sense? Your variables are scoped to what is actually being loaded - so it would make sense that File Three cannot access variables defined in another php page that has not been loaded.
Your options are to either pass the value along as a parameter or to run the database query again.
Also, obligatory sql injection attack warning.

Categories

Resources