How to set the data can do the increment? - php

May I know how to set the $n variable once I insert the data, $n will plus 1 to previous my insert number?
For similar example what I've tried:
$n = "AB000";
for ($n = 0; $n <= 0; $n++)
{
$query = "INSERT INTO [tablename] (user, country, batch_number) VALUES ('$user', '$country', $n)";
// execute query
}
I want the expect result can like below the table, every time I do the insert function, the batch number can auto add 1:
user | country| batch_number
John USA AB009
Lawn Germany AB010
Shawn England AB011
Hope someone can guide me how to solve this problem. Thanks.

What you think about this script.
This is a different approch to acheive
online fiddle: http://sandbox.onlinephpfunctions.com/code/569b6458b3080b4fa5c5f3d96bd0839334b02e8b
<?php
$n = "A00";
$user = "userName";
$country = "country";
for ($i=0; $i < 10; $i++) {
$batch = "";
$batch = $n."".$i;
echo "INSERT INTO tablename (user, country, batch_number) VALUE "."('".$user."', '".$country."', $batch)";
echo "\n";
}
?>

You could create a get_batch_number function which needs:
$number (in your case $n)
$prefix (in your case 'AB')
$pad_length (in your case 3)
for ($n = 0; $n <= $max_n; $n++) {
$batch_number = get_batch_number($n, 'AB', 3);
// ...
}
function get_batch_number($number, $prefix, $pad_length) {
return $prefix . str_pad($number, $pad_length, '0', STR_PAD_LEFT);
}

Related

Expanding Round-robin tournament 1v1 to a 1v1v1v1

I am trying to expand and improve the round-robin algorithm from 1v1 group to a 1v1v1v1 group(something like free for all). I've made the function itself to do the schedule, but when I tried to expand it, some teams repetead. For example, I have 16 teams and I want to have 5 rounds, team 1 appears 7 times in 5 rounds and team2 appears 3 times in 5 rounds. I need them to appear 5 times at most.I really can't understand how I can do it. Any advice is welcomed and links.
function make_schedule(array $teams, int $rounds = null, bool $shuffle = true, int $seed = null): array
{
$teamCount = count($teams);
if($teamCount < 4) {
return [];
}
//Account for odd number of teams by adding a bye
if($teamCount % 2 === 1) {
array_push($teams, null);
$teamCount += 1;
}
if($shuffle) {
//Seed shuffle with random_int for better randomness if seed is null
srand($seed ?? random_int(PHP_INT_MIN, PHP_INT_MAX));
shuffle($teams);
} elseif(!is_null($seed)) {
//Generate friendly notice that seed is set but shuffle is set to false
trigger_error('Seed parameter has no effect when shuffle parameter is set to false');
}
$quadTeamCount = $teamCount / 4;
if($rounds === null) {
$rounds = $teamCount - 1;
}
$schedule = [];
for($round = 1; $round <= $rounds; $round += 1) {
$matchupPrev = null;
foreach($teams as $key => $team) {
if($key >= $quadTeamCount ) {
break;
}
$keyCount = $key + $quadTeamCount;
$keyCount2 = $key + $quadTeamCount + 1;
$keyCount3 = $key + $quadTeamCount + 2;
$team1 = $team;
$team2 = $teams[$keyCount];
$team3 = $teams[$keyCount2];
$team4 = $teams[$keyCount3];
//echo "<pre>Round #{$round}: {$team1} - {$team2} - {$team3} - {$team4} == KeyCount: {$keyCount} == KeyCount2: {$keyCount2} == KeyCount3: {$keyCount3}</pre>";
//Home-away swapping
$matchup = $round % 2 === 0 ? [$team1, $team2, $team3, $team4 ] : [$team2, $team1, $team4, $team3];
$schedule[$round][] = $matchup ;
}
rotate($teams);
}
return $schedule;
}
Rotate function:
function rotate(array &$items)
{
$itemCount = count($items);
if($itemCount < 3) {
return;
}
$lastIndex = $itemCount - 1;
/**
* Though not technically part of the round-robin algorithm, odd-even
* factor differentiation included to have intuitive behavior for arrays
* with an odd number of elements
*/
$factor = (int) ($itemCount % 2 === 0 ? $itemCount / 2 : ($itemCount / 2) + 1);
$topRightIndex = $factor - 1;
$topRightItem = $items[$topRightIndex];
$bottomLeftIndex = $factor;
$bottomLeftItem = $items[$bottomLeftIndex];
for($i = $topRightIndex; $i > 0; $i -= 1) {
$items[$i] = $items[$i - 1];
}
for($i = $bottomLeftIndex; $i < $lastIndex; $i += 1) {
$items[$i] = $items[$i + 1];
}
$items[1] = $bottomLeftItem;
$items[$lastIndex] = $topRightItem;
}
For example:
If I set rounds to 5, every team play 5 matches.
Array example Screenshot
Dealing with the 5th round:
Well, after I thought for a bit, maybe there isn't a way for them to play without repeatence, but if it is lowered to minumum, like every team should play 5 times only - this means once a round. That's what I meant. And what I meant under 'they repeat' is that there are like: 16 teams, 5 rounds and some teams are going like 7 times for all these rounds and other teams are going 3 times for these 5 rounds. I want to avoid this and to make every team play 5 rounds at most.
Your foreach() with the selection of the other 3 teams is wrong. One of them have to make steps with a multiple of 4. If you don't, you will select the teams at the beginning more than one and don't select the teams at the end of the array at all. This will result in wrong team matchups like this (teams are letters here):
abcd
bcde
cdef
defg
And then your break; hits.
Instead it should look something like this:
for ($i=0; $i<4; $i++) {
$matchup = array();
for ($j=0; $j<4; $j++) {
$matchup[] = $teams[4*$i+$j];
}
$schedule[$round][] = $matchup ;
}
This way you get the following pairing (again, using letters as teams):
abcd
efgh
ijkl
mnop
This algorithm will split the team list in four groups:
abcd|efgh|ijkl|mnop
Keep in mind that depending on the shuffling of the $teams array for the next round you might get the same opponent twice.
adei|klnf|gjmc|pobh
Here the teams ad, kl and op will face again.

Grouping N person randomly but evenly? (Name & Gender)

So, I tried to create an algorithm(?) to assign a person to a classroom. The requirement for each class is :
Have at least 30 people and maximum of 45
The person name will not be "Homogen" (e.g: class 1 - 3 has all person name started with the letter "A", while class 4-5 the letter "B" etc.)
The gender is also evenly distributed
If the class is full, the remaining person will be moved to waiting list
My data has the column Unique ID, Name, and Gender. I'm still new to this kind of stuff (Algorithm?) so I don't even know where to start. Is it even possible? Where do I start? I am using PHP and my data is in MySQL Database
Step 1
You need to get data from DateBase (all people)
$host = '***';
$user = '***'';
$password = '***'';
$database = '***'';
$link = mysqli_connect($host, $user, $password, $database) or die("Error" . mysqli_error($link));
$query = "SELECT * FROM people";
$people = mysqli_query($link, $query) or die("Error" . mysqli_error($link));
mysqli_close($link);
Step 2
Conver mysql_result to Array and shuffle it.
$people = [];
foreach ($result as $person) {
$people[] = $person;
}
shuffle($people);
Step 3
There is algorithm:
$count = count($people);
// Classes
$classes = [];
const MIN_SIZE = 30;
const MAX_SIZE = 45;
$maxSizeClass= $count / MIN_SIZE;
$minSizeClass= $count / MAX_SIZE;
$countClasses = max(ceil($minSizeClass), floor($maxSizeClass));
$currentCountClass = $count / $countClasses;
$tmpClass = [];
foreach ($people as $person) {
if (count($tmpClass) < $currentCountClass) {
$tmpClass[] = $person;
} else {
$classes[] = $tmpClass;
$tmpClass = [];
}
}
if (count($tmpClass) >= MIN_SIZE) {
$classes[] = $tmpClass;
$tmpClass = [];
}
foreach ($tmpClass as $index => $person) {
foreach ($classes as &$class) {
if (count($class) < MAX_SIZE) {
$class[] = $person;
// be careful, PHP7 is OK
unset($tmpClass[$index]);
continue 2;
}
}
}
// persons awaiting distribution
$waitingQueue = $tmpClass;
Step 4
Result is:
$waitingQueue - persons awaiting distribution
$classes - classes with persons
$letters = array('a','b',....,'y','z');
foreach($letters as $letter){
$sql['male'] = "SELECT * FROM people_table WHERE person_name LIKE '".$letter."%' AND person_gender = 'male' ORDER BY person_name";
$sql['female'] = "SELECT * FROM people_table WHERE person_name LIKE '".$letter."%' AND person_gender = 'female' ORDER BY person_name";
foreach($sql as $key => $query){
$results[$key] = $connection->query($query);
for($i = 0; $i < $results[$key]->num_rows; $i++){
$people[$letter][$key][] = results->fetch_array(MYSQLI_ASSOC);
}
}
}
Here we have the lists of people listed by gender by letter... Now we can loop it and insert a man and a woman by pairs. If the count(); of the list of pairs is lesser than 30, people wait more. If bigger than 44 (because in pair isn't possible to have 45 people, if I don't missunderstand the question, of course) then save this 44 in a class array $class[$letter] which you can see all classes by each letter. To know about how many classes you have in total, you can use count($class); or if you would like to know how many classes of a specific letter you can do count($class[$letter]);.
You can redo other foreach in the $letters array or just put the loop inside the foreachabove to create the array of classes.
Inside the foreach($letters as $letter){} at the final:
if( !(count($people[$letter][$key]) < 15 OR count($people[$letter][$key]) < 15) ){
$she = count($people[$letter]['female'];
$he = count($people[$letter]['male'];
if($she < $he){
for($i = 0; $i < 2*count($she); $i++){
$class[$letter][$i] = $people[$letter]['female'][$i];
$class[$letter][$i+1] = $people[$letter]['male'][$i];
$i++;//Important to avoid replace values!
}
} else {
for($i = 0; $i < 2*count($he); $i++){
$class[$letter][$i] = $people[$letter]['female'][$i];
$class[$letter][$i+1] = $people[$letter]['male'][$i];
$i++;//Important to avoid replace values!
}
}
A false boolean in the bigger if means cannot create a class with this letter gender evenly distributed. You can loop again to make each class in an entry of an array.

Filter negative and positive values out of one variable in PHP

I have a variable in PHP where values from a database are inserted. It’s about money. I need to summarize all negative and positives values separately.
Example:
February, I have:
+ 10
− 10
+100
− 50
− 15
+ 70
+ 80
—
Credits added: 260 Euro
Credits paid: −75 Euro
The variable is named $amound in my PHP file. I really have no clue how to do that.
In Excel, this would be as follows: =SUMMEWENN(E1:E48;"<0")
But here I only have a variable, not fields.
Heres some Code:
$reportdata["tableheadings"] = array("Transaktions-ID","Kunde","Datum","Beschreibung","Betrag");
if ($startdate && $enddate) {
$query = "SELECT tblcredit.*,tblclients.firstname,tblclients.lastname FROM tblcredit INNER JOIN tblclients ON tblclients.id=tblcredit.clientid WHERE tblcredit.date BETWEEN '".db_make_safe_human_date($startdate)."' AND '".db_make_safe_human_date($enddate)."'";
$result = full_query($query);
while ($data = mysql_fetch_array($result)) {
$id = $data["id"];
$userid = $data["clientid"];
$clientname = $data["firstname"]." ".$data["lastname"];
$date = fromMySQLDate($data["date"]);
$description = $data["description"];
$amount = $data["amount"];
$currency = getCurrency($userid);
$amount = formatCurrency($amount);
$overallamount += $amount;
// $overallamountout -= $amount;
// $overallamountin += $overallamount > 0;
$reportdata["tablevalues"][] = array($id,''.$clientname.'',$date,nl2br($description),$amount);
}
Indeed, this is very simple (I assume that all of your variables are strings, e.g. coming from a text file, but even if not it will work):
$var1 = '+80';
$var2 = '-30';
$result = (int)$var1 + (int)$var2;
var_dump($result);
Will result in: "int(50)" => Working fine.
You can do it in the DB
SELECT SUM(numbers) AS sum1 FROM pepa WHERE numbers > 0;
SELECT SUM(numbers) AS sum2 FROM pepa WHERE numbers < 0;
Okay,
its done.
Heres the Code which was used:
$summeGesamt = 0;
$summeEingezahlt = 0;
$summeAusgezahlt = 0;
$summeGesamt = $summeGesamt + $data["amount"];
if ( $data["amount"] >= 0) {
$summeEingezahlt += $data["amount"];
} else {
$summeAusgezahlt += $data["amount"];
}

Generating a new unique alpha numeric string,

I need to generate an alpha numeric string and compare with database values but if the value is present in database then we should generate a different numeric string and again it should be compared with database values....
<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$Emp_Id = "";
for($i = 0; $i < 6; $i++) {
$Emp_Id .= $character_array[rand(0, (count($character_array) - 1))];} ?>
which is working fine by creating an alpha numeric code,But as i have mentioned above i need to compare it with database values.
$chkEmp_Id=mysql_fetch_array(mysql_query("SELECT Emp_Id FROM talent_users WHERE Emp_Id='{$Emp_Id}' "));
after comparing with database values if the value is present then it should generate a different "Emp_Id",every time generated employee id should be compared with database values...hope u guys got it na?please help me to fix this...
$pool = array_merge (range ('a', 'z'), range(0, 9));
do
{
$hash = "";
for ($i = 0; $i < $lengthOfHash; ++$i)
{
$hash .= $pool[array_rand ($pool)];
}
while ( mysql_result (mysql_query ('SELECT COUNT(1) FROM talent_users WHERE Emp_Id = ' . $hash), 0) > 0);
But this is a big bottleneck when the table size grows. Since the hash is alpha-numeric, why can't the hash just begin with the userId?
//hash = <a number> + <a letter> + <alpha-numeric chars>
$hash = $userId . generateHash();
Just make sure that the generateHash() function doesn't start with a number, as stated in the comment.
It would then be something like:
$hash = $userId;
$letters = range ('a', 'z');
$pool = array_merge ($letters, range (0, 9));
for ($i = 0; $i < $lengthOfHash; ++$i)
{
$chooseFrom = $pool;
if ( ! $i )
$chooseFrom = $letters;
$hash .= $chooseFrom[array_rand($chooseFrom)];
}

PHP variable additions

Hey does anyone know a reason why this is not working? its not calculating any of the additions and just entering 0 into the database. Any help would be great, thank you!.
$member_id = //users member id in database//
$track = //the track results being updated//
$engine = //the engine id from the members table in database//
$engine_points_system = array();
$engine_points_system["qualpos1"] = 30;
$engine_points_system["qualpos2"] = 20;
$engine_points_system["qualpos3"] = 18;
$engine_points_system["qualpos4"] = 17;
$engine_points_system["qualpos5"] = 16;
$enginepoints = 0;
$qualifyingpoints = 0;
$results_query = mysql_query("SELECT pos_1, pos_2, pos_3, pos_4, pos_5
from engine_qualifying_results WHERE track_id = '$track'")
or die ("Failed to update" . mysql_error());
$row = mysql_fetch_array($results_query);
$enginequalifying = array();
for ($i = 1; $i <= 5; $i++) {
$enginequalifying["pos$i"] = $row['pos_$i'];
}
for($i = 1; $i <=5; $i++) {
if($engine == $enginequalifying["pos$i"]){
$enginepoints += $engine_points_system["qualpos$i"];
$qualifyingpoints += $engine_points_system["qualpos$i"];
}
}
$results_query = mysql_query("INSERT INTO member_results (member_id, engine_points)
VALUES ('$member_id', $enginepoints')")
or die ("Failed to update" . mysql_error());
$enginequalifying["pos$i"] = $row['pos_$i'];
In this line you have 'pos_$i'. This is the literal string 'pos_$i'. You should use "pos_$i" instead.
$enginequalifying["pos$i"] = $row["pos_$i"];
UPDATE:
In your code $enginequalifying is redundant, and not needed. You can just use $row in its place.
for($i = 1; $i <=5; $i++){
if($engine == $row["pos_$i"]){
$enginepoints += $engine_points_system["qualpos$i"];
$qualifyingpoints += $engine_points_system["qualpos$i"];
}
}
Also, as #ax. points out, you have an extra ' (or a missing ') in your INSERT.
$results_query = mysql_query("INSERT INTO member_results (member_id, engine_points)
VALUES ('$member_id', '$enginepoints')")
or die ("Failed to update" . mysql_error());
Look at this code:
<?php
$i = 5;
print "i is $i";
print "\n";
print 'i is $i';
?>
You'd expect it to print:
i is 5
i is 5
But instead, it will print:
i is 5
i is $i
This happens because when the string is wrapped in single quotes, $i is not evaluated. It is just the string $i.
To fix the code, try replacing this line:
$enginequalifying["pos$i"] = $row['pos_$i'];
With this line:
$enginequalifying["pos$i"] = $row["pos_$i"];
Quotes make a difference.
And by the way, ESCAPE YOUR SQL!!!. Please?
Not an answer, but too ugly to put into a comment: You could bypass the entire loop to build the enginequalifying array by simply doing:
SELECT pos_1 AS pos1, pos_2 AS pos2, etc...
for your query, then simply having:
$enginequalifying = mysql_fetch_assoc($result);
It's a waste of CPU cycles to have PHP fetch/rename database fields for you when a simple as alias in the original query string can accomplish the exact same thing.
And incidentally, this will also remove the string-quoting error you've got that Rocket pointed out in his answer.
I dont think it is possible to say without knowing what you have in your database.
But I can tell you that you have a syntax error in the last SQL query ($enginepoints ends with a quote).

Categories