Implementing a function from another one - php

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();
}

Related

Ambiguous column in Codeigniter Datatables server side

I'm working on a system that has several server-side datatables but i facing issues with 2 joins when i try to order de columns.
I receive the following message when try to sort the columns:
Query error: Column 'notes' in order clause is ambiguous - Invalid query: SELECT *
FROM `tbl_project`
LEFT JOIN `tbl_client` ON `tbl_project`.`client_id`=`tbl_client`.`client_id`
LEFT JOIN `tbl_account_details` ON `tbl_project`.`created_by` = `tbl_account_details`.`user_id`
LEFT JOIN `tbl_notes` ON `tbl_project`.`notes` = `tbl_notes`.`notes_id`
WHERE `tbl_project`.`client_id` = '100'
ORDER BY `notes` DESC
LIMIT 10
This is the code with my query:
$id = $this->input->post("client_id");
$client_details = get_row('tbl_client', array('client_id' => $id));
$draw = intval($this->input->post("draw"));
$start = intval($this->input->post("start"));
$length = intval($this->input->post("length"));
$order = $this->input->post("order");
$search= $this->input->post("search");
$search = $search['value'];
$col = 0;
$dir = "";
if(!empty($order))
{
foreach($order as $o)
{
$col = $o['column'];
$dir= $o['dir'];
}
}
if($dir != "desc" && $dir != "desc")
{
$dir = "desc";
}
$valid_columns = array(
0=>'project_id',
1=>'client',
2=>'fullname',
3=>'notes',
4=>'origen',
5=>'end_date',
6=>'project_status',
7=>'action',
);
if(!isset($valid_columns[$col]))
{
$order = null;
}
else
{
$order = $valid_columns[$col];
}
if($order !=null)
{
$this->db->order_by($order, $dir);
}
$searchQuery = "";
if($search != ''){
$searchQuery = " (tbl_project.project_id like'%".$search."%' OR tbl_project.end_date like'%".$search."%' OR tbl_project.project_status like'%".$search."%' OR tbl_notes.notes like'%".$search."%' OR tbl_notes.eco like'%".$search."%' OR tbl_account_details.origen like'%".$search."%' OR tbl_client.name like'%".$search."%') ";
}
$this->db->select('*');
$this->db->from('tbl_project');
$this->db->join('tbl_client', 'tbl_project.client_id=tbl_client.client_id','left');
$this->db->join('tbl_account_details', 'tbl_project.created_by = tbl_account_details.user_id','left');
$this->db->join('tbl_notes', 'tbl_project.notes = tbl_notes.notes_id','left');
$this->db->where('tbl_project.client_id', $client_details->client_id);
if($searchQuery != '')
$this->db->where($searchQuery);
$this->db->limit($length,$start);
$cita = $this->db->get()->result();
For some reason the ORDER BY is not set as tbl_notes.notes
Any suggestion on how to fix this?
Thanks in advance
EDIT: i have added more code so there is more visibility of the process
The error occurs, because your column name is not unique, it exists in more than one table.
append the table name of the searched column to your query to make it unique:
for example in this line:
$this->db->order_by('my_table_name.'.$order, $dir);
that would generate something like
ORDER BY `my_table_name.notes` DESC
edit: or in case you have to address columns from several different tables you could change your $valid_columns array:
$valid_columns = array(
0=>'my_table_name1.project_id',
1=>'my_table_name2.client',
2=>'my_table_name2.fullname',
3=>'my_table_name3.notes',
// etc.
);
and maintain the remaining original code.

Same serial number is generating for different requests

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.

Problem in duplication after clicking submit button multiple times

My main problem is with that code in which when I click on submit buttons many times, it inserts duplication many times in the database in which I need to avoid that. Please help me to solve this problem. These are the two tables in which I am trying to insert. mat_ans_options_choose and mat_answer.
$val = $this->input->post(null, true);
$val['id'] = $this->input->post('id');
$val['sub_type'] = $this->input->post('sub_type');
$val['timeout'] = $this->input->post('timeout');
$val['level'] = $this->input->post('level');
$val['mat_category'] = $this->input->post('mat_category');
$option = $val['option'] = $this->input->post('option');
$type = $this->input->post('type');
$marks = [];
$uid = $this->session->userdata('id');
if (isset($val['id']) && isset($option)) {
$query = $this->db->query("SELECT * FROM mat_ans_options WHERE deleted=0 AND active=1 AND question=" . $val['id']);
$result = $query->result_array();
if ($query->num_rows() > 0) {
$count1 = 1;
foreach ($result as $res) {
if ($res['marks'] == 1) {
break;
} else {
$count1++;
}
}
}
// MAT answers options choose
$query1 = $this->db->query("SELECT * FROM mat_ans_options_choose WHERE deleted=0 AND active=1 AND uid=$uid AND q=" . $val['id']);
$result1 = $query1->result_array();
if ($query1->num_rows() > 0) {} else {
$data1 = [
'uid' => $uid,
'q' => $val['id'],
'option_chose' => $option,
'createdon' => $this->general_model->server_time(),
];
$this->db->insert('mat_ans_options_choose', $data1);
}
if ($count1 == $option) {
$marks = 1;
} else {
$marks = 0;
}
// if($marks==1 || $marks==0)
// {
// MAT answers
$query2 = $this->db->query("SELECT * FROM mat_answers WHERE deleted=0 AND active=1 AND uid=$uid AND q=" . $val['id'] . " AND type=" . $type . " AND sub_type=" . $val['sub_type'] . " AND level=" . $val['level']);
$result2 = $query2->result_array();
if ($query2->num_rows() > 0) {} else {
$data = [
'uid' => $uid,
'q' => $val['id'],
'type' => $type,
'level' => $val['level'],
'sub_type' => $val['sub_type'],
'mat_category' => $val['mat_category'],
'marks' => $marks,
'timeoutstatus' => $val['timeout'],
'createdon' => $this->general_model->server_time(),
];
$this->db->insert('mat_answers', $data);
}
// }
return 1;
} else {
return 0;
}
Use JS in which you disable the button after first click - it will work no matter if you are using AJAX or not.
You can use JS/jQuery to limit the number of requests made on the client side. For example by disabling the button on submit:
$("#my-button").prop("disabled", true);
But if the data is sensitive for duplicates (orders, user registration etc) you should make the request limit server side with PHP. You can achieve this by adding a unique index to the tables, either on user id or on a unique token that is submitted with the html form.
Create UNIQUE index in database for uid and q. The database will not insert same question's id from same user's id mulitple times.

Using PHP, loop and update certain records

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.

Array showing only first result good

I try to write this code on few ways, but always the result is good only for first team all other results are bad.
When I put id of some other club instead of $id I get the good result for that team but than is only one row, I want to show all 20 teams.
<table>
<thead><tr><th>Name</th><th>Played</th><th>0,5</th><th>1,5</th><th>2,5</th>
<th>3,5</th><th>4,5</th></tr></thead>
<tbody>
<?php
$teams = mysql_query("select * from teams");
$num_teams = mysql_num_rows($teams);
while ($group = mysql_fetch_row($teams)) {
$id_team[] = $group;
}
for ($a = 0; $a < $num_teams; $a++) {
if (isset($num_array)) {
mysql_data_seek($query_array, 0 );
$search_array_over = array();
}
$id = $id_team[$a][0];
$name_over = $id_team[$a][1];
$query_array = mysql_query("select * from full_stat where kl1 = $id or kl2 = $id");
$num_array = mysql_num_rows($query_array);
while ($row = mysql_fetch_row($query_array)) {
$data_over[] = $row;
}
$search_array_over = array('1' => '0', '2' => '0' ,'3' => '0', '4' => '0','5' => '0','6' => '0');
for ($now = 0;$now < $num_array; $now++) {
$over_pass = ($data_over[$now][3] + $data_over[$now][4]);
for ($pass = 1; $pass < 7; $pass++) {
if ($over_pass >= $pass) {
$final_pass = $pass;
}
else {
$final_pass = '6';
}
if (array_key_exists($final_pass, $search_array_over)) {
$search_array_over[$final_pass] += 1;
}
else {
$search_array_over[$final_pass] = 1;
}
}
}
echo '<tr><td>'.$name_over.'</td><td>'.$num_array.'</td> <td>'.$search_array_over[1].'</td><td>'.$search_array_over[2].'</td><td>'.$search_array_over[3].'</td><td>'.$search_array_over[4].'</td><td>'.$search_array_over[5].'</td></tr>';
}
?>
</tbody>
</table>
That is one confusing block of PHP code.
A better explanation of your final output would probably help here, but I'm going to guess it's the teamlist plus their statistics.
Since dissecting your current code strikes me as painful, I'm going to describe how I would do this instead.
In your database you have 2 tables, "team" and "team_stats"
Team Structure:
id int
name varchar
....
Stats Structure:
team_id int
someStat int
otherStat int
....
$stmt = $mysqli -> prepare("SELECT * FROM team LEFT JOIN team_stats ON team_stats.team_id");
$stmt -> execute();
$result = $stmt -> fetch_all();
foreach($result as $team) {
// output data to page
}
?>

Categories