Array showing only first result good - php

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
}
?>

Related

Implementing a function from another one

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

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.

php array is not sorting as expected

I have two lists of check boxes. I am checking which check box is selected and based on that I am trying to get an array.
Let's say the two lists are size which have small, medium, large boxes checked and the other one is color which have red, green, blue boxes checked. The array should look something like:
array[['small', 'medium', 'large']['red', 'green', 'blue']]
But I am getting this:
array[["small"],["medium"],["large"]] [["red"],["green"],["blue"]]
This is the code:
$counter = 0;
$attributes_list = [];
foreach($features_cuts_list as $k => $features_cut) {
$inner_counter = 0;
if ($features_cut["selectedid"] != "") {
$attributes_list[$counter] = [];
$title_to_get = $features_cut["features_cuts_id"];
/* Gets the name of the box that is checked */
$query = "SELECT title FROM features_cuts_translations WHERE lang = '$lang' AND features_cuts_id = '$title_to_get' LIMIT 1;";
$result = mysql_query($query) or die("Cannot query");
$attribute_name = mysql_fetch_row($result);
foreach ($attribute_name as $q) {
array_push($attributes_list[$counter], $q);
}
$counter++;
} else {
}
}
EDIT:
This is the deceleration process for $features_cuts_list:
function getListValuesSql($sql){
global $link; //Database connection
$data=array();
$subData{0}=array();
$res=mysql_query($sql,$link);
if(mysql_num_rows($res)>0){
$i=0;
while($row=mysql_fetch_array($res)){
for($j=0;$j<mysql_num_fields($res);$j++){
$field=mysql_field_name($res, $j);
$subData{$i}[$field]=$row[$field];
}
$data[$i]=$subData{$i};
$i++;
}
return $data;
}else{
return 0;
}
}
$feature_id = $feature["features_id"];
$features_cuts_list = $data->getListValuesSql("
SELECT DISTINCT fct.*, fc.sort, fc.inner_id, fc.price,
fcp.features_cuts_id AS selectedid, IFNULL(fcpv.price,fc.price)
AS price, fcpv.sku
FROM `features_cuts` as fc
JOIN `features_cuts_translations` as fct ON fct.features_cuts_id=fc.id
LEFT JOIN `features_cuts_product_values` as fcpv ON fc.id=fcpv.features_cuts_id AND fcpv.product_id='$pageid'
LEFT JOIN `features_cuts_products` as fcp ON fc.id=fcp.features_cuts_id AND fcp.product_id='$pageid'
WHERE fc.features_id='$feature_id' AND fct.lang='$lang'
Order by fc.sort
");
Hopes this is helpful
From reading your code I think you have unnecessarily provided the $counter variable.Try this modified code:
$attributes_list = [];
foreach($features_cuts_list as $k => $features_cut) {
$inner_counter = 0;
if ($features_cut["selectedid"] != "") {
$title_to_get = $features_cut["features_cuts_id"];
/* Gets the name of the box that is checked */
$query = "SELECT title FROM features_cuts_translations WHERE lang = '$lang' AND features_cuts_id = '$title_to_get' LIMIT 1;";
$result = mysql_query($query) or die("Cannot query");
$attribute_name = mysql_fetch_row($result);
foreach ($attribute_name as $q) {
array_push($attributes_list, $q);
}
$counter++;
} else {
}
}
If not completely, it will mostly solve your issue.
Let me know what the result are , after running this piece of code.

Fetching only first row value in Database

We are trying to fetch value from database & display related value for all rows.
but code is fetching only first row value in DB & displaying same value for all rows.
Database
Site
function getDesignerCollection()
{
$i = 0;
foreach($order as $orderData)
{
$orderitems = $orderData['dproduct_id'];
$orderitemsarray = explode(",", $orderitems);
$k = 0;
while ($k < count($orderitemsarray))
{
if($data['dpaid_status']=='P'){$dpaid_status='Paid';}
if($data['dpaid_status']=='U'){$dpaid_status='Unpaid';}
if($data['dpaid_status']=='R'){$dpaid_status='Returned';}
if($data['dpaid_status']==''){$dpaid_status='';}
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details");
$stmtorders->execute(array(
":dorder_id" => $orderData['entity_id']
));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
if ($roworders['dproduct_id'] == '')
{
$dorderStatus = "Unpaid";
}
else
{
$dorderStatus = $roworders['dpaid_status'];
}
$responce[] = array(
$orderData->getIncrementId() ,
$orderData->getIncrementId() ,
$orderitemsarray[$k],
$dorderStatus
);
}
$k++;
$i++;
}
}
echo json_encode($responce);
}
full code : http://pastebin.com/GnT980nL
You need use fetchAll() instead fetch()
http://php.net/manual/ru/pdostatement.fetchall.php
Your function must looks like:
function getDesignerCollection() {
global $is_admin;
$user_home = new USER();
require_once '../../app/Mage.php';
Mage::app();
$stmts = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmts->execute(array(
":uid" => $_SESSION['userSession']
));
$rows = $stmts->fetchAll(PDO::FETCH_ASSOC);
}
Now in $rows you have array of associative arrays.

How to loop through an array and add to it in JSON

I have an array containing several variables from my sql database.
{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"}, {"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}
I have an additional variable called $score that uses information from the database to calculate this score. I want to know how I can loop through and add the correct score to each country in the array.
My Original Code:
$row = $res->fetchRow();
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];
$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);
if($population == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
}
else if($gdp == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resGdp);
}
$result = $res->fetchAll();
$result[] = array('score' => $score);
echo json_encode($result);
Your code will be something like this:
$json_data = '{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"},
{"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}';
$countries_info_new = array();
$countries_info = json_decode($json_data);
foreach($countries_info as $country_info){
$country_info['score'] = Get_country_score($country_info['country_name']);
$countries_info_new[]=$country_info;
}
$new_json_data = json_encode($countries_info_new);

Categories