I'm trying to make a map with available gyms that also shows what exercises they have. So it looks like this:
Name Gym
Open spots: (number)
Logo image of Gym
Time of excercise.
Image of a dumbel for example
Trainer
The part from Time of exercise til Trainer needs to show more than one, I got like 6 exercises with 6 trainers, and 6 times and 6 different images of exercises to show. I store those in a database; but they don't show up.
Here my code:
$sql = "SELECT * FROM forts";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
echo "[";
$output = array();
while($row = $result->fetch_assoc()) {
$url = preg_replace("/^http:/i", "https:", $row['url']);
$sqlmon = "SELECT * FROM gym_trainers WHERE fort_id = " . $row['id'];
$resultmon = $mysqli->query($sqlmon);
$mon = $resultmon->fetch_assoc();
$sqlextra = "SELECT * FROM extrainfo WHERE fort_id = " . $row['id'] . " ORDER BY last_modified DESC";
$resultextra = $mysqli->query($sqlextra);
$extra = $resultextra->fetch_assoc();
array_push($output, '
{
"id": "' . $row['id'] . '",
"name": "' . htmlspecialchars($row['name']) . '",
"image": "' . $url . '",
"team": "' . $team . '",
"spots": ' . $extra['spots'] . ',
"exer_time": ' . $mon['time_exerise'] . ',
"trainer": "' . htmlspecialchars($mon['trainer_name']) . '",
"exercise_id": ' . $mon['exercise_id'] . ',
"lat": ' . $row['lat'] . ',
"lng": ' . $row['lon'] . '
}
');
}
echo implode(",", $output);
echo "]";
I think something with this part needs to change, but don't know what:
"exer_time": ' . $mon['time_exerise'] . ',
"trainer": "' . htmlspecialchars($mon['trainer_name']) . '",
"exercise_id": ' . $mon['exercise_id'] . ',
The specific problem is that you fetch only 1 record from the gym_trainers table (the $resultmon->fetch_assoc() is not in a separate loop).
The wider problem is that you do not use joins. The 3 separate sql queries could be written as
select *
from forts f
left join gym_trainers g on f.id=g.fort_id
left join extrainfo e on f.id=g.fort_id
In this case you would need a single loop and within the single loop you track if the fort changes.
Related
I am working in PHP with Laravel and the page I have been given contains 3 SQL queries on separate tables but using the same criteria. I have tried combining them but the combined results are slower than the original. What can I do to increase rather than decrease the speed of these queries?
Here are my queries:
$searchFor = 'debtor_name';
$searchForBKR = 'estate_name';
$searchForHypotech = 'hypleg_lot_credit_debtor_name';
$arraySearch = explode(",", $request->input('name'));
$search = $searchFor . ' like "%';
$bkrSearch = $searchForBKR . ' like "%';
$hypotechSearch = $searchForHypotech . ' like "%';
$searchCompany = $searchCompanyFor . ' like "%';
$searchPlaintiff = $searchPlaintiffFor . ' like "%';
$searchDefendantName = $searchDefendantNameFor . ' like "%';
$search = $search . $arraySearch[0] . '%"';
$bkrSearch = $bkrSearch . $arraySearch[0] . '%"';
$hypotechSearch = $hypotechSearch . $arraySearch[0] . '%"';
$searchCompany = $searchCompany . $arraySearch[0] . '%"';
$searchPlaintiff = $searchPlaintiff . $arraySearch[0] . '%"';
$searchDefendantName = $searchDefendantName . $arraySearch[0] . '%"';
for ($i = 1; $i < count($arraySearch); $i++) {
$search = $search . " or " . $searchFor . ' like "%' . $arraySearch[$i] . '%"';
$bkrSearch = $bkrSearch . " or " . $searchForBKR . ' like "%' . $arraySearch[$i] . '%"';
$hypotechSearch = $hypotechSearch . " or " . $searchForHypotech . ' like "%' . $arraySearch[$i] . '%"';
$searchCompany = $searchCompany . " or " . $searchCompanyFor . ' like "%' . $arraySearch[$i] . '%"';
$searchPlaintiff = $searchPlaintiff . " or " . $searchPlaintiffFor . ' like "%' . $arraySearch[$i] . '%"';
$searchDefendantName = $searchDefendantName . " or " . $searchDefendantNameFor . ' like "%' . $arraySearch[$i] . '%"';
}
$sis = DB::select('select debtor_name, count(*) as sis_total from equifax_sis_regions' . $search . ')
group by debtor_name');
$bkr = DB::select('select estate_name as debtor_name, count(*) as bkr_total from equifax_bkr_regions' . $bkrSearch . ')
group by estate_name');
$hypotech = DB::select('select hypleg_lot_credit_debtor_name as debtor_name, count(*) as hypotech_total from equifax_hypotech_regions' . $hypotechSearch . ')
group by hypleg_lot_credit_debtor_name');
I have tried replacing the 3 queries by using outer joins like this:
$other = 'select debtor_name, count(debtor_name) as sis_total,
estate_name as debtor_name, count(estate_name) as bkr_total
hypleg_lot_credit_debtor_name as debtor_name, count(hypleg_lot_credit_debtor_name) as hypotech_total
from equifax_sis_regions outer join equifax_bkr_regions on (equifax_sis_regions.debtor_name=estate_name)
outer join equifax_hypotech_regions on (equifax_sis_regions.debtor_name=hypleg_lot_credit_debtor_name)
WHERE (' . $search . ') OR ' . $bkrSearch . ') OR (' . $hypotechSearch . ')
GROUP BY debtor_name, estate_name, hypleg_lot_credit_debtor_name';
but that is a much slower query to run. The database contains over 4 million rows and the difference in API calls to the 2 query versions is ~53 seconds for the original and ~78 seconds for the combined form. Is there any way I can modify this combined query to be faster rather than slower?
Thanks in advance
You can use the UNION ALL operator to combine multiple SELECT statements. You could combine them like this:
SELECT debtor_name, SUM(sis_total), SUM(bkr_total), SUM(hypotech_total)
FROM (
SELECT debtor_name, COUNT(*) AS sis_total, 0 AS bkr_total, 0 AS hypotech_total
FROM equifax_sis_regions
-- add where clause here
GROUP BY debtor_name
UNION ALL
SELECT estate_name AS debtor_name, 0 AS sis_total, COUNT(*) AS bkr_total, 0 AS hypotech_total
FROM equifax_bkr_regions
-- add where clause here
GROUP BY estate_name
UNION ALL
SELECT hypleg_lot_credit_debtor_name AS debtor_name, 0 AS sis_total, 0 AS bkr_total, COUNT(*) AS hypotech_total
FROM equifax_hypotech_regions
-- add where clause here
GROUP BY hypleg_lot_credit_debtor_name
) derived
GROUP BY debtor_name;
I have the following script that retrieve numbers from 2 tables, make a sum, and the value is updated into a 3th table.
$query = "SELECT (SELECT SUM(net_amount) FROM fin_costos WHERE month='1' AND group_of_costos='general' AND year_analysis='2014' ) +
(SELECT SUM(net_amount) FROM em2_fin_costs WHERE month='1' AND group_of_costos='general' AND year_analysis='2014') AS total";
$result = mysqli_query($mysqli,$query);
while($row = mysqli_fetch_array($result)){$valor_final = $row['total']; }
$query_update="UPDATE fusion_analysis SET jan='$valor_final' WHERE year_for_analysis='2014' AND item_for_analysis='general' AND category='general'";
$result = mysqli_query($mysqli,$query_update);
I need to run the same script for each month of the year. Everything is exaclty the same except the variable 'month' that changes from 1 to 12 and the SET in UPDATE where the value is uploaded for each month ('jan','feb', 'mar'...etc)
I'm currently just copying and pasting the same script changing this few parameters but I believe there is a smarter way to do this in less lines of code I have
See date function of PHP:
$query = "SELECT (SELECT SUM(net_amount)"
. " FROM fin_costos"
. " WHERE month='".date('n')."'"
." AND group_of_costos='general' AND year_analysis='".date("Y")."' ) +"
."(SELECT SUM(net_amount) FROM em2_fin_costs WHERE month='".date('n')."'"
. " AND group_of_costos='general' AND year_analysis='".date("Y")."') AS total";
$query_update="UPDATE fusion_analysis"
. " SET `". strtolower(date('M'))."`='$valor_final'"
. " WHERE year_for_analysis='".date("Y")."'"
. " AND item_for_analysis='general'"
. " AND category='general'";
NOTE:
Y - A full numeric representation of a year, 4 digits like 2014
n - Numeric representation of a month, without leading zeros 1 - 12
M - A short textual representation of a month, three letters Jan through Dec
For month as short textual I've used the strtolower function to make it lowercase.
UPDATE
Based on OP comment:
for ($i = 1; $i <= 12; $i++) {
$query = "SELECT (SELECT SUM(net_amount)"
. " FROM fin_costos"
. " WHERE month='" . $i . "'"
. " AND group_of_costos='general' AND year_analysis='" . date("Y") . "' ) +"
. "(SELECT SUM(net_amount) FROM em2_fin_costs WHERE month='" . $i . "'"
. " AND group_of_costos='general' AND year_analysis='" . date("Y") . "') AS total";
$result = mysqli_query($mysqli, $query);
$row = mysqli_fetch_assoc($result);
$valor_final = $row['total'];
$monthName = strtolower(date('M', strtotime(date("Y") . "-" . str_pad($month,2, "0", STR_PAD_LEFT) . "-" . date("01") )));
$query_update = "UPDATE fusion_analysis"
. " SET `" . $monthName . "`=' " . $valor_final . "'"
. " WHERE year_for_analysis='" . date("Y") . "'"
. " AND item_for_analysis='general'"
. " AND category='general'";
mysqli_query($mysqli, $query_update);
}
I have two tables that I am creating a list that shows all the expenses under each expense type. I have been able to get it to work except when I add the
AND WHERE expenses.pid = " . $pid
it cases a Syntax error and I can't figure out way.
The biggest thing is I need to limet the Expense Type to only show the ones that have some data to go below them
EXPENSETYPE
typeid
pid
exptype
EXPENSES
expid
pid
expdate
checktype
payee
typeid
details
amount
<?php
$pid = 6;
$sql = "SELECT expensetype.typeid, expensetype.exptype
FROM `expensetype` WHERE expensetype.pid = $pid
ORDER BY expensetype.typeid DESC";
$expensetype = $db->query($sql);
foreach($expensetype as $type) {
echo '<li>' . $type['exptype'] . '<ul>';
$sql2 = "SELECT expenses.expid, expenses.expdate, expenses.checktype, expenses.payee, expenses.details, expenses.amount
FROM `expenses` WHERE `expenses`.typeid = " . $type['typeid'] . "AND WHERE expenses.pid = " . $pid ;
$expenses = $db->query($sql2);
foreach($expenses as $exp) {
echo '<li>' . $exp['expdate'] . ' ' . $exp['checktype'] . ' ' . $exp['expdate'] . ' ' . $exp['payee'] . ' ' . $exp['details'] .' ' . $exp['amount'] .'</li>';
}
echo '</ul></li>';
}
?>
Try this SQL statement instead of making two of them :
SELECT `expensetype`.`typeid`, `expensetype.exptype`, `expenses`.`expid`,
`expenses`.`expdate`, `expenses`.`checktype`, `expenses`.`payee`,
`expenses`.`details`, `expenses`.`amount`
FROM `expensetype` INNER JOIN `expenses` ON
`expensetype`.`typeid` = `expense`.`typeid`
WHERE (...)
Also, you cannot use two WHERE in a SQL statement, only use AND.
problems with a lot of users have the names of long in who liked for this Story
So How can I sort users by number of published links in who voted.
in libs/htm1.php
function who_voted($storyid, $avatar_size){
// this returns who voted for a story
// eventually add support for filters (only show friends, etc)
global $db;
if (!is_numeric($storyid)) die();
$sql = 'SELECT ' . table_votes . '.*, ' . table_users . '.* FROM ' . table_votes . ' INNER JOIN ' . table_users . ' ON ' . table_votes . '.vote_user_id = ' . table_users . '.user_id WHERE (((' . table_votes . '.vote_value)>0) AND ((' . table_votes . '.vote_link_id)='.$storyid.') AND (' . table_votes . '.vote_type= "links")) AND user_level<>"god" AND user_level<>"Spammer"';
//echo $sql;
$voters = $db->get_results($sql);
$voters = object_2_array($voters);
foreach($voters as $key => $val){
$voters[$key]['Avatar_ImgSrc'] = get_avatar($avatar_size, "", $val['user_login'], $val['user_email']);
}
return $voters;
I found these lines in topusers.php, but not for a friendly experience in writing function correctly
case 2: // sort users by number of published links
$select = "SELECT user_id, count(*) as count ";
$from_where = " FROM " . table_links . ", " . table_users . " WHERE link_status = 'published' AND link_author=user_id AND user_level NOT IN ('god','Spammer') AND (user_login!='anonymous' OR user_lastip) GROUP BY link_author";
$order_by = " ORDER BY count DESC ";
break;
I can't get the JOIN syntax correct to alter this existing MySQL query in PHP to include a join from another table. I have another table specified as DB_TABLE2 that contains columns InvmNumr and InvmDesc. The InvmNumr and InvlNumr are the exact same value in each table and I need to display InvmDesc from Table 2 in this query?
$res = mysql_query('SELECT LocId, InvlNumr, InvlQuant FROM ' . DB_TABLE1
. ' WHERE LocId = \'' . mysql_real_escape_string($cType) . '\'
AND InvlNumr = \'' . mysql_real_escape_string($br) . "'");
$markup = '';
Read up on LEFT JOIN vs INNER JOIN depending on how your data is stored in your DB_TABLE2 table.
$res = mysql_query('SELECT ' . DB_TABLE1 . '.LocId, ' . DB_TABLE1 . '.InvlNumr, ' .
DB_TABLE1 . '.InvlQuant, ' . DB_TABLE2 . '.InvmDesc
FROM ' . DB_TABLE1 . ' LEFT JOIN ' . DB_TABLE2 . ' ON ' .
DB_TABLE1 . '.InvlNumr = ' . DB_TABLE2 . '.InvmNumr
WHERE ' . DB_TABLE1 . '.LocId = \'' . mysql_real_escape_string($cType) . '\'
AND ' . DB_TABLE1 . '.InvlNumr = \'' . mysql_real_escape_string($br) . "'");
try this
SELECT db1.LocId,db1.InvlNumr,db1.InvlQuant
FROM DB_TABLE1 db1
INNER JOIN DB_TABLE2 db2 ON db1.InvlNumr = db2.InvlNumr
WHERE dbq.LocId = $cType
AND db1.InvlNumr = $br