I'm trying to design a PHP browser game just for fun and practice. I'm currently working on the combat script and I encountered an endless loop. I can't figure out the reason why it's happening. Anyways, here's the code:
<?php
session_start();
// Script PHP pentru simularea luptelor single player
/*
1 = Magic
2 = Attack
3 = Defence
5 = Maximum HP
6 = Current HP
4 = Gold coins
17 = Experience
*/
require_once("config.php");
$username = $_SESSION['username'];
$query = ("SELECT id FROM users WHERE username = '$username'");
$user_id = mysql_query($query) or die (mysql_error());
// Momentan monstrii sunt alesi in mod aleatoriu
$query = ("SELECT id FROM monsters ORDER BY RAND() LIMIT 1");
$monster_id = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM user_stats WHERE stat_id = 6 AND user_id = '$user_id'");
$player_hp = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 5 AND monster_id = '$monster_id'");
$monster_hp = mysql_query($query) or die (mysql_error());
if ($player_hp <= 0)
{
$query = ("SELECT value FROM user_stats WHERE stat_id = 4 AND user_id = '$user_id'");
$player_gc = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 4 AND user_id = '$monster_id'");
$monster_gc = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM user_stats WHERE stat_id = 17 AND user_id = '$monster_id'");
$player_exp = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 17 AND monster_id = '$monster_id'");
$monster_exp = mysql_query($query) or die (mysql_error());
$player_gc = $player_gc + $monster_gc;
$player_exp = $player_exp + $monster_exp;
// item drop trebuie facut
echo "Congratulations! You won the battle and you gained " . $monster_gc . " gold coins and " . $monster_exp . " experience points.";
}
elseif ($monster_hp <= 0)
{
echo "You lost the battle.";
}
else
{
$query = ("SELECT value FROM user_stats WHERE stat_id = 1 AND user_id = '$user_id'");
$player_magic = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 1 AND monster_id = '$monster_id'");
$monster_magic = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM user_stats WHERE stat_id = 2 AND user_id = '$user_id'");
$player_attack = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 2 AND monster_id = '$monster_id'");
$monster_attack = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM user_stats WHERE stat_id = 3 AND user_id = '$user_id'");
$player_defence = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 3 AND monster_id = '$monster_id'");
$monster_defence = mysql_query($query) or die (mysql_error());
$turn = rand(0,1);
while (($player_hp > 0) && ($monster_hp > 0) &&($turn < 6))
{
$turn++;
// Player turn
if ($turn % 2 == 0)
{
echo $monster_hp . "<br>";
$monster_hp -= ($player_attack + $player_magic / 2 - $monster_defence - $monster_magic / 2);
var_dump ($monster_hp);
}
// Monster turn
else
{
echo $player_hp . "<br>";
$player_hp -= ($monster_attack + $monster_magic / 2 - $player_defence - $player_magic / 2);
var_dump ($player_hp);
}
}
}
?>
The while is down in the else. I know that MySQL is depreciated. Thanks!
Are you after this (operator is -= not -):
// Player turn
if ($turn % 2 == 0)
{
$monster_hp -= ($player_attack + $player_magic / 2 - $monster_defence - $monster_magic / 2);
}
// Monster turn
else
{
$player_hp -= ($monster_attack + $monster_magic / 2 - $player_defence - $player_magic / 2);
}
-edit- if your variable is Resource id #5 etc, it means you haven't correctly retried your MySQL data from PHP. Try this:
$query = ("SELECT value FROM user_stats WHERE stat_id = 3 AND user_id = '$user_id'");
$player_defence = mysql_query($query) or die (mysql_error());
$player_defence = mysql_fetch_assoc($player_defence);
$player_defence = $player_defence['value'];
You'll need to do that (or something similar) for every query result you're getting. It converts your query result to an associate array then to the variable you need.
Manual: http://php.net/manual/en/function.mysql-fetch-assoc.php
In your while loop you never actually CHANGE the HPs of the monsters and players:
$monster_hp - ($player_attack + $player_magic / 2 - $monster_defence - $monster_magic / 2);
Did you mean to use something like this instead:
$monster_hp -= ($player_attack + $player_magic / 2 - $monster_defence - $monster_magic / 2);
The -= operator is really a quick way of programming equals itself minus...:
// The following lines are identical in logic:
$var-=1
$var=$var-1;
Related
This new code works for me, but not quite, the problem now is that all users have the sameness ranking, all have 1°
<?php
mysql_connect($mysql_host, $mysql_user, $mysql_pass) or die(mysql_error());
mysql_select_db($mysql_db) or die(mysql_error());
$sql = "SELECT ID, Name, username, Wins, Loses, Draws, (Wins + Loses) AS points FROM users WHERE username='$_GET[user]' ORDER BY points DESC";
$result = mysql_query($sql) or die(mysql_error());
if( !$result ){
echo 'SQL Query Failed';
}else{
$rank = 0;
$last_score = false;
$rows = 0;
while( $row = mysql_fetch_array( $result ) ){
$rows++;
if( $last_score!= $row['Wins'] ){
$last_score = $row['Wins'];
$rank = $rows;
}
echo "rank ".$rank." is ".$row['Name']." with point ".$row['Wins']."";
}
}
?>
I NEED
Example:
ID username Wins Loses
1 demo 12 12 RANKIG= 1°
2 demo2 1 3 RANKIG= 2°
Try your query as:
$result=mysql_query("SELECT ID, Name, username, Wins, Loses, Draws, (Wins + Loses) AS points, count(points) AS Ranking FROM `users` WHERE username='$_GET[user]' ORDER BY CONVERT(points, INT) DESC");
I have the following code to validate a user login at database.
Running this SELECT query at phpMyadmin, the result is "Showing rows 0 - 0 ( 1 total, Query took 0.0011 sec)".
For this reason the mysqli_num_rows($query) count is null when I echoes it.
What is wrong?
$sql = "SELECT
Id_Usuario,
Nome_Usuario,
Matricula_Usuario,
Email_Usuario,
Senha_Usuario,
Perfil_Usuario,
Status_Usuario
FROM USUARIO
WHERE Email_Usuario = '".$email."' AND Senha_Usuario = '".$senha."'
LIMIT 1";
$query = mysqli_query($conecta, $sql, MYSQLI_STORE_RESULT) or die('Problem running query: ' . mysql_error());
$row = mysqli_num_rows($query);
while ($row = mysqli_fetch_assoc($query)) {
$Id_Usuario = $row['Id_Usuario'];
$Nome_Usuario = $row['Nome_Usuario'];
$Matricula_Usuario = $row['Matricula_Usuario'];
$Email_Usuario = $row['Email_Usuario'];
$Senha_Usuario = $row['Senha_Usuario'];
$Perfil_Usuario = $row['Perfil_Usuario'];
$Status_Usuario = $row['Status_Usuario'];
}
I am trying to get a random row from MySQL table but all three attemps:
$query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
$query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
give a NULL result in mysql_query($query).
Higher up my PHP code I obtain a row from the same table OK by specifying WHERE, so I don't understand why I can't retrieve a random one.
Here is the code snippet:
$query = "SELECT uid,clu FROM uable WHERE un = '$un'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$resultid = mysql_fetch_assoc($result);
$uid = $resultid['uid'];
file_put_contents('debugging.txt',__LINE__.' - $uid = '.var_export($uid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE uid = $uid AND cn = '$cn'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$cr = mysql_fetch_assoc($result);
$cid= $cr['cid'];
file_put_contents('debugging.txt',__LINE__.' - $cid= '.var_export($cid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM fable WHERE cid= '$cid'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
file_put_contents('debugging.txt',__LINE__.' - $result = '.var_export($result,true).PHP_EOL,FILE_APPEND);
$fr = mysql_fetch_assoc($result);
file_put_contents('debugging.txt',__LINE__.' - $fr = '.var_export($fr,true).PHP_EOL,FILE_APPEND);
echo '<form action="'.$_SERVER['PHP_SELF'].’" method="post">';
if (!$fr) {
$o= $cn;
while ($o= $cn) {
// $ac = mysql_query("SELECT * FROM table") or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
// $num_rows = mysql_num_rows($ac);
//file_put_contents('debugging.txt',__LINE__.' - $num_rows = '.$num_rows.PHP_EOL,FILE_APPEND);
// --$num_rows;
// $query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
// $query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
$resultid = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($resultid);
$o= $opr['cn'];
}
file_put_contents('debugging.txt',__LINE__.' - $query = '.$query.PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $resultid = '.var_export($resultid,true).PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $op[\'cid\'] = '.$op['cid'].PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE cid= ".$op;
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($opr);
$o= $opr['cn'];
$od= $opr['description'];
echo '<p>'.$op;
if ($od<> '') {
echo ','.$odesc;
}
echo '</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
} else {
echo '<p>'.$fr['p'].'</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
}
echo '</form>';
The resulting debugging.txt:
24 - $uid = '4'
29 - $cid = '21'
32 - $result = NULL
34 - $fr = false
These queries look OK, but I think you're starting at the wrong place. When you're uncertain how to frame something in SQL, open up a SQL client like SequelPro or Navicat and try writing a few queries by hand until you get the result you want. (Also this gives you a chance to double-check the contents of relevant tables and ensure the expected data are there.) Then you can go back into the PHP with full confidence that the SQL code is correct, so if there's a problem it must be with the PHP (either the variables you inject into a Mysql statement, or the way you call that statement).
I'm working on a project where I have to show the leaderboard of players. But when wrote the below code, It shows the ranks with 2, 4, 6, 8, ... But not the odd numbered ranks. Can anyone tell me "What's wrong in this ?"
$query1_string = "CREATE VIEW Leaderboard AS SELECT Name, Points, PhoneNo
FROM user ORDER BY Points DESC";
$query2_string = "set #rank = 0";
$query3_string = "SELECT #rank := #rank + 1 as Rank, Name, Points
FROM Leaderboard";
$query5_string = "DROP VIEW Leaderboard";
// Doing the queries
$query1 = mysqli_query($con, $query1_string) or die(mysqli_error($con));
$query2 = mysqli_query($con, $query2_string) or die(mysqli_error($con));
$query3 = mysqli_query($con, $query3_string) or die(mysqli_error($con));
// Initializing the count
$count = 0;
//Making an array of strings including Rank, Name and Points of the Top 5 Players
while (($count < 5) && (mysqli_fetch_array($query3, MYSQL_NUM))) {
$row = mysqli_fetch_array($query3, MYSQL_NUM);
$results[$count] = $row[0] . " " . $row[1] . " " . $row[2];
$count++;
}
// Dropping the view.
$end_query = mysqli_query($con, $query5_string) or die(mysqli_error($con));
//Returning the array
$leader = implode("\n", $results);
echo $leader;
You are executing the query3 two times and displying the data retrieved from second execution
while (($count < 5) && (mysqli_fetch_array($query3, MYSQL_NUM))) {
$row = mysqli_fetch_array($query3, MYSQL_NUM);
I'm trying to optimize this check I have. I need to check table called lines and see if any row has matching Earned and Maxearned values (only rows with Position 1,2,3,4). If they do, I need to grab Earned from that row, write it in a different table called bank and remove that row from table called lines. This is what I have:
$sql3 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned";
$result3 = mysql_query($sql3);
if (mysql_num_rows($result3) != 0)
{
while ($row3 = mysql_fetch_array($result3))
{
$users[] = $row3['User'];
}
foreach ($users as $user)
{
$sql6 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User = '$user'";
$result4 = mysql_query($sql6);
while ($row4 = mysql_fetch_array($result4))
{
$earned = $row4['Earned'];
}
$today = date("Y-m-d");
$method = "Queue money";
$type = "Earned";
$status = "Completed";
$sql4 = "INSERT INTO bank (User,Amount,Method,Transdate,Type,Status) VALUES ('$user','$earned','$method','$today','$type','$status')";
$sql5 = "DELETE FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User = '$user'";
}
$sql7 = "UPDATE `lines` SET Position = Position - 1 WHERE Linenum = '$linenum'";
}
I'm trying to avoid having to run a different query ($sql6 and the while after that) to grab the value of Earned column. Is there a way to do this? I've tried everything and this is pretty much the best I came up with.
You can do something like this:
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$sql3 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned";
$result3 = mysql_query($sql3);
if (mysql_num_rows($result3) != 0)
{
while ($row3 = mysql_fetch_array($result3))
{
$users[] = $row3['User'];
}
$users_to_compare = "(" . rtrim(implode(",", $users),',') . ")";
$sql4 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User IN $users_to_compare";
$result4 = mysql_query($sql4);
while ($row4 = mysql_fetch_array($result4))
{
$earned = $row4['Earned'];
$today = date("Y-m-d");
$method = "Queue money";
$type = "Earned";
$status = "Completed";
$sql5 = "INSERT INTO bank (User,Amount,Method,Transdate,Type,Status) VALUES ('{$row4['User']}','$earned','$method','$today','$type','$status')";
$result5 = mysql_query($sql5);
}
$sql6 = "DELETE FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User IN $users_to_compare";
$result6 = mysql_query($sql6);
$sql7 = "UPDATE `lines` SET Position = Position - 1 WHERE Linenum = '$linenum'";
$result7 = mysql_query($sql7);
if ($result5 && $result5 && $result7) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
}
Going one step further you can also use Batch INSERT for you insert queries
Note: Dont forget that mysql_* versions are depreceated you should use mysqli_*