PHP Count Generated Results From Loop - php

I have this for loop that generates 10 results:
<?php
include "dbconnect.php";
$table = "SELECT id FROM players ORDER BY RAND()* ( 1 / percentage)";
for ($i = 0; $i < 10; $i++){
$result[0] = mysql_fetch_array(mysql_query($table));
foreach ($result as $winner){
echo $winner[0] . " ";
}
}
?>
It generates a result like:
10 10 11 9 13 11 10 12 8 12
My question is how do I count the generation? For the above example it would be:
8's = 1, 9's = 1, 10's = 3, 11's = 2, 12's = 2, 13's = 1.
I basically want to count the amount of specific results generated. Sorry if i'm not making much sense.

You need to get off of MySQL functions and check out PDO or MySQLI at a minimum. But for the meat of the question:
Don't run a query, full or limited in the loop
Look at the LIMIT clause in the query
array_count_values will count the values. You can loop it and echo or whatever
Example:
$table = "SELECT id FROM players ORDER BY RAND()*(1/percentage) LIMIT 10";
$result = mysql_query($table);
while($row = mysql_fetch_array($result)) {
$winner[] = $row[0];
}
echo implode(' ', $winner);
foreach(array_count_values($winner) as $number => $count) {
$output = "$number's = $count";
}
echo implode(', ', $output);
You're existing code to make the random choice work would look like (LIMIT 1):
$table = "SELECT id FROM players ORDER BY RAND()*(1/percentage) LIMIT 1";
for($i = 0; $i < 10; $i++){
$result = mysql_fetch_array(mysql_query($table));
$winner[] = $row[0];
}
echo implode(' ', $winner);

if you check the php manual:
http://php.net/manual/en/function.mysql-query.php
then try something like this:
while ($row = mysql_fetch_assoc($table)) {
echo $row['column_name'];
echo $row['column_name'];
//.. you get the idea
}
The id is usually the first column in a database table. This is why you are just getting the id. You need to access each row in the same way you access arrays.
I should point out that the mysql library is deprecated. So you should consider using something like PDO instead.

Related

MySQL Select Random from All but not double time

i want to show Random Item with Select by WHERE code = $Code
But if he finds like 10 Items, i want to show only 1 by 1. All 10 must show in a Row, Random Order with a 5 seconds timer. The Problem is, i dont will show the same Item again and again. If the 10 Items are done, he must look again to database and start again
I already tried to do it with putting all in array but my skills are low :(
Thats my try...
$result = $db->query( 'SELECT * FROM ads WHERE zipcode = "'.$zipcode.'";');
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
$count = mysqli_num_rows($result);
for($i = 0; $i < $count; $i++) {
$random = rand(0, $count);
$count -= 1;
$result[] = $data[$random];
echo json_encode($data);
unset($data[$random]);
}

Is there a faster way than array_diff in PHP

I have a set of numbers from MySQL within the range 1000 0000 (8 digits) to 9 999 999 999 (10 digits). It's supposed to be consecutive, but there are missing numbers. I need to know which numbers are missing.
The range is huge. At first I was going to use PHP to do this:
//MySqli Select Query
$results = $mysqli->query("SELECT `OCLC Number` FROM `MARC Records by Number`");
$n_array = array();
while($row = $results->fetch_assoc()) {
$n_array[] = $row["OCLC Number"];
}
d($n_array);
foreach($n_array as $k => $val) {
print $val . " ";
}
/* 8 digits */
$counter = 10000000;
$master_array = array();
/* 10 digits */
while ($counter <= 9999999999 ) {
$master_array[] = $counter;
$counter++;
d($master_array);
}
d($master_array);
$missing_numbers_ar = array_diff ($master_array, $n_array);
d($missing_numbers_ar);
d() is a custom function akin to var_dump().
However, I just realized it would take tons of time for this to be done. At the 15 minute mark, $master_array is being populated with only 4000 numbers.
How can I do this in a quicker way? MySQL-only or MySQL-and-PHP solutions both welcome. If the optimal solution depends on how many numbers are missing, please let me know how so. Tq.
Your d() probably is the cause of slowness, please remove it, and make small changes in your code
while($row = $results->fetch_assoc()) {
$n_array[$row["OCLC Number"]] = 1;
}
and
$missing_numbers_ar = [];
while ($counter++ <= 9999999999 ) {
if (empty($n_array[$counter])) {
$missing_numbers_ar[] = $counter;
}
}
If the following is still slow I would be surprised. I also just noticed it is similar to #Hieu Vo's answer.
// Make sure the data is returned in order by adding
// an `ORDER BY ...` clause.
$results = $mysqli->query("SELECT `OCLC Number`
FROM `MARC Records by Number`
ORDER BY `OCLC Number`");
$n_array = array();
while($row = $results->fetch_assoc()) {
// Add the "OCLC Number" as a key to the array.
$n_array[$row["OCLC Number"]] = $row["OCLC Number"];
}
// assume the first array key is in fact correct
$i = key($n_array);
// get the last key, also assume it is not missing.
end($n_array);
$max = key($n_array);
// reset the array (should not be needed)
reset($n_array);
do {
if (! $n_array[$i]) {
echo 'Missing key:['.$i.']<br />';
// flush the data to the page as you go.
flush();
}
} while(++$i <= $max);

Get the ranking of the TOTAL values from PHP that is not stored in mysql

Good Day, I am working on some scoring system that would display all the scores by all of the users and would sum it up using PHP from MySQL. The result is working fine and the computation as well (the computation is done with php, not on MySQL). Now my problem is, how can I rank the total scores from highest to lowest.
Here's the code:
$sel_query="Select * from tbl_scores";
$result = mysql_query($sel_query);
while($row = mysql_fetch_array($result)) {
$crit_3 = $row["crit_3"];
$crit_3a = number_format($crit_3);
$crit2_3 = $row["crit2_3"];
$crit2_3a = number_format($crit2_3);
$crit3_3 = $row["crit3_3"];
$crit3_3a = number_format($crit3_3);
$user1 = ($crit_3) ;
$user2 = ($crit2_3);
$user3 = ($crit3_3);
$divide = ($user1 + $user2 + $user3);
$total = number_format($divide / 9 , 2, '.', '');
$average = number_format($total * 0.15 , 2, '.', '');
?>
Thanks in advance.
1.Please stop using (deprecated from php5.5 +removed from php7) mysql_*,use mysqli_* OR PDO.
2.Define an array variable outside of the loop, and inside in the loop assign total scores to that array.
3.Now you will get an array of scores and now you can use rshort() method to get data correctly.
So the code should be like below:-
$sel_query="Select * from tbl_scores";
$result = mysql_query($sel_query);
$scores_array = array();//create an array
while($row = mysql_fetch_array($result)) {
$crit_3 = $row["crit_3"];
$crit_3a = number_format($crit_3);
$crit2_3 = $row["crit2_3"];
$crit2_3a = number_format($crit2_3);
$crit3_3 = $row["crit3_3"];
$crit3_3a = number_format($crit3_3);
$user1 = ($crit_3) ;
$user2 = ($crit2_3);
$user3 = ($crit3_3);
$divide = ($user1 + $user2 + $user3);
$total = number_format($divide / 9 , 2, '.', '');
$average = number_format($total * 0.15 , 2, '.', '');
$scores_array[$row['user_name']] = $total; // assign total to the array and i assume that your table has one column name user_name for each user, change accordingly
}
rsort($scores_array);// sort the array in decending order of total scores
foreach ($scores_array as $key=>$value){ // iterate through array
echo $key.'has scored total score:-'.$value; //print the score along with username
}
?>
Note:- Please take the variable names in such a way that they will not produce any ambiguity.

PHP Loop - dealing with non-sequential iterations

I have the following code - it produces a series of queries that are sent to a database:
$a = 'q';
$aa = 1;
$r = "$a$aa";
$q = 54;
while($aa <= $q){
$query .= "SELECT COUNT(". $r .") as Responses FROM tresults;";
$aa = $aa + 1;
$r = "$a$aa";
}
The issue I have is simple, within the database, the number is not sequential.
I have fields that go from q1 to q13 but then goes q14a, q14b, q14c, q14d and q14e and then from q15 to q54.
I've looked at continue but that's more for skipping iterations and hasn't helped me.
I'm struggling to adapt the above code to handle this non-sequential situation. Any ideas and suggestions welcomed.
I have fields that go from q1 to q13 but then goes q14a, q14b, q14c, q14d and q14e and then from q15 to q54.
for($i=1; $i<=54; ++$i) {
if($i != 14) {
echo 'q' . $i . "<br>";
}
else {
for($j='a'; $j<='e'; ++$j) {
echo 'q14' . $j . "<br>";
}
}
}
If you don’t need to execute the statements in order of numbering, then you could also just skip one in the first loop if the counter is 14, and then have a second loop (not nested into the first one), that does the q14s afterwards.
You could get the columns from the table and test to see if they start with q (or use a preg_match):
$result = query("DESCRIBE tresults");
while($row = fetch($result)) {
if(strpos($row['Field'], 'q') === 0) {
$query .= "SELECT COUNT(". $r .") as Responses FROM tresults;";
}
}
Or build the columns array and use it:
$columns = array('q1', 'q2', 'q54'); //etc...
foreach($columns as $r) {
$query .= "SELECT COUNT(". $r .") as Responses FROM tresults;";
}

PHP loop to sort table

I'm querying a database for names that are numbered 1-26 alphabetically. I have the following code, but since HTML is structured tr then td, the table appears alphabetically by row as opposed to by column. How can I make it appear in order by column?
$query = mysql_query("SELECT name FROM people WHERE main=1 ORDER BY id");
$i = 0;
while($result = mysql_fetch_array($query)) {
$name = $result['name'];
if ($i % 5 == 0) echo "<tr>\n";
echo "<td width=\"150\">";
echo "".$name."<br />";
echo "</td>\n";
$i++;
if ($i % 5 == 0) echo "</tr>\n";
};
alpha beta charlie
delta echo foxtrot
vs.
alpha charlie echo
beta delta foxtrot
Also, I'm open to reworking the code if there's a more efficient way.
You could just access the output array in strides. Compute how many rows you need as the number of results divided by 5, and use the row count as the stride.
$ncols = 5;
$nrows = $nresults / $ncols + ($nresults % $ncols == 0 ? 0 : 1);
for ($i = 0; $i < $nrows; $i++)
{
// start row
for ($j = 0; $k < $ncols; $j++)
{
// print $results[$nrows * $j + $i]
}
// end row
}
You'll have to transfer your query results into an array $results first. Since you'll have to know the total number of results, this is sort of mandatory, though I'd be curious if anyone has a solution that can work while fetching the results.
Update: See Justin's answer for a cool solution that grows the output while fetching the query results line by line. Since it's currently being worked on, here's a summary (credits to Justin):
$nresults = mysql_num_rows($query);
$ncols = 5;
$nrows = (int) ceil($nresults / $ncols);
$i = 0; $cols = array_fill(0, $nrows, "");
while ($result = mysql_fetch_array($query))
$cols[$i++ % $nrows] .= "<td>$result['name']</td>";
echo "<tr>" . implode("</tr><tr>", $cols) . "</tr>";
Edit:
After the discussion in the comments between myself, Kerrek SB and the OP bswinnerton, the following code seems to be the most effective:
$columns = 3;
$rowcount = mysql_num_rows($query);
$rows = ceil($rowcount / $columns);
$rowdata = array_fill(0, $rows, "");
$ctr = 0;
while ($result = mysql_fetch_array($query))
$rowdata[$ctr++ % $rows] .= '<td>'.$result['name'].'</td>';
echo '<tr>'.implode('</tr><tr>',$rowdata).'</tr>';
This will create three columns, filled vertically (my original answer would create three rows). It also properly initializes the array (preventing PHP warnings), yields a correct row count for result counts that aren't divisible by the column count, and incorporates Kerrek's clever "calc-row-in-the-subscript" trick.
Original Post:
You could use arrays and implode() This way, you only have to make one pass through your results:
$row = 0;
$rows = 3;
$rowdata = array();
while($result = mysql_fetch_array($query))
{
if ($row >= $rows) $row = 0;
$rowdata[$row++] .= '<td>'.$result['name'].'</td>';
}
echo '<tr>'.implode('</tr><tr>',$rowdata).'</tr>';

Categories