foreach ($_POST as $nazwa_checkboxa=>$id) {
$s = "SELECT uprawnienie FROM user WHERE Id_user=".$id;
$helpdesk = 0;
if ($s == 0) {
$helpdesk = 1;
}
$z = "UPDATE user SET uprawnienie = ".$helpdesk." WHERE Id_user=".$id;
$wynik = $polaczenie->query($z);
$zmienione++;
}
Column uprawnienie return 0 = normal user and 1 = administrator
The update always set value to 1 and I can change user to administrator (0 to 1) but it doesnÄ…t work 1 to 0
Actually, you can do it using one query, e.g.:
update user
set uprawnienie = (SELECT if(uprawnienie=1,0,1) FROM user WHERE Id_user = '<id>')
where Id_user = '<id>'
Looks like you haven't actually run the query() for $s. Therefore, the if ($s==0) is not checking the query results, but rather whether "SELECT..."==0. Per the PHP docs, "Strings will most likely return 0" when cast to integers for such comparisons.
Related
I am making Tournament mod. And I do not know how to correctly do some operations with fetched array.
What my code is doing, is that it takes data from Tournament table and add it to array. Then print it in HTML table, so all users can see the place where he has.
How can I correctly get the first, second, third array data for the first 3 winners and give them a price? And how can I deal with players who have the same amount of points?
Right now the query below seems to not work too, all statements are positiv and it should execute the function.
if($counter == 1) {
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `atm` = `atm` + 20000 WHERE `id` = ".$recordRow['id_owner']." ;");
}
Sorry, my English is not good and I tried to search for the answers but didn't find anything, because i do not know for what PHP solution should i search.
My code:
$recordFetch = $GLOBALS['DATABASE']->query("SELECT *FROM `uni1_tournament` ORDER BY wons DESC;");
$counter = 0;
$RangeList = array();
while ($recordRow = $GLOBALS['DATABASE']->fetch_array($recordFetch)) {
$counter += 1;
$RangeList[] = array(
'id' => $recordRow['id_owner'],
'name' => $recordRow['name'],
'points' => $recordRow['wons']*5,
'counter' => $counter,
);
if($t_time > TIMESTAMP) {
if($counter == 1) {
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `atm` = `atm` + 20000 WHERE `id` = ".$recordRow['id_owner']." ;");
}
elseif($counter == 2) {
//to do;
} elseif($counter == 3) {
//to do;
}
}
}
Make query like this "select * from uni1_tournament GROUP BY points ORDER BY
points desc limit 3";
If you're using regular mysql or mysqli (been a while since I have for either, moved to doctrine a while back), fetch_array needs to be ran on the results and not the GLOBALS['DATABASE'] variable (guessing this a global variable for the database connection).
Try changing
while ($recordRow = $GLOBALS['DATABASE']->fetch_array($recordFetch)) {
to
while ($recordRow = $recordFetch->fetch_array()) {
In order to use your original formatting, I believe fetch_array needed to be mysqli_fetch_array instead.
i.e
while ($recordRow = $GLOBALS['DATABASE']->mysqli_fetch_array($recordFetch)) {
PHP / MySQLI
$query = $conn->query(
"SELECT
cart.cart_id,
cart.user_ip,
cart.cart_amount,
cart.fk_product_id,
products.product_id,
products.prod_amount
FROM
cart
INNER JOIN
products
ON
cart.fk_product_id = products.product_id
WHERE
fk_product_id = '{$productID}' AND user_ip = '{$ip}'
");
$item = $query->fetch_assoc():
$FKproductID = $item['fk_product_id'];
$FKproductID = iSQLsecure($objConnection, $FKproductID);
$FKproductID = trim($FKproductID);
$CartAmount = $item['cart_amount'];
$CartAmount = iSQLsecure($objConnection, $CartAmount);
$CartAmount = trim($CartAmount);
$ProductAmount = $item['prod_amount'];
$ProductAmount = iSQLsecure($objConnection, $ProductAmount);
$ProductAmount = trim($ProductAmount);
$one = 1;
$add_amount = $CartAmount + $one;
$remove_amount = $ProductAmount - $one;
if($FKproductID == $productsID) {
$update_cart_item = $objConnection->query("UPDATE cart SET cart_amount = '{$add_amount}' WHERE fk_product_id = '{$productID}' AND user_ip = '{$ip}'");
$update_product_amount = $objConnection->query("UPDATE products SET prod_amount = '{$remove_amount}' WHERE product_id = '{$productID}'");
} else {
$add_item = $objConnection->query("INSERT INTO cart (user_ip, add_amount, fk_product_id) VALUES ('{$ip}', '{$add_amount}', '{$productID}')");
$update_product_amount = $objConnection->query("UPDATE products SET prod_amount = '{$remove_amount}' WHERE product_id = '{$productID}'");
}
$objConnection->close();
My Problem
$update_product_amount = $objConnection->query("UPDATE products SET prod_amount = '{$remove_ProductAmount}' WHERE product_id = '{$productID}'");
I use this two places if($FKproductID == $productsID) { /*HERE1*/ } else { /*AND HERE2*/}
For some reason it works in "HERE1" but not in "HERE2"?
If item is not in cart
It will insert it into my "cart" database and update "products" amount value. It is supposed to remove 1 from the current product amount (10 becomes 9). Instead it turns 10 into -1.
If item is in cart
It updates perfectly and turns 10 into 9. The code is the exact same but gives two different results?
I'll assume the above code isn't complete, since some variable name is inconsistent ($remove_amount vs $remove_ProductAmount) and yet your code run fine on some case.
For the queries, why don't you just subtract the amount on update query? Something like
UPDATE table SET field = field - 1 WHERE x = y
Even if the number 1 is dynamic, it's safer to generate the number on variables then cast it to integer. On worst case, it would be converted to zero (which can be easily added on your if() as additional validation).
I also recommend using debugger. Something like Kint or PsySH would suffice if you don't want to trouble yourself with setting up XDebug.
I think the issue may be with your INNER JOIN. From what I can tell, if the item isn't in your cart, then the cart.fk_product_id won't exist, and therefore the query will return an empty object.
If you have error display turned off (likely in the php.ini with display_errors = Off), non-existant array keys will be treated as null during equations.
When it comes time to do the equations, php will convert null to integer(0) which results in 0 - 1 = -1 if it fails the if statement.
Have you tried to output the returned object of the query? You can do this by using:
echo "<pre>"; print_r($item); echo "</pre>";
(the <pre> tag makes it a bit more readable).
Also, check the status of your httpd/apache error log if you have log_errors turned on.
I originally was satisfied with the following in order to update row 1 and row 2 to the same value (status=1)
if ($_POST){
$sql ="UPDATE table SET status = 1,
WHERE id IN (1,2 );";
db()->query($sql);
if(db()->query($sql)){
echo "<b>Good</b>";
}
else{
echo "<b>No Good</b>";
}
}
But now I want to update with different values, ie- row 1 to status 1, row 2 to status 2, and row 3 to status 3.
Off the bat, I know I need to
1. Use an array and loop through it three times.
2. pass in the array value into the $sql
I figure it would be something like this but I am still learning PHP..
$array_id = array(1, 2, 3);
$array_status = array(1, 2, 3);
if ($_POST){
$sql ="UPDATE table SET status = $array_status
WHERE id = $array_id;";
db()->query($sql);
if(db()->query($sql)){
echo "<b>Update Successful</b>";
}
else{
echo "<b>Update Unsuccessful</b>";
}
}
How would I go about making this happen?
You can loop through the arrays using a for loop and exec a query for each one (Radu Vlad answer), or you can build a long query and execute it once, something like this:
if ($_POST){
$sql = ""; // Blank string
$len = count($array_id); // Number of iterations
for ($i = 0; $i < $l; $i++) { // Enter the loop
$sql .= "UPDATE
table
SET
status = {$array_status[$i]}
WHERE id = {$array_id[$i]};"; // Append the query
}
db()->query($sql);
if(db()->query($sql)){
echo "<b>Update Successful</b>";
}
else{
echo "<b>Update Unsuccessful</b>";
}
}
When the val of $i is 0, then $array_id[$i] will print the first element, when $i is 1, $array_id[$i] will print the second element, and so on.
Using .= you append text to a string. By the end of the loop, $sql will be a string with 3 queries ('UPDATE ... SET ...; UPDATE ... SET ...; UPDATE ... SET ...;').
Not sure if it's the best way, though. But you get the idea.
If yow want the status to be equal to the id, do this (single query):
UPDATE table SET status=id WHERE id IN (1,2,3);
Of course you can use some math, like:
UPDATE table SET status=(id+1)*2 WHERE id IN (1,2,3);
You didn't really explain why you need that, so
try1(childish): set status = id
"UPDATE table SET status = id"
It's a bad practice, and only you could understand what those numbers are. Plus if id is auto-increment, status will be auto-increment too, you will have a duplicate column. If status has only 3 values posible, you should not do this.
try2(basic): do 3 updates, or actually, do as many as you need with a for
if ($_POST){
$status = 1;
for ($i = 1; $i <= 3; $i++){
$sql ="UPDATE table
SET status = $status
WHERE id = $i;";
db()->query($sql);
$status++;
}
A better way bacause you have more control over the status. Of course the second try is irrelevant if you have only that 3 values. This one assumes you will change the $status variable inside the for loop, in concordance with the $i (id)
try3(mature): set one or 2 arrays with the concordance between id and status, so that either $arr[$id] will have the value of status and the key will be the id, or $arr1[$i] will have the value of id, and $arr2[$i] will have the value of status
the example will have only one array(also called map, because you map a value based on another value)
if ($_POST){
$status_array = array(1 => 1,2 => 2,3 => 3);
for ($i = 1; $i <= 3; $i++){
$sql ="UPDATE table
SET status = $status_array[$i]
WHERE id = $i;";
db()->query($sql);
}
Also, this works because the array is consistent. If you do not have an consistent array you should either work with 2 arrays, or try a foreach with key->value instead of for
I would suggest you to use the following code:
$theArray = array("1" => "1","2" => "2","3" => "3"); // The scheme is ID => Status
$errorMsg = false; // Our default assumption is that no error occured
foreach($theArray as $key => $value) {
$sql = "UPDATE table SET status =".$value." WHERE id = ".$key;
if(!db() -> query($sql)) { // Execute the query and check whether it failed
$errorMsg = "Query for ID ".$key." failed.";
break; // When the query failed we exit the loop and echo the error message
}
}
if($errorMsg) { // If an error occured (errorMsg is no longer false) we echo it here
echo $errorMsg;
}
Basically you do just create one array $theArray, which contains key => value pairs of the IDs and the statuses you want to give them. Afterwards, you loop through this array, execute the db() -> query() for each key => value pair and check whether it failed or not. If a query failed, you break the loop and output the error message.
Advantages:
Instead of using two arrays ($array_id, $array_status) I do use only one associative array $theArray. The advantage here is that you only have one instead of two arrays and that you can extend the number of rows you'd like to change without changing your code. Just extend the array.
The array $theArray does not need to be in a chronological order and you can give each ID independently of the other IDs a status.
You are executing the db() -> query($sql) in your code two times. This is not very efficient and redundant. Instead you can execute the command only once and immediately check whether it failed or not based on its return value inside the if().
The errorMsg I am creating in the code let you know which query failed so it gives you a more detailed information for debugging.
If you want to update multiple rows (in single query) using the INSERT syntax, you can do this:
REPLACE table(id,status) VALUES(1,1),(2,2),(3,3)
Notice that id must be Primary Key or Unique, otherwise the REPLACE will insert a new row.
Notice also that REPLACE isn't SQL standard, and works only in MySQL.
Hey all i normally grab the ajax sent js object literal by doing this:
$_POST['called']
$_POST['chk1']
etc etc...
But now i have a problem that i cant seem to find a solution for.
Depending on how many checkboxes are selected, i loop (using js) to see all checked boxes and add them to the js object that ends up looking like this:
doBulk = {
called: "Approved",
chk0: "1789156857",
chk2: "5134465673753",
chk3: "234123554646",
chk10: "25511545542"
};
Now the chkXX can be any number from 0-19 (so 20 check boxes per page). I am sending that just fine to my PHP page but i am unsure on how to go about looping to get the needed data to update the database.
$chk1 = $_POST['chk0'];
$chk2 = $_POST['chk1'];
$chk3 = $_POST['chk2'];
$chk4 = $_POST['chk3'];
$chk5 = $_POST['chk4'];
$chk6 = $_POST['chk5'];
$chk7 = $_POST['chk6'];
$chk8 = $_POST['chk7'];
$chk9 = $_POST['chk8'];
$chk10 = $_POST['chk9'];
$chk11 = $_POST['chk10'];
$chk12 = $_POST['chk11'];
$chk13 = $_POST['chk12'];
$chk14 = $_POST['chk13'];
$chk15 = $_POST['chk14'];
$chk16 = $_POST['chk15'];
$chk17 = $_POST['chk16'];
$chk18 = $_POST['chk17'];
$chk19 = $_POST['chk18'];
$chk20 = $_POST['chk19'];
I could do a lot of if than else to check to see if each has data but there has got to be a better way of doing that?
So if i am doing a bulk mySQL update then i would have to run a query for each checkbox that i have a value for above? Is there also a better way of updating all the records that are needed in one swoop?
$result = mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID = " . $chk1 . "");
Thanks!
UPDATE
foreach($_POST as $key => $value)
{
// $key = CHK1-20
// $value = XXXXXXXXX
$dbBuilder = $value . ", " . $dbBuilder;
}
$dbBuilder = '(' . $dbBuilder . ')';
$result = mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID in $dbBuilder");
You can pass in the id's inside an IN SQL Clause. So, for instance you will have:
UPDATE userAccount SET Accept = 1 WHERE ID in $idCollection
Where $idCollection will be all of the IDs checked, separated by commas and inside parentheses, like so:
(1, 2, 3)
For the looping, you can iterate through the $_POST array as you would in any other array, and populate this string with the values read.
Hope that helps
for ($i=1;$i<=20;$i++){
${'chk'."$i"}=$_POST["chk"."$i"];
}
For UPDATE, i think you can use Mysql create procedure like this
$query=mysql_query("CREATE PROCEDURE dorepeat(p1 INT) SET $i = 0; REPEAT SET #i = #i + 1; UPDATE userAccount SET Accept = 1 WHERE ID = ${'chk'."$i"}; UNTIL #i =p1 END REPEAT; END") or (die mysql_error());
$result=mysql_query("CALL dorepeat(20)") or (die mysql_error());
EDIT: perhaps this is better without using CREATE PROCEDURE.
for ($i=1;$i<=20;$i++){
${'chk'."$i"}=$_POST["chk"."$i"];
$exp.=${'chk'."$i"}.',';
}
$exp=substr($exp,0,-1);
$exp='('.$exp.')';
$query=mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID IN '$exp') or (die mysql_error());
I'm programming a random event system that happens to users when logged in and I put the below piece of code into my include file.
$tehchance = mt_rand(1,15);
if ($tehchance == "1"){
$thewin = 10;
mysql_query("UPDATE members SET Points = Points + $thewin WHERE Handle = '$members[Handle]'");
}
I also have this for another event:
if ($tehchance == "2"){
$thekhwin = 5;
$thexpwin = 10;
mysql_query("UPDATE members SET Points = Points - $thekhwin WHERE Handle = '$members[Handle]'");
mysql_query("UPDATE members SET XP = XP + $thexpwin WHERE Handle = '$members[Handle]'");
}
The code will work but sometimes when $tehchance is equal to something else other than 1 or 2, it'll just ignore my conditions and update the members table without satisfying the if statement. From testing, it'll randomly add points or subtract points. I printed the random number from $tehchance and it still adds points even when it isn't equal to 1 or 2. Then sometimes it doesn't do anything to the members table. Really confused here.
Any ideas?
Try using an if-then-else and debug that.
$tehchance = mt_rand(1,15);
if ($tehchance === 1){
echo 'doing 1';
$thewin = 10;
mysql_query("UPDATE members SET Points = Points + $thewin WHERE Handle = '$members[Handle]'");
} else if ($tehchance === 2){
echo 'doing 2';
$thekhwin = 5;
$thexpwin = 10;
mysql_query("UPDATE members SET Points = Points - $thekhwin WHERE Handle = '$members[Handle]'");
mysql_query("UPDATE members SET XP = XP + $thexpwin WHERE Handle = '$members[Handle]'");
} else {
echo 'doing nothing';
}
because you are comparing to a string : "1" instead of the number 1 (without quotes)