PHP mysqli_fetch_array stopping at 360 results - php

I have a conundrum I'm struggling to crack.
I have a database with 719 entries that I'm running a script on, these entries are Characters in a game and is what they will be referenced as.
However my while loop stops at 360 every time...
See below:
$query = mysqli_query($con,"SELECT * FROM users ORDER BY entryID;");
// Start loopy loop
$runCount = 0;
$CharNum = 0;
echo "NumRows = ".mysqli_num_rows($query)."<br/>"; // Outputs: NumRows = 719
while ($row = mysqli_fetch_array($query)) {
echo "Character#: ".++$CharNum."<br/>"; // Outputs: Counter stops at 360??
$entryID = $row["entryID"];
$CharacterID = $row["characterID"];
$blue = $row["blue"];
$tsDatabaseID = $row["tsDatabaseID"];
$tsUniqueID = $row["tsUniqueID"];
$tsName = $row["tsName"];
if (...[tonnes of code here]
}
echo "Runcount = ".++$runCount."<br/>"; // Outputs: Another counter stops at 360??
}
echo [some report summary]
I have no idea how or why it is stopping, but it isn't crashing as the report summary is showing after the while finishes but it is too perfect to be 360 every time??

So fun story,
if (!mysqli_fetch_array($query)) {
Doesn't sanity check it like I thought to see if it's valid, but performs the fetch in a way it screws everything up. Perhaps someone can explain this who is better than I. But this was inside my if.

Related

How to load a php page with a 24 hours script running?

Here is the case first and then if necessary I'll post code:
The script
I have a PHP script with a for loop, that for loop will take 24
hours to be completed.
The problem
The page doesn't load because it waits until the for loop is
completed.
What I try to do
To show the page while the for loop is running
PD: Please don't suggest Google nor PHP Manual, both tried, nothing found.
Here some code:
for ($s = $getEnergy; $s < $maxEnergy; $s += $getEnergy + $sumEnergy2){
$prodToEnergySql = "UPDATE ".$planetSolar." SET energy = ".$s."";
$prodToEnergyResult = mysqli_query($db,$prodToEnergySql);
$solarSQL3 = "SELECT energy FROM ".$planetSolar."";
$solarResult3 = mysqli_query($db,$solarSQL3);
$solarRows3 = mysqli_fetch_array($solarResult3);
$solarEnergy = $solarRows3['energy'];
}
Note that $getEnergy is 0 and $maxEnergy 1.200, increment 0,14.
Alternative Code
while ($getEnergy < $maxEnergy ){
$prodToEnergySql = "UPDATE ".$planetSolar." SET energy = energy + ".$sumEnergy2."";
$prodToEnergyResult = mysqli_query($db,$prodToEnergySql);
$solarSQL3 = "SELECT energy FROM ".$planetSolar."";
$solarResult3 = mysqli_query($db,$solarSQL3);
$solarRows3 = mysqli_fetch_array($solarResult3);
$solarEnergy = $solarRows3['energy'];
}
Note: there are at least 8 variables needed to execute the script.

PHP + MySQL suddenly stops the query

I can't understand how and why my mysql_query command stops it's execution.
There are two arrays I work with:
routersTree (includes about 100 rows)
dates (includes about 30 cells)
Here the code:
while ($i <= count($routerTree)){
$currentRouter = $routerTree["router_$i"];
echo "<td>$i</td>";
for ($j = 0; $j < count($dates); $j++) {
$sql = "SELECT indications.id_device FROM indications LEFT JOIN routers ON indications.id_device = routers.id_device WHERE routers.id_router = $currentRouter[id_router] AND date(indications.dateField) = '$dates[$j]' ORDER BY routers.id_device";
if ($res = mysql_num_rows(mysql_query($sql))) {
echo "<td>$res</td>";
}
else {
echo "<td>error</td>";
}
}
}
It stops my cycle after 18-th row, but there are about 82 cycles more to do.
My guess is, that there is a small timeout for mysql_query command.
Any help would be appreciate.
Well, after continue finding the solution of my problem I finaly found one. So easy and so fast... The problem was in PHP timeout. I just added into my settings.php file next entry:
ini_set ('max_execution_time', 0);
The default value is 30 seconds. 0 means the infinite loop. But be careful with this thing. Rise the value for your needs, but try not to use infinite loop.

Select random array generated from while loop

im learning PHP because i made only designs and templates, and i came to an big problem, at least for me. I am making simple "army battle script" where each player has some troops with attack, defense, hp stats, and they battle against each other. Ive made attack player vs player but i am struggling about many entity fight and how to code it.
First im calling all my units sended to attack, run it trought the loop and get in array every row/unit
Then i made that with enemy units, and in the end, i have a simple simulation script that makes the fight. But the fight isnt working. It doesnt select random unit from the array, it doesnt switch between attacker x defender turns and whats the worse, it only runs with one unit, when that units dies, the script ends and thats it... Can you guys please give me some answer, or way to handle this? I will be so thankfull because i am solving this for few days and i have no clue. Thanks. (i know that the code is ugly, but its just concept...)
//EDIT
Ok, i turned on the error reports and change a bit the simulation code, but the results are bad. I get error Fatal error: Maximum execution time of 30 seconds exceeded in or Warning: Division by zero in php in line
$hit = ($attacker['attack']/$defender['defense']) + rand(1, 2);
Heres the full code, ive tried rand(0,count($unit_attacker_def)-1); but i think its without changes. Also i added selecting new random array with unit, if there is 0 health and unset. And its still running trought one unit, not all in attacker array, and all, or left units in defender array. I somehow came to phase where the script calls the next unit, but it havent any variables in it loaded.
case 'battle_wizard_execute';
?>
<table>
<tr><td><h3>Utok</h3></td></tr>
<?
$query_street = mysql_query("SELECT * FROM game_army_attacks WHERE attack_id = '".$_GET['id']."' ");
$row_street = mysql_fetch_assoc($query_street);
$query_loc_info = mysql_query("SELECT * FROM game_location_street WHERE street_id = '".$row_street['attack_attacker']."' ");
$row_loc_info = mysql_fetch_assoc($query_loc_info);
$tilee_info = mysql_num_rows($query_street);
if ($tilee_info > 0){
$query_units_info = mysql_query("SELECT * FROM game_army_units_attacking WHERE army_attack = '".$_GET['id']."' ");
while (($unitsinfo = mysql_fetch_assoc($query_units_info)) != NULL) {
$query_unit_info = mysql_query("SELECT * FROM game_army_class WHERE army_class_id = '".$unitsinfo['army_class_id']."' ");
$unit = mysql_fetch_assoc($query_unit_info);
$unit_attacker = array();
$unit_attacker[] = array(
'name' => $unit['army_class_name'],
'power' => $unitsinfo['army_power'],
'attack' => $unitsinfo['army_att'],
'defense' => $unitsinfo['army_def']
);
///// Kolko jednotiek máš tolko krat sa vypise
$x = 1;
while($x <= $unitsinfo['army_population']) {
foreach($unit_attacker as $index => $record){
///// Tato cast pusti kod pre kazdu jednu jednotku ktora je v poli
echo "<tr><td>Jednotka: {$record['name']} ID: {$record['power']} ParentID: {$record['attack']} Title: {$record['defense']}</td></tr>";
$x++;
}
}
}
}
?>
</table>
<table>
<tr><td><h3>Utok protivnik</h3></td></tr>
<?
$query_street_def = mysql_query("SELECT * FROM game_army_units WHERE army_street = '".$row_street['attack_defender']."' ");
$tilee_info_def = mysql_num_rows($query_street_def);
if ($tilee_info_def > 0){
$query_units_info_def = mysql_query("SELECT * FROM game_army_units WHERE army_street = '".$row_street['attack_defender']."' ");
while (($unitsinfo_def = mysql_fetch_assoc($query_units_info_def)) != NULL) {
$query_unit_info_def = mysql_query("SELECT * FROM game_army_class WHERE army_class_id = '".$unitsinfo_def['army_class_id']."' ");
$unit_def = mysql_fetch_assoc($query_unit_info_def);
$unit_attacker_def = array();
$unit_attacker_def[] = array(
'name' => $unit_def['army_class_name'],
'power' => $unitsinfo_def['army_power'],
'attack' => $unitsinfo_def['army_att'],
'defense' => $unitsinfo_def['army_def']
);
///// Kolko jednotiek máš tolko krat sa vypise
$y = 1;
while($y <= $unitsinfo_def['army_population']) {
foreach($unit_attacker_def as $index => $record_def){
///// Tato cast pusti kod pre kazdu jednu jednotku ktora je v poli
echo "<tr><td>Jednotka: {$record_def['name']} ID: {$record_def['power']} ParentID: {$record_def['attack']} Title: {$record_def['defense']}</td></tr>";
$y++;
}
}
}
}
Simulation:
$count = 0;
while ((count($unit_attacker_def) > 0) && (count($unit_attacker) > 0)){
$count++;
$attacker_key = rand(0,count($unit_attacker_def)-1);
$attacker =& $unit_attacker[$attacker_key];
$defender_key = rand(0,count($unit_defender)-1);
$defender =& $unit_attacker_def[$defender_key];
while (($defender['power'] >= 0) && ($defender['power'] >= 0)){
$hit = ($attacker['attack']/$defender['defense']) + rand(1, 2);
echo "<tr><td>{$count}.xx {$attacker_key} xJednotka {$defender['name']} ({$defender['power']} hp) bola zranená a dostala {$hit} zranenia jednotkou {$attacker['name']} ({$attacker['power']} hp)</td></tr>";
$defender['power'] = $defender['power'] - $hit;
$attacker['power'] = $attacker['power'] - $hit;
if ($defender['power'] <= 0) {
echo "<tr>Jednotka {$defender['name']} umrela, jednotka {$attacker['name']} vyhrala!</tr>";
unset($defender[$defender_key]);
$defender_key = rand(0,count($unit_defender)-1);
$defender =& $unit_attacker_def[$defender_key];
}
if ($attacker['power'] <= 0) {
echo "<tr>Jednotka {$attacker['name']} umrela, jednotka {$defender['name']} vyhrala!</tr>";
unset($attacker[$attacker_key]);
$attacker_key = rand(0,count($unit_attacker_def)-1);
$attacker =& $unit_attacker[$attacker_key];
}
}
}
?>
</table>
<?
break;
Well you use array_rand() it selects one element from the array and when u use $array[$key] where $key = 1 because of array to var conversion it returns second element of your array atackers and second element of defenders. Use rand(0,count($unit_attacker)-1) to generate random key. But it still will be bugy because you can generate the same key )).
First of all, make sure you have turned on error reporting:
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
With simple debugging you will find out where is an error. Just var_dump() every important variable and check its state. Nobody can debug for you because we don't know what is the data in your mysql table.
Try to use mysqli_* functions, because mysql are deprecated.
Try to use classes to describe everything in your game and make it more readable and maintainable. For example:
<?php
abstract class Unit{
protected $hp;
protected $damage;
protected $defense;
// Force Extending class to define this method
abstract protected function applyDamage($damage);
}
class GroundUnit extends Unit{
//GroundUnit inherits everything from Unit
//define methods specific for GroundUnits
}
class FlyingUnit extends Unit{
//FlyingUnit inherits everything from Unit
//define methods specific for GroundUnits
}
When you find where is an error, and if you are still stuck, update your question with relevant data.
Note that your code is vulnerable to SQL injection
$query_street = mysql_query("SELECT * FROM game_army_attacks WHERE attack_id = '".$_GET['id']."' ");//don't put $_GET['id'] directly into query because that is security hole
Simple steps(related to your example) to improve your protection from sql injection would be :
//assume that $_GET['id'] should hold an integer value
$id = isset($_GET['id']? trim($_GET['id']) ? 0);
$id = (int)$id;
Now let's pretend that there is a $_GET['some_key'] also and it should hold string value. Now checks would be little different:
$some_string_value = isset($_GET['some_key']? trim($_GET['some_key']) ? '');
$some_string_value = trim($some_string_value);//triming whitespace
$some_string_value = mysql_real_escape_string($some_string_value);//escaping troublesome quotes(')
Also you can use prepared statements which is in my opinion a preferred way.

How do I scan an array and stop the scan when the number becomes false, and echo what number made the loop false in PHP

Basically I am creating a simple music player in PHP and I am setting the id of each song that is played in an array. I have a script which pulls a random number and plays the song with the corresponding id. I want to make it so that if the song has already played that it wont play again.
Currently I have it generate a random number, and if that number has already been played then it adds 1 to the random number.
The problem is if the number that is the result of adding 1 to the random number, it will then play that song again. I was attempting to store the songs played in an array and just increment the number until it doesn't exist in the array but I am struggling to find a solution to the problem.
My code is as follows:
<?php
session_start();
$con=mysqli_connect("blah blah blah");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!isset($_SESSION['played'])) {
$_SESSION['played'] = array();
}
$result = mysqli_query($con,"SELECT * FROM Data") ;
$num_rows = mysqli_num_rows($result);
$numsongs= .20 * $num_rows;
$numsongs=floor($numsongs);
$music = rand(1,$numsongs);
if (in_array($music, $_SESSION['played'])) {$music = $music+1;};
/* goes on to play music below */
$_SESSION['played'][] = $music;
?>
I didn't put my whole script in, the script works minus the repeating of songs. I only included a snippet of how I wrote the repeating script to give an idea of how I attempted it.
Thanks in advance!
I think you are looking for this...
$music = rand(1,$numsongs);
while(in_array($music, $_SESSION['played'])){
$music = $music+1;
echo 'in array '.$music;
}
echo 'Not in array '.$music;
AHAAA!! I figured it out! I ended up using switch() but in a different form.
if (empty($_SESSION['played1'])) {
for ($i = 1; $i <= $numsongs; ++$i) {
$_SESSION['played1'][] = $i;}}
shuffle($_SESSION['played1']);
$music1= $_SESSION['played1'][0];
$result = mysqli_query($con,"SELECT * FROM Data WHERE position = '$music1'") ;
while($row = mysqli_fetch_array($result)){
$del_val=$row[position];
if(($key = array_search($del_val, $_SESSION['played1'])) !== false) {
unset($_SESSION['played1'][$key]);}
Basically created an array between 1 and 10. Then used switch() to randomize the array. Then picked the first number in the array, used it in mysqli query, and then removed it from the array. Problem Solved!!

Javascript loop not setting PHP value via sqlite_fetch_array() when adding series in Highcharts

I have a SQLite database and am trying to graph data on a linechart using Highcharts, PHP, and Javascript. I am graphing one series per user (a user being a text value per tuple), but am running into trouble with retrieving a subsequent user via a PHP loop.
$dbhandle = sqlite_open('db/test.db', 0666, $error);
if (!$dbhandle) die ($error);
$query5 = "SELECT DISTINCT User FROM Events";
$ok0 = sqlite_query($dbhandle, $query5, $error_msg);
if (!$ok0)
{
die("dead" . $error_msg);
}
$rows = sqlite_num_rows($ok0);
echo
"for(var i=2; i<$rows; i++) // start of JS loop.
//$rows is 4; I am graphing 2 series here
{";
$array = sqlite_fetch_array($ok0, SQLITE_ASSOC); // $ok0 is the unique list
// of users. After graphing one series, I want to grab the next user to graph
echo "chart.addSeries({
name: '{$array["User"]}',
data: [";
for($i=0; $i<$diff+1; $i++)
{
$target = date("D, j M", (strtotime($_GET["start"]) + $i * 24 * 3600));
$query6 = "SELECT * FROM Events WHERE User = '{$array["User"]}' AND Start LIKE '%{$target}%'";
$result6 = sqlite_query($dbhandle, $query6);
if (!$result6) die("Cannot execute query.");
$num = sqlite_num_rows($result6);
if($i==($diff))
{
echo $num;
}
else
echo $num . ", ";
}?>],
pointStart:
<?php
$date = DateTime::createFromFormat('D M d Y', urldecode($_GET["start"]));
echo $date->getTimestamp()*1000;?>,
pointInterval: 24 * 3600 * 1000 // one day
});
<?php echo "}";?> // end of JS loop
The result does graph two additional series, but they are both the same data from the same user. It doesn't look like the loop with sqlite_fetch_array() correctly returns the next user. Can anyone see the problem here? Maybe something with the way I'm integrating Javascript with PHP?
This line of code always does the same thing every time you call it:
$query6 = "SELECT * FROM Events WHERE User = '{$array["User"]}' AND Start LIKE '%{$target}%'";
$array supposedly has a list of distinct users, but you don't show the query for $ok0. You're doing the user lookup inside this loop for($i=0; $i<$diff+1; $i++), but you use none of those variables in determining which user to fetch.
I'd like to post the correct way to look up the next user from $array, but I have no idea what the structure is. If you can't figure out how to make your $query6 unique to each user, you'll have to post more information, like a var_dump of $array or the query text of $ok0.
Maybe you just need to move this line $array = sqlite_fetch_array($ok0, SQLITE_ASSOC); inside your for loop, but then you run the risk of $i and $diff+1 disagreeing with the number of rows available from your result.
I've figured it out. I believe that due to PHP being executed server-side, the block of code within the echoed Javascript loop results in the same values when the browser executes the Javascript. The server simply echoes the string that represents the js loop, and will run the code block after. When everything is sent to the browser, the Javascript will loop normally and simply output the results of the code block twice. I've just forgone the JS loop via PHP and replaced it with a PHP loop.

Categories