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
Related
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;
}
How do I go about running a query on tables from a previous SHOW TABLES query? What I'm trying to do is create a PHP script that runs every 24 hours that sorts a table by "verified" descending and "votes" descending and update "nomnom" on the top result, for every table in the database.
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan = (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE " . $row[0] . " SET nomnom=0 verified=0; UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $row[0] . ' done<br>';
}
} else {
echo 'query 0';
}
This correctly echos every table name followed by done, but isn't actually updating the tables. What am I missing?
UPDATE
So I've determined that the following should work:
$sql = "SET #clan := (SELECT `clan` FROM " . $row[0] . " ORDER BY `verified` DESC, `votes` DESC LIMIT 1); UPDATE " . $row[0] . " SET `nomnom`=0, `verified`=0; UPDATE " . $row[0] . " SET `nomnom`=1 WHERE `clan`=#clan";
by echoing $sql and running the queries returned through phpmyadmin without changing anything.
Here's a line that is echoed.
SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
It just for some reason isn't actually doing it when using
$conn->query($sql);
UPDATE 2
Figured out a way to make it work. Would mark my answer but I can't for 2 days...
Try this query
$sql = SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
This should work
Had to split the query into 3 separate queries. Full working code:
$conn = new MySQLi($servername, $username, $password, $dbname);
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan := (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1);";
$sql2 = "UPDATE " . $row[0] . " SET nomnom=0, verified=0;";
$sql3 = "UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $conn->error . '<br>';
$conn->query($sql2);
echo $conn->error . '<br>';
$conn->query($sql3);
echo $conn->error . '<br>';
}
} else {
echo 'query 0';
}
If anyone would like to post how to make this a proper multi_query without getting queries out of sync errors, be my guest. I cba doing that lol.
I'm attempting to select a query to use based on the number of rows returned by a test result.
$id = mysql_real_escape_string(htmlspecialchars($_POST['id']));
$result = "SELECT FROM Notifications WHERE UserID=$id";
$r = e_mysql_query($result);
$row = mysql_fetch_array($r);
$num_results = mysql_num_rows($result);
$result = '';
if ($num_results != 0) {
$result =
"SELECT U.UserID,U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U, Notifications N " .
" WHERE U.LocationID=0 " .
" AND N.UserID='$id'";
} else {
$result =
"SELECT UserID, FirstName, LastName," .
" DATE_FORMAT(BirthDate, '%m-%d-%Y') AS BirthDate " .
" FROM Users " .
" WHERE LocationID = 0 " .
" AND UserID ='$id'";
}
echo $result;
e_mysql_result($result); //Bastardized/homegrown PDO
if ($row = mysql_fetch_assoc($result)) {
$retValue['userInfo'] = $row;
...
I'm checking the Notifications table to see if the UserID exists there, if it doesn't it loads what does exist from the Users table, if it does, then it loads everything from the Notifications table.
I'm echoing out the $result and the proper statement is loaded, but it doesn't execute. When I run the concatenated query I get from the PHP preview, it returns just fine.
Before I had to if/else this, I was running the first query, loading everything from the Notifications table, and it was loading just fine. What am I missing?
You can do the whole thing with one query with a LEFT JOIN.
$query= "SELECT U.UserID, U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U " .
" LEFT JOIN Notifications N " .
" ON U.UserID = N.UserID " .
" WHERE U.UserID = '$id'";
You are missing execute a query with mysql_query() on all $result
Also change (query variable should be quoted) so change your all variables $id quoted
$result = "SELECT FROM Notifications WHERE UserID=$id";
to
$result = "SELECT FROM Notifications WHERE UserID='$id'";
$r = mysql_query($result);
Note :- mysql_* has been deprecated use mysqli_* or PDO
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
As part of my learning OOP PHP, I have made a database object that includes the following method:
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = static::instantiate($row);
}
return $object_array;
}
and I can use this to retrieve and access data from a single table, however when I try to use it with joined tables, the object only gives me the data from the primary table e.g.
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob";
$sql .= " FROM members AS m";
$sql .= " LEFT JOIN mbr_sections AS ms ON m.id = ms.member_id";
$sql .= " LEFT JOIN sections AS s ON ms.section_id = s.id";
$sql .= " ORDER BY s.organisation ASC, s.name ASC, m.lastName ASC, m.firstName ASC";
$sql .= " LIMIT {$per_page} ";
$sql .= " OFFSET {$pagination->offset()}";
$members = Member::find_by_sql($sql);
Using the above query the following code outputs nothing for the s.name field, but all the fields from the members table are correctly listed. I know that the MySQL query is accessing the data, as the ORDER BY statement is correctly sorting the output.
<?php foreach($members as $member): ?>
<tr>
<td><?php echo $member->name;?></td>
<td><?php echo $member->full_name();?></td>
<td><?php echo $member->getAge($member->dob);?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php endforeach; ?>
If I output $members with print_r($members) it only contains the data from the members table, how do I access the data retrieved from the other tables?
Thanks
You need to select them too here:
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob";
$sql .= " FROM members AS m";
$sql .= " LEFT JOIN mbr_sections AS ms ON m.id = ms.member_id";
$sql .= " LEFT JOIN sections AS s ON ms.section_id = s.id";
$sql .= " ORDER BY s.organisation ASC, s.name ASC, m.lastName ASC, m.firstName ASC";
$sql .= " LIMIT {$per_page} ";
$sql .= " OFFSET {$pagination->offset()}";
$members = Member::find_by_sql($sql);
You only selected name, id, firstName, lastName and dob.
Here is an example:
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob, mbr_sections.field_you_want, sections.*";