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)
Related
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
}
In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.
here i am trying to delete from detail table here is one problem with my code if detail table have three records than only delete one record from detail table.and also it does not effect other two records in stock table..
Only one first record this code work properly after that it does not work in for delete query from detail table and not effected in stock table...
<?php
include("include/config.inc.php");
$purchaseMasterId = isset($_REQUEST['purchaseMasterId']) ? $_REQUEST['purchaseMasterId'] : 0;
if($purchaseMasterId > 0) {
$k = 0;
$selectMaster = "SELECT purchasedetail.purchaseMasterId, colorId,
totalkg, purchaseDetailId, partyId
FROM purchasedetail
JOIN purchasemaster ON
purchaseMaster.purchaseMasterId = purchasedetail.purchaseMasterId
WHERE purchasedetail.purchaseMasterId = ".$_REQUEST['purchaseMasterId'];
$selectMasterRes = mysql_query($selectMaster);
while($purRow = mysql_fetch_array($selectMasterRes)) {
$purchaseDetailId = $purRow['purchaseDetailId'];
$purchaseMasterId = $purRow['purchaseMasterId'];
$colorId = $purRow['colorId'];
$totalkg = $purRow['totalkg'];
$partyId = $purRow['partyId'];
$select = "SELECT qty
FROM stock
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$selectRes = mysql_query($select);
if($stockRow = mysql_fetch_array($selectRes)) {
$current = $stockRow['qty'];
}
$updateStock = "UPDATE stock
SET qty = ".$current." - ".$totalkg."
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$updateStockRes = mysql_query($updateStock) or die(mysql_error());
if($updateStockRes) {
$deleteDt = "DELETE FROM purchasedetail
WHERE purchaseDetailId = ".$purchaseDetailId;
$deleteRes = mysql_query($deleteDt);
if($deleteRes){
$deleteMst = "DELETE FROM purchasemaster
WHERE purchaseMasterId = ".$_REQUEST['purchaseMasterId'];
$deleteMstRes = mysql_query($deleteMst) or die(mysql_error());
if(!$deleteMstRes) {
echo "Purchase Master Delete Fail";
} else {
header("Location:purdetail.php");
exit();
}
}
}
}
}
?>
Here is my updated code with perfect code working
<?php
include("include/config.inc.php");
$purchaseMasterId = isset($_REQUEST['purchaseMasterId']) ? $_REQUEST['purchaseMasterId'] : 0;
if($purchaseMasterId > 0)
{
$k = 0;
$selectMaster = "SELECT purchasedetail.purchaseMasterId,colorId,totalkg,purchaseDetailId,partyId
FROM purchasedetail
JOIN purchasemaster ON purchasemaster.purchaseMasterId = purchasedetail.purchaseMasterId
WHERE purchasedetail.purchaseMasterId = ".$_REQUEST['purchaseMasterId'];
$selectMasterRes = mysql_query($selectMaster) or die(mysql_error());
while($purRow = mysql_fetch_array($selectMasterRes))
{
$purchaseDetailId = $purRow['purchaseDetailId'];
$purchaseMasterId = $purRow['purchaseMasterId'];
$colorId = $purRow['colorId'];
$totalkg = $purRow['totalkg'];
$partyId = $purRow['partyId'];
$select = "SELECT qty
FROM stock
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$selectRes = mysql_query($select);
if($stockRow = mysql_fetch_array($selectRes))
{
$current = $stockRow['qty'];
}
$updateStock = "UPDATE stock
SET qty = ".$current." - ".$totalkg."
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$updateStockRes = mysql_query($updateStock) or die(mysql_error());
if($updateStockRes)
{
$deleteDt = "DELETE FROM purchasedetail
WHERE purchaseDetailId = ".$purchaseDetailId;
$deleteRes = mysql_query($deleteDt);
if($deleteRes)
{
$selectid = "SELECT purchaseDetailId
FROM purchasedetail
WHERE purchaseMasterId = ".$purchaseMasterId;
$selectidRes = mysql_query($selectid);
if(mysql_affected_rows() == 0)
{
$mst = "DELETE FROM purchasemaster
WHERE purchaseMasterId = ".$purchaseMasterId;
$mstRes = mysql_query($mst) or die(mysql_error());;
if($mstRes)
{
header("Location:purdetail.php");
exit();
}
else
{
}
}
}
}
}
}
?>
Okay so I am new to PHP and attempting to make a script that takes all of the data from a mysql database I have of stock prices and then looks to see if there was an increase in the stock price during after hours trading (by comparing one day's close price with the next day's open price). I have set up a few scripts like this that work, but for some reason this script isn't copying the data into my sql database and I am completely stumped as to why it won't.When I set up echo statements throughout I discovered that my code is seemingly being executed everywhere but the data isn't transferring. Any help is greatly appreciated.
<?php
include("../includes/connect.php");
function masterLoop(){
$mainTickerFile = fopen("../tickerMaster.txt","r");
while (!feof($mainTickerFile)){
$companyTicker = fgets($mainTickerFile);
$companyTicker = trim($companyTicker);
$nextDayIncrease = 0;
$nextDayDecrease = 0;
$nextDayNoChange = 0;
$total = 0;
$overnight_change = 0;
$overnight_change_pct = 0;
$sumOfIncreases = 0;
$sumOfDecreases = 0;
$sql = "SELECT date, open, close, percent_change FROM $companyTicker";
$result = mysql_query($sql);
if($result){
while($row = mysql_fetch_array($result)){
$date = $row['date'];
$percent_change = $row['percent_change'];
$open = $row['open'];
$close = $row['close'];
$sql2 = "SELECT date, open, close, percent_change FROM $companyTicker WHERE date > '$date' ORDER BY date ASC LIMIT 1";
$result2 = mysql_query($sql2);
$numberOfRows = mysql_num_rows($result2);
if($numberOfRows==1){
$row2 = mysql_fetch_row($result2);
$tom_date= $row2[0];
$tom_open= $row2[1];
$tom_close= $row2[2];
$tom_percent_change= $row2[3];
if ($close == 0){
$close = $tom_open;
}
$overnight_change = $tom_open - $close;
$overnight_change_pct = ($overnight_change/$close)*100;
if($overnight_change_pct > 0){
$nextDayIncrease++;
$sumOfIncreases += $tom_percent_change;
$total++;
}else if($overnight_change_pct < 0){
$nextDayDecrease++;
$sumOfDecreases += $tom_percent_change;
$total++;
}else{
$nextDayNoChange++;
$total++;
}
}else if ($numberOfRows==0){
$total = 1;
$nextDayIncrease = 1;
$nextDayDecrease = 1;
}else{
echo "You have an error in analysis_c3";
}
}
}else{
echo "unable to select $companyTicker <br />";
}
$nextDayIncreasePercent = ($nextDayIncrease/$total) * 100;
$nextDayDecreasePercent = ($nextDayDecrease/$total) * 100;
$averageIncreasePercentage = $sumOfIncreases/$nextDayIncrease;
$averageDecreasePercentage = $sumOfDecreases/$nextDayDecrease;
insertIntoResultTable($companyTicker, $nextDayIncrease, $nextDayIncreasePercent, $averageIncreasePercentage, $nextDayDecrease, $nextDayDecreasePercent, $averageDecreasePercentage);
}
}
function insertIntoResultTable($companyTicker, $nextDayIncrease, $nextDayIncreasePercent, $averageIncreasePercentage, $nextDayDecrease, $nextDayDecreasePercent, $averageDecreasePercentage){
$buyValue = $nextDayIncreasePercent * $averageIncreasePercentage;
$sellValue = $nextDayDecreasePercent * $averageDecreasePercentage;
$trueValue = $buyValue + $sellValue;
$query="SELECT * FROM analysisOvernightGain5 WHERE ticker='$companyTicker' ";
$result=mysql_query($query);
$numberOfRows = mysql_num_rows($result);
if($numberOfRows==1){
$sql = "UPDATE analysisOvernightGain5 SET ticker='$companyTicker',daysInc='$nextDayIncrease',pctOfDaysInc='$nextDayIncreasePercent',avgIncPct='$averageIncreasePercentage',daysDec='$nextDayDecrease',pctOfDaysDec='$nextDayDecreasePercent',avgDecPct='$averageDecreasePercentage',buyValue='$buyValue',sellValue='$sellValue'trueValue='$trueValue' WHERE ticker='$companyTicker' ";
mysql_query($sql);
}else{
$sql="INSERT INTO analysisOvernightGain5 (ticker,daysInc,pctOfDaysInc,avgIncPct,daysDec,pctOfDaysDec,avgDecPct,buyValue,sellValue,trueValue) VALUES ('$companyTicker', '$nextDayIncrease', '$nextDayIncreasePercent', '$averageIncreasePercentage', '$nextDayDecrease', '$nextDayDecreasePercent', '$averageDecreasePercentage', '$buyValue', '$sellValue','$trueValue')";
mysql_query($sql);
}
}
masterLoop();
?>
you have missed , at ,sellValue='$sellValue'trueValue='$trueValue'
it should be ,sellValue='$sellValue',trueValue='$trueValue'
First of all I am using JQGrid in my application. After changing my CSS to Bootstrap CSS.
I have to use DataTable. I want to reuse my controller pages which makes query to display the data in JQGrid.
Here is my controller page.
<?php
require_once("JsonHeader.php");
$at = $_SESSION['abc'];
$start_date = $_SESSION['start_date'];
$end_date = $_SESSION['end_date'];
if ($_SESSION['list'] == '-1') {
$user_query = "";
} else {
$user_list = $_SESSION['list'];
$user_query = " AND a.user_id IN ($list)";
}
$start_date = $_SESSION['start_date'];
$end_date = $_SESSION['end_date'];
if ($_SESSION['list'] == '-1') {
$user_query = "";
} else {
$user_list = $_SESSION['list'];
$user_query = " AND a.user_id IN ($list)";
}
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
$qtype = ''; // Search column
$query = ''; // Search string
if (isset($_GET['searchField'])) {
$qtype = mysql_real_escape_string($_GET['searchField']);
}
if (isset($_GET['searchString'])) {
$query = mysql_real_escape_string($_GET['searchString']);
}
if (isset($_GET['searchOper'])) {
switch ($_GET['searchOper']) {
case 'eq':
$oper = '=';
$query = mysql_real_escape_string($_GET['searchString']);
break;
case 'ne':
$oper = '!=';
$query = mysql_real_escape_string($_GET['searchString']);
break;
case 'cn':
$oper = 'like';
$query = "%".mysql_real_escape_string($_GET['searchString'])."%";
break;
}
}
$searchSql1 = ($qtype != '' && $query != '') ? "and $qtype $oper '$query'" : '';
if (!$sidx)
$sidx = 1; // connect to the database
$result = mysql_query(sprintf("SELECT ae.col1,ae.col2,ae.col3, ae.col4,ae.col5,ae.col6,ae.col7,a.col8,a.col9,r.col10,p.col11
FROM $tablename3 ae,$tableName a, $tablename1 p, $tablename2 r
WHERE ae.col1=$at $searchSql1
AND a.col1 = $at
AND a.col5=r.col5
AND a.col6=p.col6
$user_query"));
$row = mysql_num_rows($result);
$count = $row;
if ($count > 0) {
$total_pages = ceil($count / $limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages)
$page = $total_pages; $start = $limit * $page - $limit; // do not put
$limit * ($page - 1);
$SQL = sprintf("SELECT ae.col1,ae.col2,ae.col3, ae.col4,ae.col5,ae.col6,ae.col7,a.col8,a.col9,r.col10,p.col11
FROM $tablename3 ae,$tableName a, $tablename1 p, $tablename2 r
WHERE ae.col1=$at $searchSql1
AND a.col1 = $at
AND a.col5=r.col5
AND a.col6=p.col6
$query");
$result = mysql_query($SQL) or die("Couldn t execute query." . mysql_error());
$responce = new stdClass();
$responce->page = new stdClass();
$responce->total = new stdClass();
$responce->records = new stdClass();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$responce->rows[$i]['id'] = $row['col1'];
$responce->rows[$i]['cell'] = array($row['col1'], $row['col2'], $row['col3'], $row['col4'], $row['col5'], $row['col6'], $time, $row['col7']);
$i++;
}
echo json_encode($responce);
?>
HOW can I change this for DataTable?.
Please provide me the best way...
Finally I found how to resue my controller page for DataTable. Simply change the post variables in the controller page.
Like
$_GET['page']; By $_REQUEST['sEcho']
$_GET['rows']; By $_REQUEST['iDisplayStart'],$_REQUEST['iDisplayLength']
$_GET['sord']; $_REQUEST['sSortDir_0']
$_GET['searchString']: $_GET['sSearch']:
And some changes the json response like
$ans['iTotalRecords'] = $count;
$ans['iTotalDisplayRecords'] = $count;
$ans['aaData'] = $aadata;
echo json_encode($ans);