avoid (shortening) too many else if php - 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).

Related

PHP / MySQL - Write and check UPPERCASE in database

I have the following code to write the name and score of a player into a highscore table. How can I write the 'name' in uppercase into the database?
if(isset($_GET['name']) && isset($_GET['score'])) {
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['score']));
$checkExist = mysql_query("SELECT `name`, `score` FROM `$tbl_name` WHERE `name` = '$name'");
$row = mysql_fetch_assoc($checkExist);
if (mysql_num_rows($checkExist) > 0){
if ($score > $row['score']){
$sql = mysql_query("UPDATE `$tbl_name` SET `score` = '$score' WHERE `name` = '$name'");
} else {
// ERROR MSG: Your new score is lower.(not updating the database)
}
} else {
$sql = mysql_query("INSERT INTO `$tbl_name` (`id`,`name`,`score`) VALUES ('','$name','$score');");
}
$name = strtoupper(strip_tags(mysql_real_escape_string($_GET['name'])));
http://php.net/manual/en/function.strtoupper.php
Either use strtoupper() in PHP, or UPPER() in MySQL: both do exactly the same, it's up to you.

Update Query not updating field in table

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

Mysql Multiple PHP Queries, Skipped

If i'm doing multiple mysql queries on the same table, occasionally some get skipped.
Why is that?
For example:
<?php
mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'");
mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'");
mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'");
?>
Sometimes one of the queries will not be executed?
Why is that?
-Or is it something wrong with my server not general mysql?
(Obviously I know now to update the same table in the same query, but before that I was very confused as to why it happens, can anyone please explain?)
Thanks!
You do not need to make 3 queries, if you are updating the same rows:
$q = "
UPDATE table
SET field = '',
field2 = '',
field3 = 0
WHERE Id = :id
";
$statement = $pdo->prepare( $q );
$statement->bindParam(':id', $something, PDO::PARAM_INT);
$statement->execute();
Also, you should stop using the ancient mysql_* functions. They are not maintained anymore and process for deprecation has already begun.
Maybe you should avoid the 10+ year old API and learn something for this decade: PDO Tutorial for MySQL Developers.
debug your code to see if a query fails:
$result = mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Use the following to debug the code:
mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'") or die(mysql_error());
mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'") or die(mysql_error());
mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'") or die(mysql_error());
UPDATE
Make sure you are escaping $something using:
$something = mysql_real_escape_string($something);

Counter does not increment in PHP/MySQL

I need to create a counter for member section (count the number of times a user logged).
I have the following script (counter.php):
<?php
$conn = mysql_connect("localhost", "myuser", "mypass");
mysql_select_db("test");
$sql = "SELECT views FROM members WHERE mid = " . $_GET['mid'];
$result = mysql_query($sql);
if (!$result)
{
mail(ADMIN, 'Cannot Get: ' . mysql_error(), mysql_error());
}
while ($row = mysql_fetch_assoc($result))
{
$count = $row['views']++;
}
$query = "UPDATE members SET views = '$count' WHERE mid = " . $_GET['mid'];
mysql_query($query);
mysql_close($conn);
// show the logo using header() and readfile(); // that part work
?>
DB:
CREATE TABLE `members` (
`mid` int(11) NOT NULL AUTO_INCREMENT,
`views` int(11) DEFAULT '0',
/* etc...*/
PRIMARY KEY (`mid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Now, what I do in my .htaccess file is:
RewriteEngine On
RewriteRule ^img/logo([0-9]+).jpg$ /counter.php?mid=$1 [L]
but for some reason my counter does not count correctly. What am I missing?
You could probably just simplify it and do the following:
$query = "UPDATE members SET views = views + 1 WHERE mid = " . $_GET['mid'];
mysql_query($query);
if (mysql_affected_rows() == 0) {
mail(ADMIN, 'Cannot Get: ' . mysql_error(), mysql_error());
}
mysql_close($conn);
No need to do initial check.
use this
$count = $row['views'] + 1;
or
$count = ++$row['views'];
or
$query = "UPDATE members SET views = views + 1 WHERE mid = " . $_GET['mid'];
syntax:
$x = 1;
$count = $x++;
// $count = 1
$x = 1;
$count = ++$x;
// $count = 2
The problem is in the line
$count = $row['views']++;
This actually says:
- Assign the value of view to $count
- Increment views.
But you want:
$count = ++$row['views'];
Which says:
- Increment views.
- Assign the (incremented) value of view to $count
A subtle difference. :~)

MySQL get all affected rows for multiple statements in one query

MySQL/PHP:
For a query with multiple statements, which deletes rows in four different tables, I want to know the combined number of affected rows. The PHP manual says I'll only get the result from the last 'operation', which suggests it will only tell me how many rows were affected by the last of the DELETE statements.
How to get around this?
$deleteContactSQL = "DELETE FROM `persons` WHERE `persons`.`id` = '$person' AND `owner = '$user' AND `userOrContact` = 'contact';
DELETE FROM `tabs` WHERE `person` = '$person' AND `ownerIdentity` = '$user' AND `selfOrOther` = 'other';
DELETE FROM `tabAccess` WHERE `person`= '$person' AND `givenToIdentity` = '$user';
DELETE FROM `personAccess` WHERE `viewedPerson` = '$person' AND `viewerIdentity` = '$user';
;";
include $_SERVER['DOCUMENT_ROOT'].'/goalview/includes/db.inc.php';
$deleteContacts = mysqli_query($link, $deleteContactSQL);
$success = mysqli_affected_rows($link);
Something like this maybe?
include $_SERVER['DOCUMENT_ROOT'] . '/goalview/includes/db.inc.php';
$sql = array();
$sql[] = "DELETE FROM `persons` WHERE `persons`.`id` = '$person' AND `owner = '$user' AND `userOrContact` = 'contact';"
$sql[] = "DELETE FROM `tabs` WHERE `person` = '$person' AND `ownerIdentity` = '$user' AND `selfOrOther` = 'other';"
$sql[] = "DELETE FROM `tabAccess` WHERE `person`= '$person' AND `givenToIdentity` = '$user';"
$sql[] = "DELETE FROM `personAccess` WHERE `viewedPerson` = '$person' AND `viewerIdentity` = '$user';"
$aff_rows = 0;
foreach($sql as $current_sql)
{
$deleteContacts = mysqli_query($link, $current_sql);
$aff_rows = $aff_rows + mysqli_affected_rows($link);
}
Here is a compact, procedural-style mysqli_multi_query() solution for counting combined affected rows:
$deleteContactSQL="DELETE FROM `persons` WHERE `id`='$person' AND `owner='$user' AND `userOrContact`='contact';
DELETE FROM `tabs` WHERE `person`='$person' AND `ownerIdentity`='$user' AND `selfOrOther`='other';
DELETE FROM `tabAccess` WHERE `person`='$person' AND `givenToIdentity`='$user';
DELETE FROM `personAccess` WHERE `viewedPerson`='$person' AND `viewerIdentity`='$user';";
include $_SERVER['DOCUMENT_ROOT'].'/goalview/includes/db.inc.php';
if(mysqli_multi_query($link,$deleteContactSQL)){
do{
$success+=mysqli_affected_rows($link);
}while(mysqli_more_results($link) && mysqli_next_result($link));
}
Alternatively, this group of queries may be a good candidate for some TRIGGERs in the persons table.
I'd be doing it like this, but, I do like to keep things simple which not everyone can appreciate ;)
$deleteContactSQL = sprintf("call cascade_delete_persons(%d,%d)", $person, $user);
$deleteContacts = mysqli_query($link, $deleteContactSQL);
drop procedure if exists cascade_delete_persons;
delimiter #
create procedure cascade_delete_persons
(
in p_pid int unsigned,
in p_oid int unsigned
)
begin
declare v_persons_count int unsigned default 0;
declare v_tabs_count int unsigned default 0;
delete from persons where id = p_pid and owner = p_oid and userOrContact = 'contact';
set v_persons_count = row_count();
delete from tabs where person = p_pid and ownerIdentity = p_oid and selfOrOther = 'other';
set v_tabs_count = row_count();
-- etc...
select v_persons_count as person_count, v_tabs_count as tabs_count;
end #
delimiter ;
You can use this method too if you must : http://php.net/manual/en/mysqli.multi-query.php

Categories