First off, I am fairly new to coding. I try to do my due diligence before coming here for advice.
I am trying to write a function that will query the database for a users numbers and get the average for each user.
function getUserAverage($userID) {
//loop through user totals & calculate average for each user
$sql = "select p.userID, p.user, p.number ";
$sql .= "from " . DB_PREFIX . "numbers p ";
$sql .= "inner join " . DB_PREFIX . "users u on p.userID = u.userID ";
$sql .= "where u.userID = " . $user->userID . " ";
$sql .= "order by u.lastname, u.firstname";
$query = $mysqli->query($sql);
while ($row = $query->fetch_assoc()) {
//player average of numbers
$tba = ROUND(AVG(`number`),2);
}
$query->free;
return $tba;
}
The result I am hoping to get is something like:
user1 = 14.5
user2 = 35.8
user3 - 7.4
I have written code to get the average numbers for all, but the need is to get by individual user.
//Average Numbers
$sql_avgNum = "SELECT ROUND(AVG(`number`),2) AS `Average` \n"
. "FROM `" . DB_PREFIX . "numbers` \n";
$data = $mysqli->query($sql_avgNum);
$result_avgNum = mysqli_fetch_array($data);
echo ' <tr class="altrow"><td> Average Number: </td><td> ' .
$result_avgNum[0] . ' </td></tr>';
//End Average Numbers
for count average of individual data you must do it using group by. Further reference of group by is here:
I'm not very sure, but I think that this is what you're looking for:
function getUserAverage($userID) {
// loop through user totals & calculate average for each user
$sql = "SELECT p.userID, u.user, AVG(p.number) AS 'avarage' ";
$sql .= "FROM " . DB_PREFIX . "numbers p ";
$sql .= "INNER JOIN " . DB_PREFIX . "users u ON(p.userID = u.userID) ";
$sql .= "WHERE p.userID = " . $user->userID . " ";
$sql .= "GROUP BY p.userID ";
$sql .= "ORDER BY u.lastname, u.firstname";
$query = $mysqli->query($sql);
while ($row = $query->fetch_assoc()) {
//player average of numbers
$tba = $row['avarage'];
}
$query->free;
return $tba;
}
Related
$sql = "SELECT feed.feed_id, feed.title, feed.imgsrc, feed.details, Author.author_name, Feed_class.class_name, feed.create_at \n"
. " FROM feed JOIN Author JOIN Feed_class \n"
. " ON feed.author_id = Author.author_id AND feed.feedClass_id = \n"
. " Feed_class.feedClass_id ORDER BY feed.create_at WHERE feed_id = $feed_id; ";
$sql = "SELECT feed.feed_id, feed.title, feed.imgsrc, feed.details, Author.author_name, Feed_class.class_name, feed.create_at \n"
. " FROM feed JOIN Author ON feed.author_id = Author.author_id \n"
. " JOIN Feed_class ON feed.feedClass_id = \n"
. " Feed_class.feedClass_id WHERE feed_id = $feed_id ORDER BY feed.create_at ; ";
two issues noted: 1. location of ON clause:- it should be after
mentioning the second table of the join
FROM feed JOIN Author ON feed.author_id = Author.author_id
JOIN Feed_class ON feed.feedClass_id = Feed_class.feedClass_id
Issue two was on Order of WHERE Clause and ORDER Clause:- WHERE appears before ORDER
WHERE feed_id = $feed_id ORDER BY feed.create_at
I'm making a function that brings me the sum of the records in my database that meet 2 conditions.
i start like this
function cuentaticketspendienteempleado($conexion){
$pendientes = (mysqli_query($conexion, "SELECT COUNT(*) AS conteo FROM ticket ")) or die("Error mostrando tickets pendientes: ".mysqli_error($conexion));
$resultados = mysqli_fetch_row($pendientes);
return $resultados[0];
}
I need to add one more field to the account.
the ID department parameter which I want to assign to only tell me the tickets or reports of that department
using the previous function
When I'm trying to account for that user's tickets in that department using this function
function listTicketUnrevisedSupervisor($conexion, $id){
$consulta = mysqli_query($conexion, "SELECT *, COUNT(t.id) as contador_tickets, t.id as id_ticket, u.id as user_id, t.fecha_creacion as t_fcreacion, t.hora_creacion as t_hcreacion
FROM ticket as t
JOIN usuario AS u
ON t.id_usuario = u.id
WHERE t.status <> '3' AND u.id_departamento = ".$id."")
or die("Error listando Ticket: ".mysqli_error($conexion));
return $consulta;
}
i get this
error
Maybe is just the formatting of your post, but the * can't be used on a query when you are selecting other specific fields, you can use the function like this
function listTicketUnrevisedSupervisor($conexion, $id) {
$query = "SELECT t.field1, u.field_2, t.id as id_ticket, u.id as user_id, "
. "t.fecha_creacion as t_fcreacion, "
. "t.hora_creacion as t_hcreacion "
. "FROM ticket as t "
. "JOIN usuario AS u ON t.id_usuario = u.id "
. "WHERE t.status <> '3' "
. "AND u.id_departamento = " . $id . " "
. "ORDER BY t.id DESC ";
if($consulta = mysqli_query($conexion, $query)){
return $consulta;
} else {
die("Error listando Ticket: ".mysqli_error($conexion));
}
}
Or just select everything
function listTicketUnrevisedSupervisor($conexion, $id) {
$query = "SELECT * "
. "FROM ticket as t "
. "JOIN usuario AS u ON t.id_usuario = u.id "
. "WHERE t.status <> '3' "
. "AND u.id_departamento = " . $id . " "
. "ORDER BY t.id DESC ";
if($consulta = mysqli_query($conexion, $query)){
return $consulta;
} else {
die("Error listando Ticket: ".mysqli_error($conexion));
}
}
Counting the rows
$num_rows = mysqli_num_rows($consulta);
mysqli_query documentation (en)
Here you can check the documentation about mysqli_query (En EspaƱol Juan)
Hope my answer helps you.
Edit, fetch all the results
You can do it with a procedure like this one
function getTheAssocArrayOfMyQuery($consulta){
$return= array();
while ($row= mysqli_fetch_assoc($consulta)) {
array_push($return, $consulta);
}
return $return;
}
Or, using mysqli_fetch_all()
$this_is_the_array_i_will_use = mysqli_fetch_all($consulta,MYSQLI_ASSOC);
mysqli_fetch_all() manual
I am trying to optimize some of my code and i believe i need an if/else or case to do this, however I think i would need php in the query to get it to work
here is the code I am trying to optimize
$sql = "SELECT value, COUNT(*) AS count
FROM sodsurvey LEFT OUTER JOIN age
ON sodsurvey.age_id = age.id
WHERE value IS NOT NULL AND office_id = " . $office_id . "
GROUP BY age_id; ";
if ($_SESSION['filteryear'] != 0 && $_SESSION['filtermonth'] != 0) {
$sql = "SELECT value, COUNT(*) AS count
FROM sodsurvey LEFT OUTER JOIN age
ON sodsurvey.age_id = age.id
WHERE value IS NOT NULL AND office_id = " . $office_id . "
AND year = " . $_SESSION['filteryear'] . " AND month = " . $_SESSION['filtermonth'] . "
GROUP BY age_id; ";
} else if ($_SESSION['filteryear'] != 0 || $_SESSION['filtermonth'] != 0) {
$sql = "SELECT value, COUNT(*) AS count
FROM sodsurvey LEFT OUTER JOIN age
ON sodsurvey.age_id = age.id
WHERE value IS NOT NULL AND office_id = " . $office_id . "
AND (year = " . $_SESSION['filteryear'] . " OR month = " . $_SESSION['filtermonth'] . ")
GROUP BY age_id; ";
}
and this is what I have tried to give you a rough idea of what I am trying to achieve
$filter = "";
if ($_SESSION['filteryear'] != 0 && $_SESSION['filtermonth'] != 0) {
$filter = "AND year = " . $_SESSION['filteryear'] . " AND month = " . $_SESSION['filtermonth'] . ""
} else if ($_SESSION['filteryear'] != 0 || $_SESSION['filtermonth'] != 0) {
$filter = "AND (year = " . $_SESSION['filteryear'] . " OR month = " . $_SESSION['filtermonth'] . ")"
}
$sql = "SELECT value, COUNT(*) AS count
FROM sodsurvey LEFT OUTER JOIN age
ON sodsurvey.age_id = age.id
WHERE value IS NOT NULL AND office_id = " . $office_id . "
CASE
WHEN ".isset($filter)." THEN ". $filter ."
END
GROUP BY age_id; ";
You can build up an array of filters depending on which values (year, month, etc) are set, and then combine them all into the WHERE clause. You don't need to worry about all the separate cases where both are set, or one are set, and so on.
I would also strongly echo the advice above that recommended looking into prepared statements, but this will hopefully get you on your way.
<?php
$office_id = 10;
$_SESSION['filteryear'] = 2016;
$_SESSION['filtermonth'] = 12;
$filters = [
"value IS NOT NULL",
"office_id = {$office_id}",
];
if ($_SESSION['filteryear']) {
$filters[] = "year = {$_SESSION['filteryear']}";
}
if ($_SESSION['filtermonth']) {
$filters[] = "month = {$_SESSION['filtermonth']}";
}
$sql = "
SELECT value, COUNT(*) AS count
FROM sodsurvey
LEFT JOIN age ON sodsurvey.age_id = age.id
WHERE " . implode(' AND ', $filters) . "
GROUP BY age_id;
";
The implode line combines each filter that's been set into a single WHERE clause.
is it valid to use PHP with a case in my attempt above?
No. PHP code cannot be part of your SQL query, however your PHP code can generate SQL query
In MySQL, I am trying to find a way to optimize my code
Just make your SQL code generated by PHP code based on all the conditions. You can easily concatenate strings being partions of your query conditionally.
I have a mysqli SELECT query that is using an Inner Join and I noticed a big problem: it doesn't select rows where the column value for the condition is null (because NULL doesn't exist in the second table). Here's my code:
<?php
$sql = mysqli_connect(/* CONNECTION */);
$query = "SELECT " .
"e.EQUIPMENT_ID, " .
"e.CUSTOMER_ID, " .
"e.DESCRIPTION, " .
"e.LOCATION, " .
"e.JOB_SITE, " .
"e.PROJECT_NAME, " .
"jb.DESCRIPTION AS JOB_SITE_NAME " .
"FROM equipments e " .
"INNER JOIN jobsites jb ON jb.JOBSITE_ID = e.JOB_SITE " .
"WHERE e.CUSTOMER_ID = 1 ".
"ORDER BY e.EQUIPMENT_ID ASC";
$results = mysqli_query($sql, $query);
if(!isset($data)) $data = array(); $cc = 0;
while($info = mysqli_fetch_array($results, MYSQLI_ASSOC)){
if(!isset($data[$cc])) $data[$cc] = array();
///// FROM TABLE equipments /////
$data[$cc]['EQUIPMENT_ID'] = $info['EQUIPMENT_ID'];
$data[$cc]['DESCRIPTION'] = $info['DESCRIPTION'];
$data[$cc]['LOCATION'] = $info['LOCATION'];
$data[$cc]['PROJECT_NAME'] = $info['PROJECT_NAME'];
$data[$cc]['JOB_SITE_ID'] = $info['JOB_SITE'];
///// FROM TABLE jobsites /////
$data[$cc]['JOB_SITE'] = $info['JOB_SITE_NAME'];
$cc++;
}
print_r($data);
?>
So, as I said, the code returns values but only if the column "JOB_SITE" inside "equipments" has a jobsite id (not null). The ugly solution is to create a row inside the table "jobsites" with a jobsite_id named "empty", but if I can skip this, I will.
Is there a way to join only if e.JOB_SITE is not null ?
You can use LEFT JOIN in SQL query.
$query = "SELECT " .
"e.EQUIPMENT_ID, " .
"e.CUSTOMER_ID, " .
"e.DESCRIPTION, " .
"e.LOCATION, " .
"e.JOB_SITE, " .
"e.PROJECT_NAME, " .
"jb.DESCRIPTION AS JOB_SITE_NAME " .
"FROM equipments e " .
"LEFT JOIN jobsites jb ON jb.JOBSITE_ID = e.JOB_SITE " .
"WHERE e.CUSTOMER_ID = 1 ".
"ORDER BY e.EQUIPMENT_ID ASC";
This query will return NULL VALUE for column JOB_SITE_NAME if there is no row matching jb.JOBSITE_ID in equipments table
When I tested this query out in mysql it was fine but when I went to run it in php I keep getting this error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT *, (#rownum := #rownum + 1) AS rank FROM ( SELECT *, (totalWins+(total' at line 1
This is the php code I have.
<?php
$sql = " SET #rownum = 0; ";
$sql .= " SELECT *, (#rownum := #rownum + 1) AS rank FROM ( ";
$sql .= " SELECT *, (totalWins+(totalPushs*.5)) AS totalPoints, totalWins+totalLost+totalPushs AS totalBets FROM ( ";
$sql .= " SELECT *, SUM(win) AS totalWins, SUM(lost) AS totalLost, SUM(push) AS totalPushs FROM ( ";
$sql .= " SELECT *, (finalResult = 'Winner') AS win, (finalResult = 'Loser') AS lost, (finalResult = 'Push') AS push FROM ( ";
$sql .= " SELECT " . $db_prefix . "users.userID, userName, ";
$sql .= " IF (pickID=visitorID, visitorResult, homeResult) AS finalResult ";
$sql .= " FROM " . $db_prefix . "users ";
$sql .= " JOIN " . $db_prefix . "picks ";
$sql .= " ON " . $db_prefix . "users.userID = " . $db_prefix . "picks.userID ";
$sql .= " JOIN " . $db_prefix . "schedule ";
$sql .= " ON " . $db_prefix . "picks.gameID = " . $db_prefix . "schedule.gameID ";
$sql .= " ) x ";
$sql .= " ) x ";
$sql .= " GROUP BY userID ";
$sql .= " ) x ";
$sql .= " ) x ";
$sql .= " ORDER BY totalPoints DESC, totalWins DESC, totalPushs DESC, totalLost ";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row[rank] . '|' . $row[userName]. '|' . $row[totalWins] . '|' . $row[totalLost] . '|' . $row[totalPushs] . '|' . $row[totalPoints];
echo '<br>';
}
?>
I can get the php code to work without the first line of code
$sql = " SET #rownum = 0; ";
but it won't echo out the rank column.
Is there something I have to do differently to line one of the code when it's in php?
mysql_query does not support running more than one query at a time. You must first run
mysql_query("SET #rownum = 0;");, then you can run the rest of your query in a second mysql_query call.
Please try tablename.* instead of *