UPDATE MYSQL DATA ROW USING IF ELSE WITHIN FOR LOOP - php

I am trying to make the user send an email which is not already referred to by him with below code. But else statement updates e-mail to data even if there is already the same e-mail existing in MySQL data row.
if(isset($row)){
if (array_key_exists("email", $_POST)){
$query = "SELECT id FROM users WHERE email = '".mysqli_real_escape_string($link,$_POST['email'])."' LIMIT 1";
$ans = mysqli_query($link, $query);
if(mysqli_num_rows($ans) > 0){
$nofriend = $_POST['email']." is already registered.";
}
else{
$referredemails = $row["rfremails"];
$array = explode(",", $referredemails);
print_r($array);
for($i = 0; $i < sizeof($array); $i++){
if($array[$i] == $_POST["email"]){
$nofriend = "This e-mail is already referred by you.";
}
else{
$referdate = getdate();
$timestamp = "$referdate[mday] $referdate[month] $referdate[year]";
$opngems = $row["gems"];
$query = "UPDATE users SET rfremails = '".$referredemails.",".$_POST["email"]."', gems = '".$opngems."+1-".$timestamp."-".$_POST["email"]."' WHERE id = '".mysqli_real_escape_string($link,$_SESSION['id'])."' LIMIT 1";
mysqli_query($link,$query);
header("Location: showupdate.php");
}
}
}
}
}

it is caused by condition in for cycle
for($i = 0; $i < sizeof($array); $i++){
if($array[$i] == $_POST["email"]){
//stuff
} else {
//....$query = "UPDATE users SET rfremails =...
}
}
when user have referred more than one email this condition will be evaluated as false and thus else segment of code will be processed, resulting in update in database.
it is wise to use help variables for such cases as this. e.g.:
$noFriend = false;
for ($i = 0; $i < sizeof($array); $i++) {
if ($array[$i] == $_POST["email"]) {
$noFriend = true;
...
}
if ($noFriend === false) {
//update
}
you can also use break statement when you find first occurence of same referred email, to speed things up.

Related

Auto Repeat Isset Post Until Requirements met

I have a php code that updates mysql tables with results of a fight.
When you press the button fight you excetude the below:
if(isset($_POST['attack_creature'])){
if($monnewhealth > "0"){ //if Monster exists
if($charhealth > "0"){ //if Character is alive go to fight
$fightcreature = "UPDATE user_character SET current_action_points = current_action_points-$fight_action_points WHERE ID = $currentUser AND current_action_points>$fight_action_points";
$stmt = $con->prepare($fightcreature);
$stmt->execute();
if($totalinflicteddamagetocreature > "0") {
$monnewhealth = $monnewhealth - $totalinflicteddamagetocreature;
if($monnewhealth < "0") {
$monnewhealth = 0;
}
$updatenmonewhealth = "UPDATE user_character SET fight_creature_new_health = $monnewhealth WHERE ID = $currentUser";
$stmt = $con->prepare($updatenmonewhealth);
$stmt->execute();
}
if($monnewhealth <= "0"){
$lastFight = $now_time;
$updatecharlastfightkills = "UPDATE user_character SET character_last_fight = $now_time, character_kills = $charkills+1, character_gold = $chargold+$mongoldreward, character_current_xp = $charexp+$monxpreward, current_xp_reward = $monxpreward, current_gold_reward = $mongoldreward WHERE ID = $currentUser";
$stmt = $con->prepare($updatecharlastfightkills);
$stmt->execute();
$insertbattlelog1 = "INSERT INTO battle_log (ID, battle_log_date, battle_log_result, battle_log_enemy_name, battle_log_enemy_lvl, battle_log_gold, battle_log_xp, battle_log_event) VALUES ('$currentUser', '$now_time', '1', '$monname', '$monlvl', '$charlastgoldreward', '$charlastxpreward', 'You have Destroyed Level $monlvl $monname and earned $monxpreward XP and $mongoldreward')";
mysqli_query($con, $insertbattlelog1);
}
if($monnewhealth > "0"){ //if Monster still alive
if($totalinflicteddamagetocharacter > "0") {
$charhealth = $charhealth - $totalinflicteddamagetocharacter;
if($charhealth < "0") {
$charhealth = 0;
}
$updatecharnewhealth = "UPDATE user_character SET current_health = $charhealth WHERE ID = $currentUser";
$stmt = $con->prepare($updatecharnewhealth);
$stmt->execute();
}
if($charhealth <= "0"){
$updatecharlastfightdeaths = "UPDATE user_character SET character_last_fight = $now_time, character_deaths = $chardeaths+1 WHERE ID = $currentUser";
$stmt = $con->prepare($updatecharlastfightdeaths);
$stmt->execute();
$insertbattlelog2 = "INSERT INTO battle_log (ID, battle_log_date, battle_log_result, battle_log_enemy_name, battle_log_enemy_lvl, battle_log_event) VALUES ('$currentUser', '$now_time', '2', '$monname', '$monlvl', '$charlastgoldreward', '$charlastxpreward', 'You have been killed by Level $monlvl $monname')";
mysqli_query($con, $insertbattlelog2);
}
}
}
}
header('Location: hunt.php');
}
I don't know how to repeat this process until monhealth or charhealth reach 0 Zero.
Also I want to log how many rounds took to reach 0 Zero and log every round totaldamages.
Many thank you in advance,
Chris
You can write a function and call it recursively with a condition.
function doIt() {
if($condition > 0) {
doIt();
}
}
doIt();
instead of using if just use while so if the $monnewhealth is still greater than 0 i will rerun the code block. and also add new variable $rounds thats increase on each round. something like the code below.
$rounds = 0;
while ($monnewhealth > "0") { // if($monnewhealth > "0"){
$rounds++; // this will cound your rounds
while ($charhealth > "0") { // if($charhealth > "0"){
// your huge code block here
}
}
A while loop would work in this case:
$roundCount = 0;
while($monnewhealth > 0 && $charhealth > 0) {
++$roundCount;
// Your current code
}

database query, compare each two rows but getting only first two rows

Hi i am querying my db so that i can compare every two rows. ex 1 and 2, then 2 and 3, then 3 and 4. and so on and so forth. but it only compares the first two rows. any ideas? here is my code:
$result = mysql_query("SELECT *FROM attendance ORDER BY pid ASC") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// $response["nominees"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$prev_sid = $row["sid"];
$prev_pid = $row["pid"];
$row2 = mysql_fetch_array($result);
if($row2["pid"] == $prev_pid){
if(($row2["sid"] - $prev_sid) == 1){
$attended_elec = mysql_query("SELECT pid FROM election_attendance where election_id = '$election_id'");
if(mysql_num_rows($attended_elec) > 0){
$not_officer = mysql_query("SELECT usertype FROM users WHERE pid = '$prev_pid'");
if(mysql_result($not_officer, 0) == "member"){
// echo "PID" . $prev_pid;
// $nominee["pid"] = $row2["pid"];
$user_details = mysql_query("SELECT *FROM users WHERE pid = '$prev_pid'");
if(mysql_num_rows($user_details) > 0){
$response["nominees"] = array();
while ($row3 = mysql_fetch_array($user_details)) {
$nominee = array();
$nominee["pid"] = $row3["pid"];
$nominee["firstname"] = $row3["firstname"];
$nominee["lastname"] = $row3["lastname"];
$nominee["gender"] = $row3["gender"];
$nominee["contact"] = $row3["contact"];
$nominee["email"] = $row3["email"];
$nominee["address"] = $row3["address"];
$nominee["institution"] = $row3["institution"];
$nominee["points"] = $row3["points"];
$nominee["usertype"] = $row3["usertype"];
// push single product into final response array
array_push($response["nominees"], $nominee);
}
}
}
}
}
}
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "There is no candidate yet from the records.";
// echo no users JSON
echo json_encode($response);
}
thanks in advance, have a nice day
Theres a problem right at the while(), you're fetching the 1st row, and is correct.
Then, inside it you fetch the 2nd, which is what you intend, but when the iteration is repeating, the while will fetch the 3rd, and the inner the 4th, so you lost there the comparisson between 2nd and 3rd.
// fetch data from DB
$results = "...";
if (mysql_num_rows($result) < 1)
{
// no products found tell your users
return;
}
// lets make some variables to walk through the list
$previous = mysql_fetch_array($results);
$actual = null;
// and now lets walk through the list
while($actual = mysql_fetch_array($results))
{
// execute your logic here
// than at the end move the actual row to become the previous
$previous = $actual;
}
NOTICE you shouldn't use mysql_ * methods they're are deprecated. you can use the brother mysqli_ * or PDO
I would do something like this? But there is almost certainly a less resource intensive way to do it.
$x = 0;
$y = 1;
$total = mysql_num_rows(mysql_query("SELECT * FROM `the_place`");
while ($x < $total AND $y < total){
$query1 = "SELECT * FROM `the_place` LIMIT $x,1";
$query2 = "SELECT * FROM `the_place` LIMIT $y,1";
$row1 = mysql_fetch_array(mysql_query($query1);
$row2 = mysql_fetch_array(mysql_query($query2);
// Do comparison here
if ($row1 == $row2){
// etc
}
$x = $x++;
$y = $y++;
}

PHP MySQL generating unique random number

I don't understand why my code isn't working. The connection works and everything else however when I try to generate a unique random number and check from the MySQL if the number is there it still prints out a random number but it's not UNIQUE. Could anyone help me thx?
Here's my code:
$num = rand(1,5);
$sel_query = "SELECT * FROM test";
$result2 = $con->query($sel_query);
$i = 1;
for (;$i<2; $i++)
{
while($row = mysqli_fetch_array($result2))
{
if ($row['id'] == $num)
{
$num = rand(1,5);
$i = 0;
}
}
}
This should work:
$is_unique = false;
$num = false;
while (!$is_unique){
$num = rand(1,5);
$sel_query = "SELECT id from test where id = " . $num;
$result2 = $con->query($sel_query) or die($conn->error);
if (!mysqli_fetch_array($result2)){
$is_unique = true;
}
}
echo "Unique number is " . $num;
But if there aren't any more possible unique numbers, it will loop forever.
I know this is a bit old, but I found this question after needing a similar answer. I've taken Jodes's answer and updated it slightly, so that it won't run forever, is a function that returns the number, and accepts a mysqli connection as $mysqli:
function getUniqueNumber($mysqli)
{
$is_unique = false;
$num = false;
$times_run = 0;
while (!$is_unique)
{
if($times_run > 10)
{
echo "Run too many times, dying.";
die();
}
$num = rand(1,5);
$sel_query = "SELECT id from test where id = " . $num;
$result2 = $mysqli->query($sel_query) or die($mysqli->error);
if (!mysqli_fetch_array($result2))
{
$is_unique = true;
}
$times_run++;
}
return $num;
}

MySQLi not returning rows in order

This is probably not a very difficult question to answer. I'm having trouble with this PHP function I wrote... it returns the rows line by line, but it's returning them incremented by 4 each time. So the the 1st row will output, then the 5th, then the 9th...
function showDatabases() {
# $_GET variables from the URL.
$database = mysql_real_escape_string($_GET['database']);
$table = mysql_real_escape_string($_GET['table']);
$mysqli = new mysqli('127.0.0.1', 'root', '', $database);
$query_one = $mysqli->query("SELECT * from $table");
$num_rows = mysqli_num_rows($query_one);
$num_fields = mysqli_num_fields($query_one);
for ($x = 0; $x < $num_rows; $x++) {
for ($c = 0; $c < $num_fields; $c++) {
$row = mysqli_fetch_row($query_one);
echo($row[$c]." ");
}
echo("<br/>");
}
}
Thanks!
mysqli_fetch_row fetched an entire row and moves the pointer to the following row. You should call it only once per each row; now you are calling it once per column.
That is,
for ($x = 0; $x < $num_rows; $x++) {
$row = mysqli_fetch_row($query_one);
for ($c = 0; $c < $num_fields; $c++) {
echo($row[$c]." ");
}
echo("<br/>");
}
you are complicating things
you can do it with just one loop
$query = "SELECT * from $table";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row['fieldname']." ";
}
}
I advice you to add order by some time the default order is not the id order.

INSERT INTO not populating database table

I have a script that checks the submitgame table and if both approve1 and approve 2 are not blank it inserts data into clanstats. There is no mysql_error it simply redirects to the header without inserting anything into the clanstats table, so I have no idea what is going on. Below is the code.
<?php
include("user.php");
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM submitgame WHERE id='$id'") or die(mysql_error());
$playerclan = $row['playerclan'];
$opponentclan = $row['opponentclan'];
$win = $row['win'];
$approve1 = $row['approve1'];
$approve2 = $row['approve2'];
if($win == "won") {
$win = 1;
$points = 2;
$win2 = 0;
$points2 = 1;
}
else {
$win = 0;
$points = 1;
$win2 = 1;
$points2 = 2;
}
if($approve1 != "" && $approve2 != "") {
$query=mysql_query("INSERT INTO clanstats (clan, points, wins) VALUES ('$playerclan', '$points', '$win')");
$query=mysql_query("INSERT INTO clanstats (clan, points, wins) VALUES ('$opponentclan', '$points2', '$win2')");
echo mysql_error($query);
}
else {
header("location:../approvegames.php");
}
mysql_close($con);
header("location:../approvegames.php");
?>
<?php
//first off are you connecting, ill presume so
include("user.php");
//sql injection!!!
$id = mysql_real_escape_string($_GET['id']);
$result = mysql_query("SELECT * FROM submitgame WHERE id='$id' limit 1") or die(mysql_error());
//you were missing this
$row=mysql_fetch_array($result);
$playerclan = $row['playerclan'];
$opponentclan = $row['opponentclan'];
$win = $row['win'];
$approve1 = $row['approve1'];
$approve2 = $row['approve2'];
if($win == "won") {
$win = 1;
$points = 2;
$win2 = 0;
$points2 = 1;
}else{
$win = 0;
$points = 1;
$win2 = 1;
$points2 = 2;
}
if($approve1 != "" && $approve2 != "") {
//you can have multiple inserts
$query=mysql_query("INSERT INTO clanstats (clan, points, wins) VALUES
('$playerclan', '$points', '$win'),
('$opponentclan', '$points2', '$win2')");
header("location:../approvegames.php");
//adding die after the header will make sure nothing else gets executed
die();
}else{
header("location:../approvegames.php");
die();
}
//no need to kill the connection as it will close when the script exits
?>
I think you are missing a line. Perhaps something like:
$row = mysql_fetch_row($result)

Categories