Update Query not updating field in table - php

I am currently struggling with the following :
$res = $db->uniquequery("SELECT distinct won_current,ctt,darkmatter FROM ".USERS." WHERE `id` = '".$USER['id']."'");
$checkwon = $res['won_current'];
$ct=$res['ctt'];
$dm=$res['darkmatter'];
These appear to be working. Now...
$dmgift=0;
while($checkwon>=1000)
{
$ct=$ct+1;
//incrementing $ct doesnt seem to work in the loop but it works fine outside it
$checkwon=$checkwon-1000;
//threshold ranges and setting of dmgift.
switch($ct){
case $ct=1 : $dmgift=25000;break;
case $ct>=5 && $ct<10: $dmgift=50000;break;
case $ct>=10 && $ct<15: $dmgift=75000;break;
case $ct>=15 && $ct<20: $dmgift=100000;break;
case $ct>=20 : $dmgift=150000;break;
}
$dm=$dm+$dmgift;
//$db->query("UPDATE ".USERS." SET won_current=$checkwon,ctt=$checkthreshold,darkmatter=$dm WHERE `id` = ".$USER['id'].";");
$db->query("UPDATE ".USERS." SET won_current=$checkwon WHERE `id` = ".$USER['id'].";");
$db->query("UPDATE ".USERS." SET ctt='$ct' WHERE `id` = ".$USER['id'].";"); // this update query is not passing.db field remains the same
$db->query("UPDATE ".USERS." SET darkmatter=$dm WHERE `id` = ".$USER['id'].";");
}
Kindly advise...the other 2 update queries are passing well...if you notice above the 3 updates I had a full query commented in...split it to see what is not working in update...
I did echo and vardump...outside the loop they gave me the correct values...BUT inside the loop they have me 11111 instead of 5...for example...not sure what I'm doing wrong....I'm very new to php ( 2 days ? ) and would appreciate a solution...

The problem is with the switch.
switch($ct){
case $ct=1 : $dmgift=25000;break;
...
}
The first case changes $ct to 1, so its value is always 1 in the SQL query so it looks like the query doesn't work.
In any case switch doesn't work like that, you need separate if phrases:
if( $ct == 1 ) {
$dmgift=25000
}
else if( $ct>=5 && $ct<10 ) {
$dmgift=50000;
}
else if( $ct>=10 && $ct<15 ) {
$dmgift=75000;
}
else if( $ct>=15 && $ct<20 ) {
$dmgift=100000;
}
else if( $ct>=20 ) {
$dmgift=150000;
}
Also note that you don't have cases for $ct between 2 and 4.

Check for $ct value.
If $checkwon is not greater than or equal to 1000, $ct value will remain the same db value
$db->query("UPDATE ".USERS." SET ctt='" . $ct . "' WHERE `id` = ".$USER['id'].";");

Change your update query
$db->query("UPDATE ".USERS." SET won_current = '".$checkwon."' WHERE `id` = '".$USER['id']."'");
$db->query("UPDATE ".USERS." SET ctt = '".$ct."' WHERE `id` = '".$USER['id']."'");
$db->query("UPDATE ".USERS." SET darkmatter = '".$dm."' WHERE `id` = '".$USER['id']."'");
Remove ";" semicolon from here

use single quotes for values of MySQL
$db->query("UPDATE ".USERS." SET won_current='$checkwon' WHERE id = '".$USER['id']."'");

Related

avoid (shortening) too many else if php

I have this code but in my opinion it's too many lines. I'm new into programming so that's why I have questions.
I think there should be a shorter way to make it work without this if else loop, switch or is it ok like it's now?
if $total==21 then mysql_query("UPDATE user SET left = '20', $total==20 then left=19 and so on until the $total=1 and left=0.
if ($total==21 )
{
mysql_query("UPDATE `user` SET `left` = '20' WHERE `user` = 'user1' ") or die(mysql_error() );
}
else if ($total==20)
{
mysql_query("UPDATE `user` SET `left` = '19' WHERE `user` = 'user1' ") or die(mysql_error() );
}
....
else if ($total==1)
{
mysql_query("UPDATE `user` SET `left` = '0' WHERE `user` = 'user1' ") or die(mysql_error() );
}
else {
echo nl2br("0 left");
}
Merry Christmas !
First, look at How can I prevent SQL injection in PHP?, and then something like:
if($total > 0 && $total < 22) {
$left = $total - 1;
// prepare("UPDATE `user` SET `left` = ? WHERE `user` = 'user1'")
// bind_param('i', $left)
// execute()
}
You should be using PDO or Mysqli instead of the deprecated old mysql driver. This should solve your issue for now:
$total = (int) $total;
if ($total <= 0) {
echo '0 left';
} else {
$total--;
mysql_query("UPDATE `user` SET `left` = '$total' WHERE `user` = 'user1' ") or die(mysql_error() );
}
Notice how I am hardcoding the variable to be an integer, this way it wouldn't be venerable to injections (in the event it comes from the client side).

Feedback for php code

hello guys I am subtracting one unit from a variable called Eppl which resides in a Database and this is working perfectly. However I have added a condition which is that the value of the variable Eppl must be greater than 0 before the subtraction takes place. My code is as follows:
$id = $_GET["id"];
$result = $mysqli->query("SELECT `CreatedBy` AND `Eppl` FROM `events` WHERE `Eid` = '$id'");
$row = $result->fetch_assoc();
$sessionid = $row['CreatedBy'];
$notlesszero = $row['Eppl'];
$zero = 0;
//echo $result;
session_start();
if ((!($_SESSION['login_user'] == $sessionid)) && ($notlesszero>0)){
$mysqli->query("UPDATE `events` SET `Eppl` = `Eppl` - 1 WHERE `Eid` = '$id'");
$mysqli->query("INSERT INTO `eventusers` (EventID, UserID) VALUES ('{$id}', '{$_SESSION['login_user']}')");
header("location:view.php");
//}
}
The if branch works without the second condition $notlesszero>0...
What is the problem here?
Thanks for your help
Instead of querying the database to get the value of the field and then checking it, why not just add a condition on the UPDATE?
$mysqli->query("UPDATE `events` SET `Eppl` = `Eppl` - 1 WHERE `Eid` = '$id'");
to
$mysqli->query("UPDATE `events` SET `Eppl` = `Eppl` - 1 WHERE `Eid` = '$id' AND `Eppl` > 0");
The first query is wrong after you added Eppl to it. Fields to select should not be separated by AND. So
SELECT `CreatedBy` AND `Eppl` FROM
should be
SELECT `CreatedBy`, `Eppl` FROM
This is something you could have caught by inspecting the error information after executing the query, or at least by inspecting $row after changing the query. :-p

Update a SQL table field when a variable is empty using PHP

I have a table, with columns _photo(string) and f1(int)(this is users sex).
If _photo is empty I want to populate it with a string based on what column f1 contains.
I have this working fine for when a new user joins up, by doing this -
$sex = mysql_result(mysql_query("SELECT `f1` FROM `{$dbtable_prefix}user_profiles` WHERE `fk_user_id`='".$_SESSION[_LICENSE_KEY_]['user']['reg_id']."' "),0);
And then
if ($sex =='1') {
$no_photo = "no_photo_male.png";
}
if ($sex =='2') {
$no_photo = "no_photo_female.png";
}
if ($sex =='3') {
$no_photo = "no_photo_couple_ff.png";
}
if ($sex =='4') {
$no_photo = "no_photo_couple_mm.png";
}
if ($sex =='5') {
$no_photo = "no_photo_couple_mf.png";
}
$insertphoto= "UPDATE dsb_user_profiles SET _photo = '$no_photo' Where `fk_user_id` = '".$_SESSION[_LICENSE_KEY_]['user']['reg_id']. "' "; // note the use of reg_id and not user_id
if (!($res=#mysql_query($insertphoto))) {trigger_error(mysql_error(),E_USER_ERROR);}
I am trying to make a script that I can run on the database to update all the records to assign the correct string to all the records where _photo is empty.
I am new to mysql and php and can't work out how to cycle through each record and check f1, run the code to set the no_photo variable than insert it into the _photo column.
Any help is greatly appreciated!
Thanks.
You could loop trough records like this:
$userResult = mysql_query("SELECT `f1` FROM `{$dbtable_prefix}user_profiles` WHERE");
while($user = mysql_fetch_array($userResult)) {
if($user['f1'] == '1'){
$no_photo = "no_photo_male.png";
}
else if($user['f1'] == '2'){
//more else ifs
}
//your update query
}
Please try below update query:-
UPDATE Table_Name
SET _photo =
CASE
WHEN f1 = '1'
THEN "no_photo_male.png"
WHEN f1 = '2'
THEN "no_photo_female.png"
WHEN f1 = '3'
THEN "no_photo_couple_ff.png"
WHEN f1 = '4'
THEN "no_photo_couple_mm.png"
WHEN f1 = '5'
THEN "no_photo_couple_mf.png"
ELSE NULL
END
WHERE _photo = ''
You can update the database directly w/o PHP using nested MySQL IF() statements:
UPDATE user_profiles
SET _photo = IF(sex = 1, 'photo_1', IF(sex = 2, 'photo_2', IF(sex = 3, 'photo_3', IF(sex = 4, 'photo_4', NULL ) ) ) )
WHERE photo IS NULL;

PHP MYSQL Update multiple fields including DATETIME field

I can update the field 'delivered' from 0 to 1 no problem but when I try to update 'delivered_time' nothing happens in the database. This may be to do with the way I am writing the code but If anybody could help I would really appreciate it, thanks!
if (isset($_POST['delivered']) === false) {
mysql_query("UPDATE `listings` SET `delivered_time` = '{$date->format('Y-m-d H:i:s')}' AND `delivered` = 1 WHERE `order_id` = $order_id");
}
I have also tried this but this did not work either
if (isset($_POST['delivered']) === false) {
mysql_query("UPDATE `listings` SET `delivered_time` = NOW() AND `delivered` = 1 WHERE `order_id` = $order_id");
}
My MYSQL database is set to have 'delivered' defined to 0 and is stored as an INT value. The 'delivered_time' field is stored as a DATETIME value in the database.
, not AND as the field separator; AND is used in WHERE clauses
UPDATE `listings`
SET `delivered_time` = '{$date->format('Y-m-d H:i:s')}',
`delivered` = 1
WHERE `order_id` = $order_id
Try this code
<?php
if (isset($_POST['delivered']) === false) {
mysql_query("UPDATE `listings` SET `delivered_time` = NOW(),`delivered` = 1 WHERE `order_id` = ".$order_id);
}
?>

Why the script saves all the time the same data?

I have a problem with my php Script that the system runs every minute.
My php-script is this:
<?php
$y = date("Y", time());
$m = date("m", time());
$d = date("d", time());
$h = date("H", time());
mysql_connect("localhost", "root", "");
mysql_select_db("dashboard");
$check_date = mysql_query("SELECT year,month,day FROM serverstats WHERE year='".$y."' && month='".$m."' && day='".$d."'");
if(mysql_num_rows($check_date)==0) {
mysql_query("INSERT INTO serverstats (year,month,day,h01,h02,h03,h04,h05,h06,h07,h08,h09,h10,h11,h12,h13,h14,h15,h16,h17,h18,h19,h20,h21,h22,h23,h24)
VALUES (
'".$y."', '".$m."', '".$d."', NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL
);
") or die(mysql_error());
} else {
$load = file_get_contents("/proc/loadavg");
$load = explode( ' ', $load );
$total_load = $load[0] + $load[1] + $load[2];
$last_load = mysql_query("SELECT h".$h." FROM serverstats");
$daten = mysql_fetch_array($last_load);
$total = $daten["h".$h.""]+$total_load;
mysql_query("UPDATE serverstats SET h".$h."='".$total."'");
mysql_query("UPDATE serverstats SET ts ='".time()."'");
}
?>
And the database looks like this:
The Timestamp(ts) and the other values are the same, what did I make wrong?
You are missing where condition in update
UPDATE serverstats SET ts ='".time()."'"
While updating the database it should have where clause .. your sql should be something like\
UPDATE serverstats SET ts ='".time()."' Where = 'your condition'"
If you miss where in update clause .. then all records will get updated ..
NOTE please switch to mysqli_* or PDO . mysql_* are no longer officially maintained.
I assume, the ts is not an "on update CURRENT_TIMESTAMP" field. Having this would make it easier, leaving the ts stuff to the DB.
BUT:
these two statements
mysql_query("UPDATE serverstats SET h".$h."='".$total."'");
mysql_query("UPDATE serverstats SET ts ='".time()."'");
Will always update all records in the table - missing where clause.
Try this:
mysql_query("UPDATE serverstats SET h".$h."='".$total."', ts ='".time()."' ".
" WHERE year='".$y."' && month='".$m."'` && day='".$d."'");
and obviously
$last_load = mysql_query("SELECT h".$h." FROM serverstats " .
" WHERE year='".$y."' && month='".$m."'` && day='".$d."'");
since otherwise this is reading the entire table and your taking just an arbitrary first row.
It seems I don't have enough rep to leave comments but as an aside, you're using:
$h = date("H", time());
Which is in the form of 00 to 23 but the table columns are 01 - 24.
This may become an issue for example at 00:
$last_load = mysql_query("SELECT h".$h." FROM serverstats");
...

Categories