Fetch Only new Entries Database mysql [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
i need some little help .. i wanna fetch only new entry in my database without refresh my page..
ii have an php page which can display all record's of my database .. like someone entered new data in database i want to fetch only single entery .. don't fetch all entries of again .. i also read too many of articles about JSON ajax etc .. but no onehelps me about fetch only single entery . is here any way using xml or something's special to do this .. i don't have any idea how i can do it
thank you

A very general approach would be something like that:
On every page load run a script that checks every a certain time interval the database for new entries:
Javascript:
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'POST',
url: 'ajaxfile.php'
}).success(function(response){
var response = $.parseJSON(response);
var username = response.username; //here we put hypothetical db column "username" in a variable
alert(username); //here we alert the "username" variable in order to verify the script. All other db columns can be called as: response.db_column_name
});
}, 10000); //interval time: 10000 milliseconds (10 seconds)
});
</script>
This script, combined with the following "ajaxfile.php" will display all database columns as: response.db_column
Before I give you my idea about the 'ajaxfile.php', please keep in mind that in order for this approach to work, you need to add an extra column to your db table (for example column: "seen" -that takes values 1 or 0 and having number 1 as default for every new row added). Since you didn't provide enough information, I will here assume that the database table is called "users" and -say- you want to monitor each new user registration in real time (with 10 seconds intervals).
PHP (ajaxfile.php)
<?php
//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}
require("db_connect.php"); //a typical db connection function
$results = array(); //define the results variable
$query = mysql_query("SELECT * FROM users WHERE new_column = '1' ORDER BY id DESC LIMIT 1"); //here we query the db to fetch only the newest record -the one where column "seen" is "1"
while($res = mysql_fetch_assoc($query)){
$current_id = $res["id"];
mysql_query("UPDATE users SET new_column = '0' WHERE id = '$current_id' "); //update the record so it will appear as "seen" and will not be fetched again
$results[] = $res;
}
echo json_encode($results);
?>
In the above file, notice the first two lines which are there to protect the ajax file from direct "browser calls". It is quite a universal solution and can be used in all ajax files.
Finally, here is an example of the db_connect.php file:
<?php
define('DB_HOST', 'localhost'); // the database host
define('DB_PORT', '3306'); // the database port
define('DB_NAME', 'your_db_name'); // the database name
define('DB_USER', 'your_db_user'); // the database user
define('DB_PASSWORD', 'your_db_password'); // the database password
$conn = #mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Could not connect to the Database Server");
mysql_select_db(DB_NAME, $conn) or die("Could not find the Database");
?>
It is a very general approach indeed, but can cover a wide spectrum of applications with small modifications or additions.
I am sorry I could not be more specific -but your question was also a bit too "general"... Hope this helps you and others.

Related

PHP - Reducing an independent record stock value by 1

I'm currently doing a school project and I'm using dreamweaver along with a backend database using phpMyAdmin.
Now, what i need to do is, when I click the button, it will reduce the stock column value in the "products" table by 1.
However there are different products in the table. Shown below:
http://i.stack.imgur.com/vLZXQ.png
So lets say, A user is on the game page for "Destiny" and clicks on the Buy now button, how can i make it reduce the stock level by one, but only for the Destiny record and not for the Fifa 15 column. So Destiny stock becomes 49, but Fifa stays 50. Will i just need to make each button have a different script or?
Currently, I made a button in the page, which links to an action script, but im not sure what sort of code i will be using.
Thank you
xNeyte is giving you some good advice, but it comes across to me that you - Xrin - are completely new to programming database contents with PHP or similar?
So some step by steps:
MYSQL databases should be connected with one of two types of connection - PDO and MySQLi_ . MySQL databases will also always work using the native MySQL but as xNeyte already mentioned - this is deprecated and highly discouraged .
So what you have is you pass your information to the PHP page, so your list of games is on index.php and your working page that will update the number of games ordered would be update.php, in this example.
The Index.php file passes via anchor link and $_GET values (although I highly recommend using a php FORM and $_POST as a better alternative), to the update.php page, which needs to do the following things (in roughly this order) to work:
Update.php
Load a valid database login connection so that the page can communicate with the database
Take the values passed from the original page and check that they are valid.
establish a connection with the database and adjust the values as required.
establish the update above worked and then give the user some feedback
So, step by step we'll go through these parts:
I am going to be a pain and use MySQLi rather than PDO - xNeyte used PDO syntax in his answer to you and that is fully correct and various better than MySQLi, for the sake of clarity and your knowledge of MySQL native, it may be easier to see/understand what's going on with MySQLi.
Part 1:
Connection to the database.
This should be done with Object Orientated - Classes,
class database {
private $dbUser = "";
private $dbPass = ""; //populate these with your values
private $dbName = "";
public $dbLink;
public function __construct() {
$this->dbLink = new mysqli("localhost", $this->dbUser, $this->dbPass, $this->dbName);
}
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
if ( ! $this->dbLink )
{
die("Connection Error (" . mysqli_connect_errno() . ") "
. mysqli_connect_error());
mysqli_close($this->dbLink);
}
else
{
$this->dbLink->set_charset("UTF-8");
}
return true;
} //end __construct
} //end class
The whole of the above code block should be in the database.php referenced by xNeyte - this is the class that you call to interact with the database.
So using the above code in the database.php object, you need to call the database object at the top of your code, and then you need to generate an instance of your class:
include "database.php"; ////include file
$dataBase = new database(); ///create new instance of class.
Now When you write $dataBase->dbLink this is a connection to the database. If you do not know your database connection use the details PHPMyAdmin uses, it carries out its tasks in exactly the same way.
Sooo
Part 2:
That is that your database connection is established - now you need to run the update: First off you need to check that the value given is valid:
if (is_numeric($_GET['id']) && $_GET['id'] >0 ){
$id = (int)$_GET['id'];
}
This is simple code to check the value passed from the link is a integer number. Never trust user input.
It is also a good idea never to directly plug in GET and POST values into your SQL statements. Hence I've copied the value across to $id
Part 3:
$sql = "UPDATE <TABLE> SET STOCK = STOCK-1 WHERE Product_ID = ? LIMIT 1";
The table name is your table name, the LIMIT 1 simply ensures this only works on one row, so it will not effect too many stocked games.
That above is the SQL but how to make that work in PHP:
first off, the statement needs to be prepared, then once prepared, the value(s) are plugged into the ? parts (this is MySQLi syntax, PDO has the more useful :name syntax).
So:
include "database.php"; ////include file
$dataBase = new database(); ///create new instance of class.
if (is_numeric($_GET['id']) && $_GET['id'] >0 ){
$id = (int)$_GET['id'];
$sql = "UPDATE <TABLE> SET STOCK = STOCK-1 WHERE Product_id = ? LIMIT 1";
$update = $dataBase->dbLink->prepare($sql);
$update->bind_param("i",$id);
$update->execute();
$counter = $update->affected_rows;
$update->close();
//////gap for later work, see below:
}
else
{
print "Sorry nothing to update";
}
There's probably quite a lot going on here, first off the bind_param method sets the values to plug into the SQL query, replacing the ? with the value of $id. The i indicates it is meant to be an Integer value. Please see http://php.net/manual/en/mysqli-stmt.bind-param.php
The $counter value simply gets a return of the number of affected rows and then something like this can be inserted:
if ($counter > 0 ){
print "Thank you for your order. Stock has been reduced accordingly.";
}
else {
print "Sorry we could not stock your order.";
}
Part 4
And finally if you wish you can then just output the print messages or I tend to put the messages into a SESSION, and then redirect the PHP page back.
I hope this has helped a bit. I would highly recommend if you're not used to the database interactions in this way then either use PDO or MySQLi but do not combine the two, that will cause all sorts of syntax faults. Using MySQLi means that everything you know MySQL can do, is done better with the addition of the letter "i" in the function call. It is also very good for referencing the PHP.net Manual which has an excellent clear detailed examples of how to use each PHP function.
The best is to set a link on each button with the ID of your game (1 for destiny, 2 for Fifa15).
Then your script which the user will launch by clicking will be :
<?php
include('database.php'); // your database connection
if($_GET['id']) {
$id=$_GET['id'];
} else throw new Exception('Invalid parameter');
$statement = myPDO::getInstance->prepare(<<<SQL
UPDATE TABLE
SET STOCK = STOCK-1
WHERE Product_id = :id
SQL
);
$statement->execute(array(":id" => $id));
This script will do the job

How to update data in an SQL database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have already build a functioning login page which redirects the user the index.php file.
From previous help, I was able to get the wage and display it on the page depending on which user logs in. This is the table users in the database user_registration
user_id username password email wage
1 johnsmith jsmith99 jsmith#gmail.com 100
2 davidscott dscott95 davidscott#gmail.com 90
The part i am stuck on is creating a functioning form that the user can update their wage to the sql database.
Can someone please help me with the php code?
This is the form i already have in place:
<form id="change-wage" action="update.php" method="post">
<input type="text" id="new_wage" name="new_wage">
<input type="button" value="Save">
</form>
EDIT: this is the code, The aim of it is that the user can update the wage value in the table by filling in the textbox and pressing submit. any Ideas how i can acieve this?>
<?php //CHANGING THE WAGE
$username = '$_SESSION['MM_Username'];';
if (isset($_POST['submit'])){
$wage = $_POST['wage-new'];
//connect to server
mysql_connect ("localhost","root","") or die ("Could not connect");
mysql_select_db("user_registration") or die ("Could not connect to the database");
mysql_query ("UPDATE users SET wage='$wage' WHERE username = '$username'") or die ("Could not update");
}
?>
I wont give you the code unless you demonstrate as previous commentator said. However I will give you a an overview so you can work at it your self.
update.php
Check if your is logged in.
if TRUE, continue.
get the new wage from the form
$new_wage = $_POST['new_wage'];
Be sure to validate and clean the $new_wage variable.
Next stage assumes your using PDO
$params = array($new_wage, $logged_in_user_id);
$update = "UPDATE user_registration SET wage=? WHERE user_id=?";
$pdo->prepare($update);
$pdo->execute($params);
First of all if you are using session variables make sure you start the session -session_start();
$username = '$_SESSION['MM_Username'];';
should be
$username = $_SESSION['MM_Username']; (without single quotes)
$wage = $_POST['wage-new'];
should be
$wage = $_POST['new_wage']; as you named it in your html file
you are selecting database user_registation and I assume it should be user_registration
And last, think about switching to PDO or mysqli.

Create website with a page to show online users including username and picture [closed]

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 in the stages of the class diagram, I was creating the class diagram for a website I am planning to create. It was going fine until I reached the stage of wanting to have a web page that displayed the online users e.g. showing their username and profile picture of all online users. I am not sure on how I would do this, the image is of what I have so far. I would appreciate any help or guidance.
Here is my current class diagram http://imgur.com/sgjJwkc
You could also set up a column for user's status (logged in, logged out) and make it toggle between 0 (logged out) and 1 (logged in). You could update this information every 5 seconds (in the background of course) using an AJAX call. Something like this:
//JAVASCRIPT
<script>
$(document).ready(function() {
setInterval(function() {
$.post('Path To PHP File', {x : Pass Variables, y: If You Want}, function(res)
//Do something with the result (res)
);
}, 5000);
});
</script>
//PHP FILE
<?php
//If you passed any variables to the script:
$x = $_POST['x'];
$y = $_POST['y'];
//Connect to your database
$dbConn = "I hope you're using PDO for this.";
//Create your query
$sql = "SELECT * FROM users WHERE status=1";
$res = $dbConn->prepare($sql);
$res->execute();
//Return/echo results
foreach($res as $x) {
echo "<div id='useTheIdToStyleTheResults'>".$x['name']."</div>";
}
?>
res is whatever your php script returns. You can simply run an SQL query on your database in that script to get all users who are logged in and use a foreach() loop to return each item as an html div element. Style those elements to your liking and there you go. If you have questions, just ask!
EDIT:
After reading a little more of your question, SQL JOIN and UNION are a couple of concepts you might want to look into.
http://www.w3schools.com/sql/sql_join.asp
EDIT #2:
//Define Variables
$hostname = '127.0.0.1';
$username = 'userName';
$password = 'passWord';
$dbname = 'database in use';
//Create Connection
try {
$con = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
//echo "Connected to database"; //Uncomment statement to the left to check for connection
} catch (PDOException $e) {
print "Unable to connect: " . $e->getMessage();
mysql_close($con);
die();
}
?>
I would update a timestamp in the user's row every time they load a page and on the load of the online users I would check for timestamps that are fairly recent.
Pseudocode:
SELECT username,avatar FROM users WHERE last_active >= time()-900;

Cannot name a php $_SESSION the id value

I'm trying to make a voting system for a database currently records are rendered in php on screen with images for an up or down vote. When clicked they run the php scripts upvote.php or downvote.php respectively, they pass the id value (integer of the record being manipulated.
Currently it works, the scripts increment and decrement the records votes value as intended. I was, however, trying to stop a user doing this multiple times for one record. I was trying to achieve this by using a session and naming it the value of the id and before altering the votes value checking if the session for that id has been set.
I am going to use my 'upvote.php' as my example:
//Upvote Script
//begin session
session_start();
//database connection credentials import
include("../scripts/connection_variables.php");
//connect to mysql or display error
#mysql_connect("$db_host","$db_username","$db_pass") or die ("Could not connect to the database, please try again shortly. If problem persists please refer to help then contact support.");
//select database or or display error
#mysql_select_db("$db_name") or die ("Could not connect to the database, please try again shortly. If problem persists please refer to help then contact support.");
//collect id
$id = $_GET['id'];
//check if user has already voted for this
if(isset($_SESSION[$id])) {
//session has been set for this id, so don't execute the script
exit();
}else{
//set the session
$_SESSION[$id] = "The punniest thing about puns is that they are really punny.";
//increment the votes value
$query = "UPDATE punniest_database SET votes= 1 + votes WHERE id='$id'";
mysql_query($query);
}
The default serializer used for sessions cannot handle numeric-only keys. It also emits a warning message during shutdown, you should see it in your logs (assuming you have logging enabled, look for Unknown).
Older serialize handlers cannot store numeric index nor string index contains special characters
(quote from link below)
You can test it with the following script, save it somewhere and refresh a few times:
<?php
session_start();
$_SESSION[time()] = true;
var_dump($_SESSION);
The most portable solution is prefixing the keys with a static string. Alternatively you can change the serialize handler used for sessions.

Mysql PHP Arbitrary Increment

I'm trying to increment +1 impression every time an ad is displayed on my site, however the variable increments +2 to +3 arbitrarily. I've removed everything that's working correctly and I made a page with only this code in it:
<?php
require "connect_to_mydb.php";
echo 'Hello***** '.$testVariable=$testVariable+1;
mysql_query("UPDATE `imageAds` SET `test`=`test`+1 WHERE `id`='1'");
?>
Every time the page is refreshed the, test increments arbitrarily either +2 or +3 and my page displays Hello***** 1 (Just to show its not looping). Access is restricted to this page so it's not other users refreshing the page.
Also, id and test are int(11) in the DB.
My DB required connection has nothing in it that would interfere.
Edit
Here is an updated code:
<?php
require "connect_to_mydb.php";
mysql_query("UPDATE `imageAds` SET `test`=`test`+1 WHERE `id`='1'");
$sql = mysql_query("SELECT * FROM imageAds WHERE id='1' LIMIT 1");
$check = mysql_num_rows($sql);
if($check > 0){
$row = mysql_fetch_array($sql);
echo $row['test'];
}
?>
Increments by +2 everytime
Edit
This is whats in connect_to_mydb.php
<?php
$db_host = "*************************";
$db_username = "*********";
$db_pass = "**********";
$db_name = "**************";
mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("$db_name") or die ("no database");
?>
Either there's a bug in MySQL's implementation of UPDATE, or you're doing something wrong in some code you haven't posted.
Hint: It's very unlikely to be a bug in MySQL. Other people would have noticed it.
From what you've shown, it looks like your page is being loaded multiple times.
This attempt to prove that the code is only being called once doesn't prove anything:
echo 'Hello***** '.$testVariable=$testVariable+1;
This will always print the same thing (Hello***** 1) even if you open this page multiple times because the value of $testVariable is not preserved across seperate requests.
This +2/+3 error is occurring only with Chrome and my Mobile Android browser and the code is solid. I looked to see if there is any issue with Chrome sending more than one http request (thx user1058351) and there is which is documented here:
http://code.google.com/p/chromium/issues/detail?id=39402
So since this way was unreliable I just completed a work around that is solid. Instead of including a PHP file that updates the amount of ad impressions on reload, I now have it so when the page loads, an AJAX request is sent to a separate PHP file which updates the ad stats and returns the appropriate data. The key I think is to send it through the JS code so only one http request can be sent to increment the data.
Thank you to all who responded especially user1058351 and Mark Byers (not a bug in MYSQL but possibly appears to be a bug in Chrome).

Categories