Hello I am trying to implement after they pay it checks how much they paid and inputs different variables in sql database with if methods.
The problem:
The problem is all the if methods return to this first option(inserts paid=1, and 30days) not sure what the problem is, is my if method broken?what's wrong please explain! thanks!
if(number_format($amount, 2) == 8.00)
{
$mysqli = new mysqli(******);
$stmt = $mysqli->prepare("UPDATE `as_users` SET paid='1', reg_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
} elseif (number_format($amount, 2) == 10.00)
{
$mysqli = new mysqli(******);
$stmt = $mysqli->prepare("UPDATE `as_users` SET paid='2', reg_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
} elseif (number_format($amount, 2) == 100.00)
{
$mysqli = new mysqli(******);
$stmt = $mysqli->prepare("UPDATE `as_users` SET paid='2', reg_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 365 DAY) WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
}
Edit: I tried with $amount and also tried using the names of the array from dropdown menu I have
array("Basic Package-Monthly", "8.00", "Month", "1", "0", "0"),
array("Premium Package-Monthly", "10.00", "Month", "1", "0", "0"),
array("Premium Package-Annually", "100.00", "Year", "1", "0", "0"),
Why worry about the conditional statement, let the switch handle it. Leverage your prepared statement fully.
$mysqli = new mysqli('******');
$paid = false;
$recurring = false;
switch(number_format($amount, 2)):
case '8.00':
$paid = 1;
$recurring = 30;
break;
case '10.00':
$paid = 2;
$recurring = 30;
break;
case '100.00':
$paid = 2;
$recurring = 365;
break;
endswitch;
$stmt = $mysqli->prepare("UPDATE `as_users` SET paid=?, reg_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL ? DAY) WHERE username = ?");
$stmt->bind_param('dis', $paid, $recurring, $username);
$stmt->execute();
try to use
number_format($amount, 2, '.', '') instead of number_format($amount, 2) for returning english notation without thousands separator.
i.e
english notation without thousands separator
$number = 1234.56;
$english_format_number = number_format($number, 2, '.', '');
1234.56
and to compare two float values use BC math function
$b = 10.00;
$a = number_format($amount, 2, '.', '');
bccomp($a, $b)==0 // returns true if both values are 10.00
Related
in my current project I want to split 10 users from a queue into 2 teams with 5 users each.
When 10 users are in the queue the function create_new_lobby() is executed. In this function the match is created and all users should be assigned to the teams in an intermediate table. With a for loop all users should be assigned to the match. Currently the for loop only takes every second user (0, 2, 4, 6, 8). The values 1, 3, 5, 7 & 9 are apparently skipped by the for loop.
Where is the error here?
<?php
function create_new_lobby() {
global $connection;
$timestamp = date("Y-m-d H:i:s", strtotime(date('h:i:sa')));
$stmt = $connection->prepare("INSERT INTO competition_game (create_time) VALUES (?)");
$stmt->bind_param("s", $timestamp);
$stmt->execute();
$stmt->close();
$stmt = $connection->prepare("SELECT competition_match_id FROM competition_game ORDER BY competition_match_id DESC LIMIT 0, 1");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$competition_match_id = $row['competition_match_id'];
$stmt->close();
for($player = 0; $player <= 9; $player++) {
$status_queue = 1;
$stmt = $connection->prepare("SELECT * FROM competition_queue WHERE competition_queue_status = ? AND DATE_ADD(competition_queue_activity ,INTERVAL 20 MINUTE) >= NOW() ORDER BY competition_queue_id ASC LIMIT ?, 1");
$stmt->bind_param("ss", $status_queue, $player);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$user_id = $row['user_id'];
$stmt1 = $connection->prepare("INSERT INTO competition_game_player (competition_match_id, user_id) VALUES (?, ?)");
$stmt1->bind_param("ss", $competition_match_id, $user_id);
$stmt1->execute();
$stmt1->close();
}
$stmt->close();
$status_leave = 2;
$stmt = $connection->prepare("UPDATE competition_queue SET competition_queue_status = ? WHERE user_id = ? AND competition_queue_status = ?");
$stmt->bind_param("sss", $status_leave, $user_id, $status_queue);
$stmt->execute();
$stmt->close();
}
}
?>
Current result:
Expected result:
The for loop works as it should and you can check that by placing an var_dump($payer) inside the for loop;
The increment in the for loop is given by the third statement, the $player++, which means $player = $player + 1;
If you would want to have a different looping step, you can add a different expression for the third statement in the for loop.
e.g.
for($player = 0; $player <= 9; $player++) {
var_dump($player);
}
exit;
The code snippet will output 0 1 2 3 4 5 6 7 8 9
for($player = 0; $player <= 9; $player += 2) {
var_dump($player);
}
exit;
The code snippet will output 0 2 4 6 8
I hope this helped you better understand the for loop.
The actual problem you are facing is created by the logic that you have made with SQL and not by the for loop
Hello i have a table in sql called premium now when "user" with premium (in the table that there is 1 number is premium and 0 is not) then in the code before you i have an avant that every hour when clicked need to get something in return in this case this is a table called userMana Now i want premium name Will receive more (that is paid money) then is this way correct?
The first part I tried and after that I used the bottom part
if (isset($_GET['daily'])) {
if ($user->checkHours($user->hourEvent)) {
$time = date("Y-m-d H:i:s", time());
$mysqli->prepare("UPDATE `users` SET `hourEvent` = ?, `userMana` = `userMana` + 10, `userCitizens` = `userCitizens` + 1 WHERE userId = ?")->execute([$time, $user->userId]);
header("Location: /אזור-משחק/בסיס");
} else if ($user->premium > 0) {
if ($user->checkHours($user->hourEvent)) {
$time = date("Y-m-d H:i:s", time());
$mysqli->prepare("UPDATE `users` SET `hourEvent` = ?, `userMana` = `userMana` + 101, `userCitizens` = `userCitizens` + 1 WHERE userId = ?")->execute([$time, $user->userId]);
header("Location: /אזור-משחק/בסיס");
}
}
}
################################ Separator ###########################
if (isset($_GET['daily'])) {
if ($user->checkHours($user->hourEvent)) {
$time = date("Y-m-d H:i:s", time());
$mysqli->prepare("UPDATE `users` SET `hourEvent` = ?, `userMana` = `userMana` + 10, `userCitizens` = `userCitizens` + 1 WHERE userId = ?")->execute([$time, $user->userId]);
header("Location: /אזור-משחק/בסיס");
}
if ($user->premium > 0 && $user->checkHours($user->hourEvent)) {
$time = date("Y-m-d H:i:s", time());
$mysqli->prepare("UPDATE `users` SET `hourEvent` = ?, `userMana` = `userMana` + 11, `userCitizens` = `userCitizens` + 1 WHERE userId = ?")->execute([$time, $user->userId]);
header("Location: /אזור-משחק/בסיס");
}
}
The first one will not work properly.
The else if condition will only be tested when $user->checkHours($user->hourEvent) returns false. But the nested if block is only executed when this same expression returns true. Unless the result of this changes between these two tests, the second one can never succeed. So premium users will never get a bonus.
The second version will give two bonuses to premium users. They'll first get the same bonus of 10 that everyone gets, then they'll get an additional 11 bonus because they're premium users. I think it would be clearer to write it like this:
$normal_bonus = 10;
$premium_bonus = 21;
if (isset($_GET['daily']) && $user->checkHours($user->hourEvent)) {
$bonus = $user->premium ? $premium_bonus : $normal_bonus;
$mysqli->prepare("UPDATE `users` SET `hourEvent` = ?, `userMana` = `userMana` + ?, `userCitizens` = `userCitizens` + 1 WHERE userId = ?")->execute([$time, $bonus, $user->userId]);
header("Location: /אזור-משחק/בסיס");
}
This removes lots of duplicate code between the cases, and only executes one query to add to userMana.
im trying to get a datetime variable (example: 2019-02-10 03:13:33) to update exactly a year. i read that datetime is written as a string so i tried to subtract by itself and add +365.
the code works if i take out all "expirationdate" including the bind value. also for some reason, i have to keep my UPDATEs encased in single quotations because theres no changes in my database if they are inside double quotes.
$stmt = $db->prepare('UPDATE usr_customer_profile SET packageid = 3, expirationdate = .'$oneyear'. WHERE usrcustomerid = :usrcustomerid');
$stmt->bindValue(':expirationdate', $_SESSION['expirationdate'], PDO::PARAM_STR);
$stmt->bindValue(':usrcustomerid', $_SESSION['usrcustomerid'], PDO::PARAM_INT);
$oneyear = (':expirationdate' - ':expirationdate') + 365;
$stmt->execute();
You can do this in PHP or SQL. In PHP you can use strtotime or (preferably) the DateTime class to add one year to the value in $_SESSION['expirationdate']:
// using strtotime
$expirationdate = date('Y-m-d H:i:s', strtotime($_SESSION['expirationdate'] . ' + 1 year'));
// using DateTime
$expiration = new DateTime($_SESSION['expiration_date']);
$expiration->add(new DateInterval('P1Y'));
$expirationdate = $expiration->format('Y-m-d H:i:s');
// do the query
$stmt = $db->prepare('UPDATE usr_customer_profile
SET packageid = 3,
expirationdate = :expirationdate
WHERE usrcustomerid = :usrcustomerid');
$stmt->bindValue(':expirationdate', $expirationdate, PDO::PARAM_STR);
$stmt->bindValue(':usrcustomerid', $_SESSION['usrcustomerid'], PDO::PARAM_INT);
$oneyear = (':expirationdate' - ':expirationdate') + 365;
$stmt->execute();
In SQL use + INTERVAL 1 YEAR to add 1 year to the expiration date:
$stmt = $db->prepare('UPDATE usr_customer_profile
SET packageid = 3,
expirationdate = :expirationdate + INTERVAL 1 YEAR
WHERE usrcustomerid = :usrcustomerid');
$stmt->bindValue(':expirationdate', $_SESSION['expirationdate'], PDO::PARAM_STR);
$stmt->bindValue(':usrcustomerid', $_SESSION['usrcustomerid'], PDO::PARAM_INT);
$oneyear = (':expirationdate' - ':expirationdate') + 365;
$stmt->execute();
I am writing a tool to search through different records in my database, where you have to specify the year. However, if no year value is entered, or is equal to zero, I want to be able to select all records.
$stmt = $mysqli->prepare("SELECT * FROM performances WHERE year = ?");
$stmt->bind_param("i", $year);
I have tried to do if statements, but they fail because then there are more parameters in bind_param than spaces in the query, m.sh:
$stmt = $mysqli->prepare("SELECT *
FROM performances
. (($year != 0) ? " WHERE year = ? " : " ")
. "");
$stmt->bind_param("i", $year);
Thanks
You can achieve this in different ways, like:
$stmt = $mysqli->prepare("SELECT * FROM performances WHERE year = :year or 0 = :year");
$stmt->bind_param("year", $year);
ShyForNow has a pretty good answer. I'd also recommend to validate inputs going into SQL:
$year = sprintf("%d", $year); -- or even throw exception if $year is not numeric
if ($year > 0) -- or could also write if ($year >= $minAcceptableYear and $year <= $maxAcceptableYear)
{
$stmt = $mysqli->prepare("SELECT * FROM performances WHERE year = ?");
$stmt->bind_param("i", $year);
}
else
{
$stmt = $mysqli->prepare("SELECT * FROM performances");
}
I've been looking for an answer to this all afternoon so far and cannot come up with anything yet.
I have the following MySQL PDO query:
$q = "select recip_id,
sum(case when msg_read = '0' AND msg_deleted = '0' then 1 else 0 end) uu,
sum(case when msg_read = '0' AND msg_deleted = '1' then 1 else 0 end) ud,
sum(case when msg_read = '1' AND msg_deleted = '0' then 1 else 0 end) ru,
sum(case when msg_read = '1' AND msg_deleted = '1' then 1 else 0 end) rd,
count(*) as total
from messages where recip_id = :d GROUP BY recip_id WITH ROLLUP";`
which, when I use recip_id = 18 for an example in PHPMyAdmin gives me the following table:
I have tried several ways to fetch the resulting row in php so that I can use the values for another task, to no avail. I've tried this:
$stmt = $dbo->prepare($q);
$row = $stmt->execute(array(":id" => $id));
$total = $row['total'];
$uu = $row['uu'];
$ud = $row['ud'];
$ru = $row['ru'];
$rd = $row['rd'];
echo "Recipient id: $id, Total: $total, UU: $uu, UD: $ud, RU: $ru, RD: $rd";
And this:
$stmt = $dbo->prepare($q);
$stmt->bindParam(":id", $id);
$msgcount = array();
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$total = $row->total;
$uu = $row->uu;
$ud = $row->ud;
$ru = $row->ru;
$rd = $row->rd;
}
echo "Recipient id: $id, Total: $total, UU: $uu, UD: $ud, RU: $ru, RD: $rd";
and this too:
$msgcount = array();
$stmt = $dbo->prepare($q);
$stmt->bindParam(":id", $id);
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($msgcount, array($row['uu'], $row['uu'], $row['ud'], $row['ru'], $row['rd']));
}
echo $msgcount[];
I cannot retrieve the values using my PHP script from the MySQL result set. I've tried serialize() on the rows and whole result set, I've tried to use PDO::FETCH_ASSOC and also unspecified fetch() and fetchAll(). *'ve used different combos and just get an empty result set or *I can't find an answer anywhere either. Can anyone help me with this please?
In your first attempt you forget to $stmt->fetch, and in the last two you forget $stmt->execute. Try this:
$stmt = $dbo->prepare($q);
if ( ! $stmt->execute(array(":id" => $id)) ) die("error"); // returns true or false
$row = $stmt->fetch(); // add this line!
$total = $row['total'];
$uu = $row['uu'];
$ud = $row['ud'];
$ru = $row['ru'];
$rd = $row['rd'];
echo "Recipient id: $id, Total: $total, UU: $uu, UD: $ud, RU: $ru, RD: $rd";