MYSQLI row updating by 2 when update by 1 is called - php

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.

Related

Search a database to update the results

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'"
);

PHP redirect syntax utilizing results of mysqli query

I have a database table with six records which are urls for six different shiny servers. There is a program that populates, on a real time basis, whether each of the servers are available. I have written a query that returns the url of the first available server. I have tested the script and determined the selection process works. I now want to perform a redirect to the available server using the "header" function and I am having difficulty determining the correct syntax. The URLs are in the format of "muscle.mysite.com:3535nameScan." Here is what I have at present.
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 ";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
//printf ("%s\n", $row["url"]);
$url= printf ("%s\n", $row["url"]);
header ("Location: $url"); //redirect to muscle*
mysqli_close($dbc);
exit(); //before or after mysqli_close? I think after.
When I execute, I see mysite.com/40 in the address bar and I get a 404.
I tried this:
header ("Location: $row"); //redirect to muscle*
When I execute, I get "mysite.com/array in the address bar and I get my 404 page. I have tried many variations and I have thoroughly confused myself.
I hope you can see what I am trying to do. I have backed up to what does work which is
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 ";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
printf ("%s\n", $row["url"]);
mysqli_close($dbc);
I get the first url that is available and I can see the results printed as muscle.mysite.com:3535nameScan. Now, I need to capture the results as a variable I can use in an UPDATE query and the header function. I have been searching for an answer and I have not found one as yet. I thought a different fetch command would be the answer but I could not find one that would apply to what I want to do.
I believe I am heading in the correct direction my using the suggestion to use "sprintf." However, I am still not able to "update" the table. Here is where I am at now.
error_reporting(E_ALL);
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 "; //make query
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
//printf ("%s\n", $row["url"]);
$url= sprintf ("%s\n", $row["url"]); //assign results to a variable?
echo "$url";
$qu = "UPDATE ShinyServers SET Availability = 0 WHERE url = $url LIMIT 1";
$ru = mysqli_query($dbc, $qu);
if (mysqli_affected_rows ($dbc) ==1){
echo '<p> The status has been updated</p>';
}else{
echo '<p class="error"> The status could not be updated</p>';
}
I get the expected results from 'echo "$url";' But I am getting the error message "The status could not be updated." I have been at this for so long I am afraid I am overlooking something. Is there a problem with the code or could there be a problem with the DB table? I looked at the DB table, created by someone else, and I noticed it does not have a unique column.
With prodigitalson and Dan08's help, I have a script that works. It is as follows
error_reporting(E_ALL);
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 "; //make query
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
//printf ("%s\n", $row["url"]);
$url= sprintf ("%s", $row["url"]); //assign results to a variable
//echo "$url";
$qu = "UPDATE ShinyServers SET Availability = 0 WHERE url = '$url' LIMIT 1";
$ru = mysqli_query($dbc, $qu);
if (mysqli_affected_rows ($dbc) ==1){
echo ' The status has been updated';
}else{
echo ' The status could not be updated';
}
mysqli_close($dbc);
header ("Location: http://$url");
exit();
My DB table is updated and I am redirected (I know I do not need the conditional statement). I learned also that the "header" function had to be after mysqli_close. I found that in the php manual. A little more tweaking and then I have the task of marrying this script into a registration script and a login script. Whoppee...thanks again.
This is my final script and it works perfectly
<?php
//selecting available server and update status
include_once '../DB/test1DB.php'; //connect to DB
error_reporting(E_ALL);
$q = "SELECT url FROM ShinyServers WHERE Availability = '0' LIMIT 0, 1 "; //make query
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$url = sprintf("%s", $row["url"]); //assign results to a variable
$qu = "UPDATE ShinyServers SET Availability = 1 WHERE url = '$url' LIMIT 1";
mysqli_close($dbc);
header("Location: http://$url");
exit();

How to run query until one record is found?

This is what i am trying right now but no luck
$bid = $next - 2;//This subtracts 2 from the number, this number is also auto generated
$preid = $bid;
$query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));
while(mysqli_num_rows($sql) !=0) {
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
--$preid;
}
whats suppose to happen is that if a record does not exist it subtracts 1 from preid and runs the query again with the new preid and keeps happening until a record it found but cant figure out how to do it.
I am assuming that you are constantly checking database for new values. However, on a large scale application thi is an highly inefficient way to constantly ping the database.
You have made a variable $preid but you are not using it anywhere.
This is how i would do it if i were to go according to your way
$bid = $next - 2;//This subtracts 2 from the number, this number is also auto generated
$preid = $bid;
$query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));
while(mysqli_num_rows($sql) !=0 || !$preid) { //notice here i added the condition for preid.
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
--$preid;
}
now what happens is that the loop will run as long as either of the two condition stays true ie either a row is returned from the database or it will keep searching until preid is not 0.
If you want to test for an empty set, your while should run while mysqli_num_rows == 0
while(mysqli_num_rows($sql) == 0) {
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
$preid--;
}
As #DarkBee has mentionend in his comment, this code is highly vulnerable for an infinite loop which will take down your script, as soon as there are no entries for anything.

PHP MySQL UPDATE Failure Change INT Value from 0 to 1 with PHP Statement

I am trying to create a small script that will basically replace the value of an already existing mysql table array. The table has the row "claimed" which has a default value of 0, and is an enum of "0", "1" (can switch to a INT or Text if that helps but hasn't helped when I tried).
The idea is that my game server will call to the database and if the value is either a 0 or a 1, a different action is performed. Someone please help!
I cannot get the Claimed Row Value to update from 0 to 1 with my script that my game servers calls to read a single line of text for its value.
Any ideas?
<?php
include 'connect.php';
if(isset($_GET['username'])){
if(!empty($_GET['username'])){
$username = mysql_real_escape_string(strip_tags($_GET['username']));
$sql = mysql_query("SELECT * FROM donations WHERE username='$username' LIMIT 1") or die("MYSQL");
$count = mysql_num_rows($sql);
if($count == 1){
while($row = mysql_fetch_array($sql)){
$claimed = $row["claimed"];
$amount = $row["amount"];
$package = $row["package"];
if($claimed == 0){
$sql = mysql_query("UPDATE claimed SET claimed='1' WHERE username='$username' LIMIT 1");
if($sql){
die($package);
}else{
die("MYSQL");
}
}else{die("CLAIMED");}
}
}else{die("EMPTY");}
}else{die("EMPTY");}
}
?>
To fix:
mysql_query("UPDATE claimed SET claimed='1' WHERE username='$username' LIMIT 1");
Change to
mysql_query("UPDATE donations SET claimed='1' WHERE username='$username' LIMIT 1");
Syntax for update:
UPDATE table_name SET column_name = value where ...
And Stop using mysql_* as it is deprecated use mysqli_ or pdo

Is this coding wrong it's not working properly

The below script inputs data to a database this takes some information from a form then stores them in to the database. And I'm also using uplodify to upload a image file and store the file name in the database but my issue is this data processing script keeps updating the row ID one never jumps to the second line I tried every thing can some one help me with this or show me what I'm doing wrong.
Also this checks the ID and if it's not equal to 1 then does an insertion if it's equal then update it but this not happening.
The ID is auto incrementing.
My script
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM poiinfo ORDER BY ID DESC LIMIT 1");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
//$poiId = $_REQUEST['pID'];
if($row['ID'] != "1"){
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon'";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
I tried u r suggestions but it's still the same now my code for the update is looks like this.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE `ID`='".$row['ID']."'";
But still it keeps up dating the ID 1 not moving on to the next one.
Your update query is missing a WHERE clause. Try this:
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE ID = '".$row['ID']."'";
Also be beware of MySQL Injections: http://en.wikipedia.org/wiki/SQL_injection
To check why your update failed, you should call mysql_error in your last else clause :
} else {
echo mysql_error();
}
As for the first problem : if you never insert a new record (I don't see how that could happen, provided your code), you will never have a record whose ID is 2.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon'";
You need a where clause in this sql to specify a record to update. Currently it is updating all records.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE `ID` = ".$row['id']";";
You will need to set an $id variable for this to work.

Categories