Question
I have to award my members with some bonuses on completion of certain tasks.If they have achieved task1, new the task will be task2
If they have achieved task2, new the task will be task3
If they have achieved task3, new the task will be task4
If they have achieved task4, new the task will be task5
Database
while($row = mysql_fetch_array($sql))
{
$offername[] = $row['name'];
$offertask1[] = $row['task1'];
$offertask2[] = $row['task2'];
$offertask3[] = $row['task3'];
$offertask4[] = $row['task4'];
$offertask5[] = $row['task5'];
$offerprize[] = $row['prize'];
$offercurrent[] = $row['current'];
$offerpercent[] = $row['percent'];
$offertask[] = $row['task'];
}
Values:
$offername[] = (offer1, offer2, offer3 ,offerXX)
$offertask1[] = (100,150,200 ,taskxx)
$offertask2[] = (100,150,200 ,taskxx)
$offertask3[] = (100,150,200 ,taskxx)
$offertask4[] = (100,150,200 ,taskxx)
$offertask5[] = (100,150,200 ,taskxx)
$offerprize[] = (5000,2222,3333 ,taskxx)
$offertask= this will replace it value with $offertask1[]
,$offertask2[] to $offertask5[] , depending upon the condition
My Code
for ($i=0;$i<=count($offername);$i++) {
// Check for existing bonuses first. // Code omitted
//#### If it's the first bonus ########
if ($member['count'] == 0 ) {
if ($offerprize[$i] != 0) {
$offertask = array_replace($offertask, $offertask1);
$per = $offercurrent[$i]/$offertask[$i] * 100;
$offerpercent[$i] == round($per);
}
}
//### If he has claimed one bonus and this is the second bonus #####
if ($member['count'] == 1 ) {
if ($offercurrent[$i] >= $offertask1[$i] AND $offercurrent[$i] < $offertask2[$i]) {
if ($offerprize[$i] != 0) {
$offertask = array_replace($offertask, $offertask2);
$per = $offercurrent[$i]/$offertask[$i] * 100;
$offerpercent[$i] == round($per);
}
}
}
}
I have already claimed the first bonus for offer1 == offername[0]. I have tested for $offercurrent[0]. It does not work for ($member['count'] == 1) and so on.
Problem
All the values remain same for ($member['count'] == 0 ) and do not change with the count.
Related
Hi i am iterating over Episodes getting array of authors and inside this loop i want to gather information about each author. But there is problem, i just need the information about each author once.
This is my approatch, but wrong. and the code i am trying to make. Please help. I tried also in_array, and array_filter but without success.
$presentUsers = [];
$pUi = 0;
if ($isAuthor == true){
if ($project->getType() == 1) {
$episodes = $project->getComic()->getComicEpisodes();
foreach ($episodes as $comicEpisode) {
foreach ($comicEpisode->getProject()->getAccount() as $author) {
if ($author->getUser()->getId() == $this->getUser()->getId()) {
$comicEpisode->setIsMine(true);
$comicEpisode->setRevenue($author->getRevenue());
$comicEpisode->setIncome($author->getIncome());
}
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
if (!in_array($presentUsers, ['Id'=>$author->getUser()->getId()]))
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
}
}
}
}else{
die('You are not the author of this project.');
}
Okay i done it like this
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
$found = 0;
foreach ($presentUsers as $presentUser){
if ($presentUser['Id'] == $author->getUser()->getId()){
$found = 1;
break;
}
}
if ($found != 1)
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
this is my first post and im really new to php world, Sorry if i use wrong words or terms to describe my problem.
I have a script that was written in php for telegram, and i have two commands that is almost the same.
with this one it is possible to add to multiple groups using this separator ","
/madd
groupid, groupid
this one it is not possible to do
/wadd
groupid
I want to be able to use the second command with a separator between the group ids
I can see in the code how it is written to be able to do that in /madd but I cant figure out how to implement this in /wadd
I will put here the two scripts for the commands, would appreciate any help <3
Thanks.
This is the one with the separator
if(strpos($text,"/madd") === 0){
$e = explode("\n",$text);
if(!isset($e[1]) || !isset($e[2])) exit($bot->sendMessage($user['id'],"/madd\ntelegram_username or ID\ngroup, ids\nmax_posts per day (default 1)\nnumber of reposts (default 0)\n\nAdds new telegram username to the manual autodrop users list.\n\nReplace group_id with * to add to all groups"));
$group = $e[2]; $username = strtolower(ltrim($e[1],"#"));
$addto = [];
if($group == "*"){
$addto = $groups;
}else{
$ex = explode(",",$group);
foreach($ex AS $id){
$id = trim($id);
if(isset($groups[$id])){
$addto[$id] = $groups[$id];
}
}
}
$add = mysqli_fetch_assoc($conn->query("SELECT * FROM utenti WHERE username LIKE '%".mysqli_real_escape_string($conn,$username)."%'"));
if(!isset($add['id'])){
$add = mysqli_fetch_assoc($conn->query("SELECT * FROM utenti WHERE id = ".mysqli_real_escape_string($conn,$username)));
}
if(!isset($add['id'])){ exit($bot->sendMessage($user['id'],"š User $username not found! They need to start the bot, or send a simple message in one of the groups.")); }
$result = "ā <b>Selected User:</b> <a href='tg://user?id=".$add['id']."'>".$add['username']." (".$add['id'].")</a>";
$manual = [
'max_posts' => $e[3] ?? 1,
'reposts' => $e[4] ?? 0,
'groups' => []
];
foreach($addto AS $id => $r){
$manual['groups'][] = $r['group_id'];
}
$conn->query("UPDATE utenti SET manual = '".mysqli_real_escape_string($conn,json_encode($manual,true))."' WHERE id = ".$add['id']);
$bot->sendMessage($user['id'],$result."\n\n".json_encode($manual,JSON_PRETTY_PRINT));
exit();
}
and this is without the separator
if(strpos($text,"/wadd") === 0){
$e = explode("\n",$text);
if(!isset($e[1]) || !isset($e[2])) exit($bot->sendMessage($user['id'],"/wadd\ngroup_id\ntelegram_username or ID\nmax_posts per day (default 5)\nnumber of reposts (default 0)\n\nAdds new telegram username to the whitelisted users list.\n\nReplace group_id with * to add to all groups"));
$group = $e[1]; $username = strtolower(ltrim($e[2],"#"));
if($group != "*" && !isset($groups[$group])) exit($bot->sendMessage($user['id'],"š„ <b>Group $group</b> not whitelisted."));
$add = mysqli_fetch_assoc($conn->query("SELECT * FROM utenti WHERE username LIKE '%".mysqli_real_escape_string($conn,$username)."%'"));
if(!isset($add['id'])){
$add = mysqli_fetch_assoc($conn->query("SELECT * FROM utenti WHERE id = ".mysqli_real_escape_string($conn,$username)));
}
if(!isset($add['id'])){ exit($bot->sendMessage($user['id'],"š User $username not found! They need to start the bot, or send a simple message in one of the groups.")); }
$result = "ā <b>Selected User:</b> <a href='tg://user?id=".$add['id']."'>".$add['username']." (".$add['id'].")</a>";
$premiums = json_decode($add['premiums'],true);
if(!is_array($premiums)) $premiums = [];
$groups_to_update = []; if($group == "*"){ foreach($groups AS $group => $data){ $groups_to_update[] = $group; } }else{ $groups_to_update[] = "-".abs($group); }
$max_posts = $e[3] ?? 5; $reposts = $e[4] ?? 0;
foreach($groups_to_update AS $group_id){
if(isset($premiums[$group_id])){
if($premiums[$group_id]['max_posts'] == $max_posts && $premiums[$group_id]['reposts'] == $reposts){
$result.="\n\nš <i>No changes for group</i> <code>$group_id</code>";
}else{
$result.="\n\nā»ļø <b>Updated</b> for group <code>$group_id</code>\nMax. Posts: $max_posts | Reposts: $reposts";
$premiums[$group_id] = ['max_posts' => $max_posts,'reposts' => $reposts];
}
}else{
$result.="\n\nā <b>Added</b> for group <code>$group_id</code>\nMax. Posts: $max_posts | Reposts: $reposts";
$premiums[$group_id] = ['max_posts' => $max_posts,'reposts' => $reposts];
}
}
$conn->query("UPDATE utenti SET premiums = '".mysqli_real_escape_string($conn,json_encode($premiums,true))."' WHERE id = ".$add['id']);
$bot->sendMessage($user['id'],$result);
exit();
}
I am inserting a serial number in a table that is increment by one always but when multiple request is coming in same time it is inserting same serial number for different requests.I am using mysql database.
I know i am fetching the max serial number too early in the code and if request is come in same time so it will fetching same serial number for both. is it good idea to update serial number after all work done. what if inserting a record for new request and updating the serial number for previous one is in same time.
public function add(){
$session = $this->request->session();
$company_id = $session->read('Admin.company_id');
$emp_id = $session->read('Admin.emp_id');
$user_email_id = $session->read('Admin.email_id');
$employee_name = $session->read('Admin.employee_name');
$conn = ConnectionManager::get('default');
if ($this->request->is('post')) {
try{
$conn->begin();
$department = $this->request->data['department'];
$data = $this->request->data;
if(!array_key_exists('is_requisition_for_contractor', $data)){
$is_requisition_for_contractor = 0;
} else {
$is_requisition_for_contractor = $data['is_requisition_for_contractor'];
}
if(!array_key_exists('is_requisition_for_employee', $data)){
$is_requisition_for_employee = 0;
} else {
$is_requisition_for_employee = $data['is_requisition_for_employee'];
}
if(!array_key_exists('is_boulder_requisition', $data)){
$is_requisition_for_boulder = 0;
} else {
if($data['is_boulder_requisition'] == ''){
$is_requisition_for_boulder = 0;
} else {
$is_requisition_for_boulder = $data['is_boulder_requisition'];
}
}
$is_requisition_for_plant = 0;
if(!array_key_exists('is_plant_requisition', $data)){
$is_requisition_for_plant = 0;
} else {
if($data['is_plant_requisition'] == ''){
$is_requisition_for_plant = 0;
} else {
$is_requisition_for_plant = $data['is_plant_requisition'];
}
}
if(array_key_exists("files",$this->request->data)) {
$files = $this->request->data['files'];
if (count($files)) {
$files_uploading_response = $this->uploadMultipleFiles($files, 'files/requisitions/');
}
}
$last_material_insert_id = '';
if($this->request->data('material_id')[0] == ''){
if($this->request->data('department') == 1){
$type = 1;
} elseif($this->request->data('department') == 3){
$type = 3;
} elseif($this->request->data('department') == 2){
$type = 2;
}
if($this->request->data('department') == 1 || $this->request->data('department') == 3){
$conn->execute("INSERT INTO material (material_name, material_type_id, company_id, status, is_approved_by_admin) VALUES (?,?,?,?,?)",[$this->request->data('material_name'), $type, $company_id, 1,0]);
$last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
} elseif($this->request->data('department') == 2) {
//todo for unapproved material
$conn->execute("INSERT INTO material (part_no, material_type_id, company_id, status, is_approved_by_admin,unique_category_id) VALUES (?,?,?,?,?,?)",[$this->request->data('part_no')[0], $type, $company_id, 1,0,$this->request->data('unique_category_id')[0]]);
$last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
}
}
// here i am fatching max serial number from table
$requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc');
$Requisition = TableRegistry::get('requisition');
$requisition = $Requisition->newEntity();
$requisition->registered_on = $this->request->data['date'];
$requisition->department_id = $this->request->data('department');
$requisition->site_id = $this->request->data('site_id');
$requisition->issues_to_id = $this->request->data['prepared_by_id'];
$requisition->prepared_by_id = $this->request->data['prepared_by_id'];
$requisition->approved_by_id = $this->request->data['hod_id'];
$requisition->hod_id = $this->request->data['hod_id'];
$requisition->is_diesel_requisition_for_employee = $is_requisition_for_employee;
$requisition->is_diesel_requisition_for_contractor = $is_requisition_for_contractor;
$requisition->is_requisition_for_boulder = $is_requisition_for_boulder;
$requisition->is_requisition_for_plant = $is_requisition_for_plant;
if(array_key_exists('for_tanker_stock', $this->request->data)) {
$requisition->for_tanker_stock = 1;
}
if($last_material_insert_id != ''){
$requisition->is_material_approved_by_admin = 0;
}
$requisition->status = 1;
$site_id = $this->request->data['site_id'];
$requisition->requisition_no = $requistion_number[0]['requisition_no'] + 1;
$requistionnumber = $requistion_number[0]['requisition_no'] + 1;
$saveRequsition = $Requisition->save($requisition);
$conn->commit();
}
I am expecting the output different serial number for each request.any optimise way to do this. thanks in advance.
Ok, how about the same strategy, setting the $requisition_number after the row has been inserted (see my other answer), but using a single query with the same method you use to determine the new requisition id:
$conn->execute("UPDATE requisition
SET requisition_no = (SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?) + 1",
[$this->request->data('site_id')]);
The idea here is that a single query will be executed in one step, without another, similar query, being able to interfere.
What you currently do is to first get the old requistion number like this:
$requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no
FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc');
and then increase it before you save and commit.
My suggestion is to not set the $requistion_number at all before you save and commit the requisition row, but to determine the $requistion_number afterwards.
You now wonder how?
Well, you need to count the total number of requisition rows in the table for the site the requisition is for, and add one, like this:
$last_requisition_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
$site_id = $this->request->data('site_id');
$requisition_number = $conn->execute("SELECT COUNT(*) AS requisitionsCount
FROM requisition
WHERE <primary_key> <= ? AND
site_id = ?",
[$last_requisition_id, $site_id]) + 1;
$conn->execute("UPDATE requisition
SET requisition_no = ?
WHERE <primary_key> <= ?",
[$requisition_number, $last_requisition_id]);
I know this code is not working. The $requisition_number will probably contain an array with the requisitionsCount as a value, but you can correct that.
Because you're using data that is already present in the database table you don't run the risk that two rows will get the same $requisition_number. The assumption here is that requisitions are never deleted.
I'm developping a php application which is used to process IP adresses. Thus, I'm juggling with mysql tables containing up to 4 billion rows.
I have a script that currently needs to fetch 65536 adresses from this table and the mysql query fails to give a response via PHP or even via phpMyAdmin when I try to extract these 65K lines.
The table containing the IP Adresses has 3 indexes ( 1 unique, 2 primary ) which are supposed to help it go faster but I simply cannot get past having mysql give an associative array back to PHP in order to continue my data processing.
Any tips as to how to circumvent this problem ?
Thx in advance !
$request = new Request(DB_NAME);
$request->select = '*';
$request->from = Etherwan_Adressage_Ip::TABLE_NAME;
$request->where = Etherwan_Adressage_Ip_Ressource::PRIMARY_KEY." = '".$options->Ressource_ID."'";
$request->order = " inet_aton(IP) ";
$Compteur = 0;
$Liste = array();
$result = $request->exec('select');
for ($i=0 ; $i<$result['length'] ; $i+=$CIDR->Adresses_Totales){
$Possible = TRUE;
$Selected = FALSE;
for ($j=$i ; $j<$i+$CIDR->Adresses_Totales ; $j++){
if ($result[$j]['Date_Affectation'] != '0000-00-00 00:00:00'){
if (isset($options->Include)){
if ($options->Include->Type != $result[$j]['Type_Liaison'] || $options->Include->Liaison_ID != $result[$j]['Liaison_ID'] || str_replace('/', '', $options->CIDR) != $result[$j]['Bits']){
$Possible = FALSE;
} else {
$Selected = TRUE;
}
} else {
$Possible = FALSE;
}
break;
}
}
if ($Possible){
$Liste[$Compteur]['text'] = $result[$i]['IP'] . " / " . $result[$i+$CIDR->Adresses_Totales-1]['IP'];
$Liste[$Compteur]['value'] = $result[$i]['Ressource_ID'];
$Liste[$Compteur]['selected'] = $Selected;
$Liste_IP = array();
for ($j=$i ; $j<$i+$CIDR->Adresses_Totales ; $j++){
if ($result[$j]['Nom'] != ''){
$result[$j]['Dispo'] = 0;
} else {
$result[$j]['Dispo'] = 1;
}
$Liste_IP[] = $result[$j];
}
$Liste[$Compteur]['Liste_IP'] = $Liste_IP;
$Compteur++;
}
}
$Liste['maxLength'] = $Liste['length'] = $Compteur;
return $Liste;
Link to table indexes ( JPG )
Link to data sample ( JPG )
I am trying to update a table based on the input provided by a user. There are ten fields which a user can choose to input information into. The table I am trying to input too has a following structure.
leagueTrackID | leagueID | trackID
1 1 1
2 1 2
3 1 12
...
15 1 4
I need the code to update the fields where a new track has been added via looping though each inputted track and place it in a new field which has the matching criteria. The criteria which it needs to be match too is the leagueID. How can this be achieved without overwriting the same column row?
The code below is what I have so far but I have an error with trying to assign the php track variables to either a php array or php list.
$data = mysql_query("SELECT COUNT(leagueID) AS totalTracks , min(leagueTrackID) AS minLeagueID , max(leagueTrackID) AS maxLeagueID , leagueID , trackID
FROM leagueTracks
WHERE leagueID = '$vaildLeagueID'");
$info = mysql_fetch_array( $data );
// get posted track id and assign them to the php track varaibles
if ( $_POST['track1'] == '' ) { $track1 = $info['track1']; } else { $track1 = $_POST['track1']; }
if ( $_POST['track2'] == '' ) { $track2 = $info['track2']; } else { $track2 = $_POST['track2']; }
if ( $_POST['track3'] == '' ) { $track3 = $info['track3']; } else { $track3 = $_POST['track3']; }
if ( $_POST['track4'] == '' ) { $track4 = $info['track4']; } else { $track4 = $_POST['track4']; }
if ( $_POST['track5'] == '' ) { $track5 = $info['track5']; } else { $track5 = $_POST['track5']; }
if ( $_POST['track6'] == '' ) { $track6 = $info['track6']; } else { $track6 = $_POST['track6']; }
if ( $_POST['track7'] == '' ) { $track7 = $info['track7']; } else { $track7 = $_POST['track7']; }
if ( $_POST['track8'] == '' ) { $track8 = $info['track8']; } else { $track8 = $_POST['track8']; }
if ( $_POST['track9'] == '' ) { $track9 = $info['track9']; } else { $track9 = $_POST['track9']; }
if ( $_POST['track10'] == '' ) { $track10 = $info['track10']; } else { $track10 = $_POST['track10']; }
// Assign tracks selected to an array
$tracksArray = array($track1 , '$track2' , '$track3', '$track4', '$track5' , '$track6' ,'$track7', '$track8' , '$track9' , '$tack10');
// Counter
$trackNumber = '1';
// Get the lowest leagueTrackID based on the leagueID being updated
$min = $info['minleagueID'];
// Get the highest leagueTrackID based on the leagueID being updated
$max = $info['maxLeagueID'];
while($min != $max) {
$updateLeagueTracks = mysql_query ("UPDATE userLeague SET trackID = $trackArray['$tracknumber'] WHERE leagueID = '$vaildLeagueID'");
$addTracks = mysql_query($updateLeagueTracks);
$trackNumber++;
$min++;
} // closes the for loop