Updating mySQL INT with new INT - php

Okay so for a basic outline I'm trying to update a column in my mySQL database dependent on the outcome of my code.
Basically it's rolling dice, if you beat the house it increases your INT by 5 if you loose to the house, it decreases by 5. This is for my own educational purposes and will not be used publicly.
The part that isn't working is the mysq_query("UPDATE") with both win and lose.
if (isset($_POST['roll'])) {
$rand = rand(1, 6);
$rand1 = rand(1, 6);
$rand2 = rand(1, 6);
$rand3 = rand(1, 6);
$score = $rand + $rand1;
$score1 = $rand2 + $rand3;
echo 'You rolled a '.$rand.' and a '.$rand1.' Totalling '.$score;?><br><?
echo 'Your opponent rolled a '.$rand2.' and a '.$rand3.' Totalling '.$score1;?><br><br><?
if ($score > $score1){
echo 'Win';
$coins = $user_data['coins'] + 5;
mysql_query("UPDATE `users` SET `coins` = '$coins' WHERE `user_id` = $user_id");
} else {
echo 'Loose';
$coins1 = $user_data['coins'] - 5;
mysql_query("UPDATE `users` SET `coins` = '$coins1' WHERE `user_id` = $user_id");
}
}
?>
<form action="playdice.php" method="POST">
<input type="submit" name="roll" value="Roll Dice.">
</form>

You dont need the ' around $coins. Those specify that the input is a CHAR, so MySQL is probably trying to insert a CHAR and refusing as it's an INT column.
You also don't appear to have defined a connection to query on.
$mysqli = new mysqli("localhost", "user", "password", "database");
...
if ($score > $score1){
echo "Win";
$coins = $user_data['coins'] + 5;
$mysqli->query("UPDATE `users` SET `coins` = $coins WHERE `user_id` = $user_id");
} else {
echo "Lose";
$coins = $user_data['coins'] - 5;
$mysqli->query("UPDATE `users` SET `coins` = $coins WHERE `user_id` = $user_id");
}
This should work. (Sorry for switching you from the deprecated mysql syntax but I honestly don't remember it, if you're learning you're better off using mysqli anyway).

Put a ' around the $user_id, it's probably a string. removing the quote tells MySQL that it is an integer.

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).

Loop through database and update a field with a foreach loop

I am trying to round a decimal from a table and update another field in the same table with the new rounded value, but I just cant seem to hack it.
The rounding script works perfectly, but I am stuck trying to run the rounding script and update the database accordingly.
The table consist of over 10,000 entries, thus I request only data of a specific given date, which narrows down to about 1,200 entries at a time...
Here is my foreach loop (which works well on its own), but this is not working:
<?php
include("XXXX");
$cxn = mysqli_connect($host,$user,$password,$dbname)
or die ("Couldn't connect to server.");
$query = "SELECT `sub_hrs`, `id` FROM `attend` WHERE `date` = '$date'";
$result = mysqli_query($cxn,$query)
or die ("Couldn't execute query.");
while($row = mysqli_fetch_assoc($result))
{
extract($row);
$n = array($sub_hrs);
foreach($n as $i) {
$new[] = (fmod($i, 1) > 0.5
? sprintf("%2.f", (float) (int) $i + 0.5)
: sprintf("%2.f", (float) (int) $i)) . PHP_EOL;
$mysql_query("UPDATE `attend` SET `total_hrs` = $new WHERE `id` = $id");
}
}
You are assigning an array $new[] in below line.
$new[] = (fmod($i, 1) > 0.5
? sprintf("%2.f", (float) (int) $i + 0.5)
: sprintf("%2.f", (float) (int) $i)) . PHP_EOL;
But in query you are passing only $new variable which will not work as you will not get any value in $new variable.
$mysql_query("UPDATE `attend` SET `total_hrs` = $new WHERE `id` = $id");
Thanx for all the help guys, but I figured out that a simple query does the trick...
UPDATE `attend`
SET `total_hrs` = if((`sub_hrs` - truncate(`sub_hrs`,0)) < 0.5, truncate(`sub_hrs`,0), ((truncate(`sub_hrs`,0)) + 0.5))
WHERE `date` = '$date'

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.

for loop, $i equals two different values in the same loop

I have a small form that is generated from a mysqli->query and I've set each inputs name to be an array, such as name="Shift_ID[]". Then I have a for loop that is meant to UPDATE the records one at a time as it loops through. The problem I have is that the $i variable is a different value within the same loop and I don't understand why. This is my code:
if(isset($_POST['update_submit']))
{
$id = $_POST['Shift_ID'];
$name = $_POST['Shift_Name'];
$short_name = $_POST['Shift_Short_Name'];
$color = $_POST['Shift_Color'];
$shift_total_records = "5";
for($i = 0; $i <= $shift_total_records; $i++)
{
$sql = ("UPDATE shift SET Shift_ID = '$id[$i]', Shift_Name = '$name[$i]', Shift_Short_Name = '$short_name[$i]', Shift_Color = '$color[$i]' WHERE Shift_ID = '$i'");
echo "SQL: " . $sql . "<br>";
if(!$result_shift_update = $mysqli->query($sql))
{
die ('There was an error updating the shift table [' . $mysqli->error . ']');
}
}
}
The echo returns this:
SQL: UPDATE shift SET Shift_ID = '1', Shift_Name = 'Morning', Shift_Short_Name = 'AM', Shift_Color = '#FF0000' WHERE Shift_ID = '0'
I was expecting Shift_ID = '1' and WHERE Shift_ID = '1'. Can someone explain why this is happening? Also, before someone says it, I do know this is open to injection attacks and I need to use prepared statements.
*EDIT: * The reason I had it Shift_ID = '$id[$i]' and WHERE Shift_ID = '$i' was because I wanted to user to be able to change the Shift_ID field if they wanted to. The point would be to have the option to rearrange the order. The Shift_ID is the PRIMARY KEY, so they would get an error if they tried to use the same number twice, but is there a way to make this do what I want?
The first '1' is $id[$i] not $i - there is no problem evident here.
for($i = 0; $i <= $shift_total_records; $i++)
sets $i to 0, when you echo $id[$i] you will get the content in $id[0], the first id, but when you only echo $i you print 0 because you made $id = 0.
You've used a different variable in each location. Do you mean this:
$sql = ("UPDATE shift SET Shift_ID = '$id[$i]', Shift_Name = '$name[$i]', Shift_Short_Name = '$short_name[$i]', Shift_Color = '$color[$i]' WHERE Shift_ID = '$id[$i]'");
The first time you use $i you use it as follows $id[$i] the second time you just use $i....

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. :~)

Categories