Equal distribution of data into groups - php

I have a MySQL table with groups of people who have a number attached to their name. They are either a 1,2,3 or 4. I need to create groups where there is an even distribution of members in each group. In other words, I don't want all the 4's in one group, or all the 3's in another. I'd like it to be distributed evenly.
This is what I have so far. It echo's out the people and groups them by their level, but I'm not sure how to make groups of them that equally distributes their levels.
I have some more code and even though I've pissed off the community with my lack of experience, I was hoping someone might be able to tell me how to clean up the code. It works how I want it, but it feels ugly. Any help would be greatly appreciated.
<?php
include_once 'connect.php';
$level1 = array();
$level2 = array();
$level3 = array();
$level4 = array();
$sql1 = "SELECT * FROM table WHERE level = 1";
$stmt = $handler->prepare($sql1);
$stmt->execute();
$row = $stmt->fetchAll();
foreach($row as $rows)
{
$level1[] = $rows['name'];
}
$sql2 = "SELECT * FROM table WHERE level = 2";
$stmt = $handler->prepare($sql2);
$stmt->execute();
$row = $stmt->fetchAll();
foreach($row as $rows)
{
$level2[] = $rows['name'];
}
$sql3 = "SELECT * FROM table WHERE level = 3";
$stmt = $handler->prepare($sql3);
$stmt->execute();
$row = $stmt->fetchAll();
foreach($row as $rows)
{
$level3[] = $rows['name'];
}
$sql4 = "SELECT * FROM table WHERE level = 4";
$stmt = $handler->prepare($sql4);
$stmt->execute();
$row = $stmt->fetchAll();
foreach($row as $rows)
{
$level4[] = $rows['name'];
}
$sql5 = "SELECT * FROM table";
$stmt = $handler->prepare($sql5);
$stmt->execute();
$row = $stmt->fetchAll();
$result = count($row);
for($i=0; $i<=$result; $i++)
{
echo $level1[$i];
echo"<br>";
echo $level2[$i];
echo"<br>";
echo $level3[$i];
echo"<br>";
echo $level4[$i];
echo"<br>";
}
?>

Sounds like a simple round-robin style of distribution, it requires a loop range of 1 to 4, uses that as an index to an array that accumulates counts for each group. That may solve the problem you describe, if I have understood what you have asked.
If you are still in the theoretical side of this, draw a diagram of what you mean. A code example would mean the answer could address your issue rather than address it theoretically.

Related

My for loop only allows one post to be displayed, over and over again

/* To sort the id and limit the post by 40 */
$sql = "SELECT * FROM requests";
$result = $conn->query($sql);
$sqlall= "SELECT * FROM requests ";
$resultall = $conn->query($sqlall);
$i = 0;
if ($result->num_rows > 0) {
// Output data of each row
$idarray= array();
while($row = $result->fetch_assoc()) {
echo "<br>";
// Create an array to store the
// id of the blogs
array_push($idarray,$row['id']);
}
}
else {
echo "0 results";
}
?>
<?php
for($x = 1; $x < 40; $x++) {
// This is the loop to display all the stored blog posts
if(isset($x)) {
$query = mysqli_query(
$conn,"SELECT * FROM `requests`");
$res = mysqli_fetch_array($query);
$email1 = $res['email1'];
$msg1= $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
the output is 40 cards reading data from the first row in my database. can anyone help?
I'm using xampp.
This code is to show the loop, but if anyone wants the full code is here
You are storing all the IDs in the array $idarray, but then you don't really use them properly. You loop over them, but you just run SELECT * FROM requests` 40 more times, and always extract the same first row. You never use the ID to change the query.
But it really makes no sense to run lots of separate queries anyway. If you just want the first 40 rows then use MySQL's LIMIT keyword. It usually works best when combined with ORDER BY as well. Something like this:
$sql = "SELECT * FROM requests ORDER BY id LIMIT 40";
$result = $conn->query($sql);
while ($res = $result->fetch_assoc()) {
$email1 = $res['email1'];
$msg1 = $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
//example output, just for demo:
echo $email1." ".$msg1." ".$subject1." ".$name1." ".$id;
}
Documentation: https://dev.mysql.com/doc/refman/8.0/en/limit-optimization.html

Is there a way to access a row column via index and not name it?

The code I have is this
$sql = "SELECT * FROM user_buildings WHERE player_id = '$id'";
$result = mysqli_query($conn, $sql);
$amounts = array();
while ($row = $result->fetch_assoc()) {
$amounts[0] = $row['cursor_amount'];
$amounts[1] = $row['grandma_amount'];
}
However what I would like to be able to do is, instead of naming the column like I do here 'cursor_amount' and 'grandma_amount' is do the following:
$sql = "SELECT * FROM user_buildings WHERE player_id = '$id'";
$result = mysqli_query($conn, $sql);
$amounts = array();
while ($row = $result->fetch_assoc()) {
$amounts[0] = $row[0];
$amounts[1] = $row[1];
}
Although when I have tried to do this I've received the undefined offset error.
Any help would be greatly appreciated and yes I have tried looking for the answer already. I'm not exactly sure of the key terminology I need to make my searches more specific so if the answer for this does already exist I do apologise, feel free to post the link to the correct answer if that is the case instead of explaining it yourself.
Fetch the results with a different function:
$result->fetch_array(MYSQLI_NUM);

Fetch multiple records from php/mysql

I am fetching records as follows:
$aResult = array();
$sql = "SELECT notes FROM table WHERE user_id = '$user_id'";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)){
$aResult['query_result'] = $row;
}
This returns only the last record in the table. I need to return all records from the sql statement.
change you $aResult['query_result'] = $row; to $aResult['query_result'][] = $row;
You've override the result each time, so you just get one.
It seems your loop constantly overwrites the value and hence you will only ever seen the last row. I think you might see better results if you do something like:
while($row = mysqli_fetch_array($result))
{
$aResult[] = $row;
}
so that each new row gets appended to your array
Try with following code, currently You are initiating the values to the same array key :
$aResult = array();
$sql = "SELECT notes FROM table WHERE user_id = '$user_id'";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)){
$aResult['query_result'][] = $row;
}
for more Detail On Array

Sorting PHP arrays

I have three MySQL tables that I need to query for all of the rows. Upon getting all of the rows from each table, I need to create a multidimensional array whereby each index of that array contains only value from each of the tables. What I have right now works. But, something is telling me that there has got to be a better way of accomplishing this.
$tables = array('table_one', 'table_two', 'table_three');
$final = array();
foreach($tables as $table) {
$sql = "SELECT * FROM ".$table."";
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
$num = mysqli_num_rows($query);
$i = 0;
while($row = mysql_fetch_array($query)) {
$id[$i] = $row['user_id'];
$i++;
}
for($i=0;$i<$num;$i++) {
if(!is_array($final[$i])) {
$final[$i] = array($id[$i]);
} else {
array_push($final[$i], $id[$i]);
}
}
}
The end results is something that looks like this
$final = array(array('table_one_row_one_val', 'table_two_row_one_val', 'table_three_row_one_val'),
array('table_one_row_two_val', 'table_two_row_two_val', 'table_three_row_two_val'),
array('table_one_row_three_val', 'table_two_row_three_val', 'table_three_row_three_val')
);
I get the gut felling that this could be done much more effectively, but I'm not sure how.
Thanks,
Lance
You can make your code simpler if you make your query more explicit in selecting the columns you want in the order you want them. So for example:
$sql = 'SELECT table_one.user_id as u1, table_two.user_id as u2, table_three.user_id as u3 FROM ' . implode(',', $tables);
Then each row of your result set will have the columns in the proper order making the construction of your arrays less involved. For example:
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
while($row = mysql_fetch_array($query)) {
$final[] = array($row['u1'], $row['u2'], $row['u3']);
}
There may be issues with the order and relationships of the data in these arrays (especially if all 3 tables don't have the same number of rows), but working just off the information above, this is another way you could approach it. Something to think about anyway.
Try this:
$sql = "SELECT 'user_id' FROM ".$table;
What about:
$tables = array('table_one', 'table_two', 'table_three');
$final = array();
foreach($tables as $tableIndex => $table) {
$sql = "SELECT user_id FROM ".$table;
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
$i = 0;
while($row = mysql_fetch_array($query)) {
$final[$tableIndex][$i] = $row['user_id'];
$i++;
}
}
It is always better selecting only the columns you will use. SELECT * is not a good SQL practice.

sql query working in phpmyadmin but not via mysql_query in php

Well first of all I am French so I hope my question will be understandable ;-)
I know some people have already experienced problems with queries in php that worked in phpmyadmin. The thing is that each time (or so) these people had "echo" their queries and copy/paste in phpmyadmin, but as php does not always display spaces it was always the problem.
Actually my problem is different :
if I use the query
$sql = "SELECT * FROM jos_dtregister_invoice_sent";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
it returns all the rows in both phpmyadmin and my php code, but if I want to look in a different table (with same structure), it just works in phpmyadmin and not via my php code (only one row instead of all of them)
Here is the query not working:
$sql = "SELECT * FROM jos_dtregister_receipt_sent";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
Perhaps the answer is very simple but I admit this is kind of tricky for me...
Many thanks in advance!
Here is my complete code :
function sendReceipt($row) {
$to = getUserInformation($row,10);
$from = getEventAdminEmailFromEmail($row);
$subject = getEventTitle($row)." - Invoice #".$row["confirmNum"];
$message = $row["userFirstName"]." ".$row["userLastName"]." \n\n".getMessageToSendUser($row);
$headers = "From: ".$from."\r\n";
$sql1 = "SELECT * FROM `jos_dtregister_invoice_sent`";
$query1 = mysql_query($sql1);
echo 'Fetched rows number: '.mysql_num_rows($query1)."<br />";
while($row1 = mysql_fetch_array($query1)) {
echo "Invoice Sent: ".$row1["sent"]."<br />";
}
$sql2 = "SELECT * FROM `jos_dtregister_receipt_sent`";
$query2 = mysql_query($sql2);
echo 'Fetched rows number: '.mysql_num_rows($query2)."<br />";
while($row2 = mysql_fetch_array($query2)) {
echo "Receipt Sent: ".$row2["sent"]."<br />";
}
}
mysql_fetch_array() fetches only a row.The name suggests that it fetches a result row as an array
$sql = "SELECT * FROM jos_dtregister_receipt_sent";
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($query);
Try to execute this. The mysql_error() line will spit out what exactly went wrong when trying to execute the SQL. Post it back here and we can help you a little more.
$sql = "SELECT * FROM jos_dtregister_receipt_sent";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
// $row will have your data
}
You need to loop over the results with mysql_fetch_array().
while ($result = mysql_fetch_array($query)) {
print_r($result);
}
Or if you want all your results in one big array ($results):
$results = array();
while ($row = mysql_fetch_array($query)) {
$results[] = $row;
}

Categories