Search a database to update the results - php

I am taking a users input and storing it in a database, however I want to be able to update the records if a user adds more information. So I want to search the database find the server with the same name and update the the last downtime and the number of downtimes.
$connect = mysqli_connect("localhost", "Username", "Password","Test_downtime");
if (!$connect)
{
die("Connection failed: " . mysqli_connect_error());
}else
{
echo "Connected successfully\n";
}
$servername = $_GET["server_name"];
$downtime = $_GET["downtime"];
$time_now = time();
$result = mysqli_query($connect, "SELECT COUNT(*) FROM `Test_downtime`.`Downtime` WHERE `Server_Name` = '$servername'");
$row = mysqli_fetch_array($result);
// If no downtime have been reported before
if ($row[0] == 0){
$sql = mysqli_query($connect, "INSERT INTO `Test_downtime`.`Downtime` (ID, Server_name, First_downtime, Last_downtime, Num_of_downtime,Total_downtime) VALUES (NULL, '$servername', '$time_now','$time_now',1,'$downtime'); ");
if ($sql==true) {
echo $servername . " has has its first downtime recorded\n";
}
}
//If users is already in the database
else{
$numdowntime = ($row["Num_of_downtime"] + 1);
$id = ($row["ID"]);
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
if ($sqlupdate == TRUE) {
echo "Oh No! " . $servername . " has had ". $numdowntime ." of downtimes" ;
}
}
?>
The program works fine if the server is not already in the database, the problems arise if the server is already in the database. I get the message saying it has been updated yet nothing happens to the database. How do i make it so it search and updates the records for the searched item.

So nothing append since you do not execute the sql statement ^^
Take a look here :
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
You need to use :
$sql = mysqli_query($connect, $sqlupdate);
Just after it in order to execute it.
Or at least change it to
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
Btw there is other problem but here is the main one [check out the other answer in order to found another one ]

you are fetching the result as indexed array
mysqli_fetch_array($result);
and here you are accessing results as associative array
$numdowntime = ($row["Num_of_downtime"] + 1);
change your query to
mysqli_fetch_assoc($result);
use
mysqli_num_rows($result);
to checking if you have any data
change
if ($row[0] == 0){}
to
if(mysqli_num_rows($result) ==0){}

A good approach for increasing a count in a column is using SQL to increase that.
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = (`Num_of_downtime` + 1), `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
This way you can skip your $numdowntime calculation, and the result is more accurate.
In your current setup, two users may fire the event at the same time, they both retrieve the same number from the database (ie. 9), both increasing it with one (ie. 10), and writing the same number in the database.
Making your count one short of the actual count.
SQL takes care of this for you by locking rows, and you are left with a more accurate result using less logic :)

You miss the mysqli_query() function, which actually queries the database.
$sqlupdate = mysqli_query("
UPDATE `Test_downtime`.`Downtime`
SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now()
WHERE `Server_Name` = '$servername'"
);

Related

Whats wrong in my php mysql counter script code?

I am writing a Php 5 and Mysql 5 page counter script. When a student having id as 'visitorid' visits a page having id 'pageid' (both int(11)) the page counter tries to log the visit in 'visitors' database. But counter is not updating in mysql db, instead the visit_counter int(4) turns to 0.Whats wrong with my code? visitdate is datetime.
<?php
$pageid = 101;
$visitorid = 234;
$sql = "SELECT * FROM visitors
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("Error 1.<br>".mysql_error());
$data = mysql_fetch_array($temp);
// visit_counter is a field in table
if(($data['visit_counter']) != NULL){
echo "Entery exists <br>";
// Tried below version also
$visit = " SET visit_counter = visit_counter+1";
//$visit_counter = $data['visit_counter'];
//$visit = " SET visit_counter = ".$visit_counter++ ;
// Valid SQL
// UPDATE `visitors`
// SET visit_counter = visit_counter+1
// WHERE pageid = 101 and visitorid=234
// This manual sql query updates in phpmyadmin
$sql = "UPDATE visitors ".$visit."
AND visitdate = NOW()
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("ERROR 3.<br>".mysql_error());
//No error is displayed on above query.
} else {
//first entry
$visit_count = "1";
$sql = "INSERT INTO visitors
(`pageid`,`visitorid`, `visitdate`, `visit_counter`)
VALUES ('".$pageid."','".$visitorid."', NOW(), '".$visit_count."')";
$temp = mysql_query($sql);
//first entry is inserted successfully
//and visit_counter shows 1 as entry.
}
?>
Can anyone tell me whats wrong with this code?
Oh! I got answer by myself. Sometimes just little errors make us go crazy..
I made a mistake in udate query.. rather than using and I should have user a comma instead. .. working well now!

Update query in sql commiting wrong value

I trying to implement simple query using php in sql, but the value deducing is twice I don't know why.
What am trying to do is to get the current points of the user and reduce the points that are redeemed by the user and update the points. But what happening is suppose user have 500 points and am sending 100 points to reduce in the following php but the result shows user have 300 points remaining. Why double points are reducing in this table only.
Things i have already checked : -Calling php one time only, Checking the value of points by echo , make a separate table for checking it shows correct points.
Any help would be appreciated
<php
require "conn.php";
$conn = mysqli_connect($server_name, $mysql_username, $mysql_password, $db_name);
$number = mysqli_real_escape_string($conn, $_POST['number']);
$points = mysqli_real_escape_string($conn, $_POST['points']);
//echo $points ;
$sql1 = "UPDATE user_earning SET points = points - '$points' WHERE user_number = '$number'";
$result = $conn->query($sql1);
if ($conn->query($sql1) === TRUE) {echo "Current points Updated";
} else {echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Both $points and $number are coming from android application and am not getting any error. The response i get is current points updates. So php is running fine but the value is not coming correct in mysql
You're running the query twice, once each on these two lines.
$result = $conn->query($sql1);
if ($conn->query($sql1) === TRUE) {echo "Current points Updated";
The second line, maybe, should be
if ($result === TRUE) {echo "Current points Updated";
I think your error is here
$sql1 = "UPDATE user_earning SET points = points - '$points' WHERE user_number = '$number'";
You need the following steps
1. First retrieve the points from your table and store in a variable
$q=mysqli_query($con,"select * from user_earning");
$current_points = 0;
if($q){
while($row = mysqli_fetch_assoc($q))
$current_points = $row['points'];
}
2. Subtract the points as you want`enter code here`
$new_points = $current_points - $points.
3. Then do your update
$sql1 = "UPDATE user_earning SET points = '$new_points' WHERE user_number = '$number'";

MYSQLI row updating by 2 when update by 1 is called

i have a curious problem. When i make an update to a row, the info is updated, but not how i expect it to. i call this code
$count = $v_count+1;
mysqli_query($db_conn, "UPDATE videos SET v_count='$count' WHERE id='$vk'");
I have also tried this code as well...
if(isset($_POST['vk'])){
mysqli_query($db_conn, "UPDATE videos SET v_count='$v_count'+1 WHERE id='$vk'");
}else{
echo mysqli_error($db_conn);exit();
}
It does work, But the number is increased by 2, not the 1 i expected.This line HAS worked in other applications i have used... but now it is behaving oddly. Any help will be appreciated. Here is the full PHP block
$vk = $_GET['vk'];
if($vk != ''){
$sql = "SELECT * FROM videos WHERE id='$vk' LIMIT 1";
$query = mysqli_query($db_conn, $sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$v_count = $row['v_count'];
}
mysqli_query($db_conn, "UPDATE videos SET v_count=v_count+1 WHERE id='$vk'");
mysqli_free_result($query);
}else{
header('location: index.php');
}
You probably have some error in your application logic such that $v_count in your PHP code doesn't equal the v_count field in your MySQL table.
If you use
mysqli_query($db_conn, "UPDATE videos SET v_count=v_count+1 WHERE id='$vk'");
it will always increase by 1 no matter what the value of your $v_count PHP variable.

Database not updating row

Before you assume I didn't establish a database connection, I did. the only portion of the code that does not update is the if empty statements.
All the values can be echoed out correctly, it's just that query doesn't work.
This is in directory config and named stuff.php
$user = $mysqli->real_escape_string($_SESSION['username']);
$user_query = "SELECT * FROM users WHERE username = '$user'";
$result = $mysqli->query($user_query);
$row = $result->fetch_assoc();
$referrer = $row['ref'];
$refearn = $row['refearn'];
verify.php
include('config/stuff.php');
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Get Real IP
$IP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$IP = $_SERVER['REMOTE_ADDR'];
}
if ($IP=="external server ip here") {
if (!empty($referrer)){
$mysqli->query("UPDATE users SET points=points+10, refearn = refearn+10 WHERE username='".$referrer."'") or die(mysqli_error($mysqli));
}
$mysqli->query("UPDATE users SET points=points+".$earnings.", completed = completed+1 WHERE username='".$subid."'") or die(mysqli_error($mysqli));
}
My guess is you could try to retrieve the value of points through a query then add to it so you're just updating to a simple value. However, if mysql_error() is returning an error, it should be easier to figure out.
Example:
$getPoints = mysql_query("SELECT points FROM table WHERE condition");
$points = mysql_result($getPoints, 0, "points");
$update = mysql_query("UPDATE table SET points=" . ($points+10) . " WHERE condition");
Hope that helps. Another consideration, though. Why use an endif structure unless you're breaking PHP tags to display content?
try this:
$mysqli->query("UPDATE `users` SET `points`=`points`+10, `refearn` = `refearn`+10 WHERE `username`='".$referrer."'") or die(mysqli_error($mysqli));
Hope this helps. What I think is, mysql query might be taking those as constant - not as the mysql rows. Try that

Having trouble adding a 24 hour voting system?

There is a script that triggers the code below
I want to disallow executing the script more than once per 24 hours.
I wanted this script to store the last visit time in a table against the user id in a database, then do a time calculation and back them out until the 24 hour expiry time.
Can someone explain how to do this? It would be greatly appreciated if someone could help me with this?
<?php
//Input correct values into this section
$dbhost = '888888';
$dbuser = '888888';
$dbpass = '888888';
$dbname = '888888';
$dbtable = 'redeem';
$dbtable2 = 'playersthatvoted';
//------------------------------------
$input = 'diamond 12';
$player = $_POST['Player'];
$time = time();
if(!isset($_COOKIE['24Hourvote'])){
//---- This is the connection
$conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ('Error: ' . mysql_error());
mysql_select_db($dbname);
$query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";
$query2 = "INSERT INTO `".$dbname."`.`".$dbtable2."` (`player`, `time`) VALUES ('".$player."', '".$time."')";
mysql_query($query1);
mysql_query($query2);
$query= 'SELECT `player` FROM `playersthatvoted` ASC LIMIT 0, 10 ';
$result = mysql_query($query);
mysql_close($conn);
echo 'Done! Type /redeem in-game to get your diamonds.';
$ip=#$REMOTE_ADDR;
setcookie ("24Hourvote",$ip,time()+86400,'/',true,…
} else {
echo 'You have already voted today! Come back later...'; }
?>
EDIT: and could I make it so that it displays the time left until the user can vote again?
To me it looks like you already know what you have to do:
I wanted this script to store the last visit time in a table
against the user id in a database.Then do a time calculation and
back them out until the 24 hour expiry time.
So:
Forget about the cookie. It is stored on client side and can be manipulated.
Before count the vote check the [lastvisit] field of the current user.
If not set count the vote and set the [lastvisit] field in your table to the current date.
If set calculate the time span between now and the last vote. If bigger than 24 hours, count the vote and set the [lastvisit] field in your table to the current date.
Be aware of:
Manipulated parameters: $_POST['Player'];
SQL injections: VALUES ('".$player."', '".$input."')
If you have problems with one of these tasks then ask about the specific problem.
<?php
//Input correct values into this section
$dbhost = '888888';
$dbuser = '888888';
$dbpass = '888888';
$dbname = '888888';
$dbtable = 'redeem';
$dbtable2 = 'playersthatvoted';
//------------------------------------
$input = 'diamond 12';
$time = time();
if(!isset($_COOKIE['24Hourvote'])){
$ip = $_SERVER['REMOTE_ADDR'];
//---- This is the connection
$conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ('Error: ' . mysql_error());
mysql_select_db($dbname);
// Escape all user entered data always
$player = mysql_real_escape_string($_POST['Player']);
// Select time for this player if available
$query = "SELECT time FROM playersthatvoted WHERE player = '$player' ORDER BY time DESC LIMIT 0, 1";
$result = mysql_query($query);
if(mysql_num_rows($result) != 0)
{
$row = mysql_fetch_row($result);
$last_visit = $row[0];
$vote_allowed_time = $last_visit + 86400;
// Allowed to vote
if($time > $vote_allowed_time)
{
// Do whatever else you need to here ...
setcookie ("24Hourvote",$ip,time()+86400,'/');
}
else
{
echo 'This player has already voted today! Come back later...';
}
}
else
{
$query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";
$query2 = "INSERT INTO `".$dbname."`.`".$dbtable2."` (`player`, `time`) VALUES ('".$player."', '".$time."')";
mysql_query($query1);
mysql_query($query2);
$query= 'SELECT `player` FROM `playersthatvoted` ASC LIMIT 0, 10 ';
$result = mysql_query($query);
mysql_close($conn);
echo 'Done! Type /redeem in-game to get your diamonds.';
setcookie ("24Hourvote",$ip,time()+86400,'/');
}
} else {
echo 'You have already voted today! Come back later...'; }
?>
Note: Never trust the user input, always validate and escape the data.
Changed:
$player = $_POST['Player'];
to:
$player = mysql_real_escape_string($_POST['Player']);
Added:
// Select time for this player if available
$query = "SELECT time FROM playersthatvoted WHERE player = '$player' ORDER BY time DESC LIMIT 0, 1";
$result = mysql_query($query);
if($result)
{
$row = mysql_fetch_row($result);
$last_visit = $row[0];
$vote_allowed_time = $last_visit + 86400;
// Allowed to vote
if($time > $vote_allowed_time)
{
// Do whatever else you need to here ...
setcookie ("24Hourvote",$ip,time()+86400,'/');
}
else
{
echo 'This player has already voted today! Come back later...';
}
}
else
{
...
}
UPDATE
I would like to highlight the fact that as it stands anyone can enter the player name and try to vote for it and that does not necessarily mean the same user who clicks the vote button.
Additionally the IP address is not being used for any purposes, it may be an idea to use this for further permission/security checks.

Categories