MYSQL Count Method - php

function sum($nomId){
$sql = "SELECT SUM(nomDetCantidad) FROM table2 where Id = $nomId";
$Resultado=$this->ProcesaSQLQueryList($sql);
if($Resultado>0){
foreach($Resultado as $key => $valor){
$cantidadTotal = $valor[0];
}
}
if($Resultado=='null'){$cantidadTotal=0;}
$sql = "UPDATE table1 SET nomCantidadTotal=$cantidadTotal,nomActualizado = NOW() WHERE nomId= $nomId";
return $this->ProcesaSQLQueryUpdate($sql);
and this is the function I call
function ProcesaSQLQueryList($SQLQuery){
$row= array();
if(!$this->link_mysql) $this->link_mysql = conectarManager();
if($res = mysql_query($SQLQuery,$this->link_mysql)){
while($r = mysql_fetch_array($res)){
$row[] = $r;
}
mysql_free_result($res);
return $row;
}else{
$this->last_error = $SQLQuery . " - " . mysql_error();
return -1;
}
}
So I sum up whatever I have in a field table 2 with the foreign key of table 1 then my result gets updated to the table 1 field but if I delete the fields in table 2 result wont get updated to 0 any suggestions I'm pretty sure this is an easy one but can't seem to find it

$sql = "SELECT SUM(nomDetCantidad) FROM table2 where nominaId = $nomId";
$Resultado = $this->ProcesaSQLQueryList($sql);
if ($Resultado > 0) {
foreach ($Resultado as $key => $valor) {
$cantidadTotal = $valor[0];
}
}
if ($cantidadTotal == '') {
$cantidadTotal=0.00;
}
$sql = "UPDATE table1 SET nomCantidadTotal=$cantidadTotal,nomActualizado = NOW() WHERE nomId = $nomId";
return $this->ProcesaSQLQueryUpdate($sql);
There! It was sending me a blank variable xD but fixed and there are more suitable ways to do it, I agree with Spencer but if a client wants a red swing he has to get a red swing you know? :) thanks for the help guys!

If you need a zero returned when there are no "matching" rows in table2, then wrap the return expression in an IFNULL function.
SELECT IFNULL(SUM(nomDetCantidad),0) FROM table2 ...
You could significantly reduce the amount of code you have, reduce the number of roundtrips to the database, and improve performance by doing all this work in a single UPDATE statement. You can use either a correlated subquery or an OUTER JOIN:
-- using a correleated subquery
UPDATE table t1
SET t1.nomActualizado = NOW()
, t1.nomCantidadTotal =
( SELECT IFNULL(SUM(t2.nomDetCantidad),0) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = t1.nomID
)
WHERE t1.nomId = $nomId
-- using an OUTER JOIN
UPDATE table1 t1
LEFT
JOIN (SELECT t2.Id, SUM(t2.nomDetCantidad) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = $nomId
GROUP BY t2.Id
) s
ON s.Id = t1.nomID
SET t1.nomCantidadTotal = IFNULL(s.nomCantidadTotal,0)
, t1.nomActualizado = NOW()
WHERE t1.nomID = $nomId
It's not at all clear why you need to store this total on table1, when you could derive it from table2 whenever you need it, without storing that value on table1 at all...
SELECT t1.nomId
, IFNULL((SELECT SUM(t2.nomDetCantidad) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = t1.nomID
),0) AS nomCantidadTotal
FROM table1 t1
WHERE t1.nomId = $nomId

Related

How to get results from mysqli_fetch_assoc with table aliases

I am pretty new to PHP and don't know how to get results from the mysqli_fetch_assoc() function if my select statement has table joins and those joins are handled with table aliases.
The code looks like following:
$sql = 'SELECT T1.update_text, T1.created_at, T2.username, T3.group_name FROM updates AS T1
INNER JOIN users AS T2 ON T2.user_id = T1.user_id_fk
INNER JOIN groups AS T3 ON T3.group_id = T1.group_id_fk
WHERE T1.user_id_fk = "1"';
And the PHP Code afterwards:
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
printf ("%s (%s)\n",$row["username"],$row["T1.created_at"]);
}
For the "username" row I am not getting an error, but nothing is displayed. For the second one I am getting an Index undefined error. (This is only a snippet of the code)
Change the SQL Query as following,
$sql = 'SELECT T1.update_text as update_text, T1.created_at as created_at, T2.username as username, T3.group_name as group_name FROM updates AS T1
INNER JOIN users AS T2 ON T2.user_id = T1.user_id_fk
INNER JOIN groups AS T3 ON T3.group_id = T1.group_id_fk
WHERE T1.user_id_fk = "1"';
then change the PHP code as following,
$result = $mysqli->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = $results->fetch_object())
{
echo $row->username.$row->created_at."<br/>";
}
}

PHP while loop returning only one row when SUM added to multiple JOIN query

I have a query like this:
$query = "SELECT a.sender_id,
a.recipient_id,
a.form_id, due_date,
a.completed,
f.name,
p.priority,
u.first_name,
u.last_name,
SUM(a.completed) as completed_sum
FROM form_assignments a
JOIN forms f ON (form_id = f.id)
JOIN users u ON (sender_id = u.id)
JOIN priorities p ON (priority_id = p.id)
WHERE recipient_id = '{$_SESSION['user_id']}'
ORDER BY due_date ASC";
And a while loop like this:
$assignment_count = (mysqli_num_rows($result));
$assignments_row = array();
while ($row = mysqli_fetch_array($result)) {
$sender = $row['first_name'] . ' ' . $row['last_name'];
$form_id = $row['form_id'];
$form_name = $row['name'];
$priority = $row['priority'];
$due_date = date('m/d/Y', strtotime($row['due_date']));
$completed = $row['completed'];
$not_done = $assignment_count - $row['completed_sum'];
}
And it's only returning one row. It seems my SUM(a.completed) as completed_sum is causing the issues because the query worked fine before I added it, but I want to add up all the values in completed to use in my $not_done variable.
Can anyone help clarify what I'm doing wrong?
When you use an aggregate function like SUM, all the results will be aggregated into one row unless you use a GROUP BY clause to segregate them. But it looks to me like you don't need a SUM in the first place. Your loop is subtracting this value from a total, so you just need the value from each row -- when you subtract them all you'll have subtracted the total. So just select a.completed rather than SUM(a.completed).
For $not_done, you need to initialize it before the loop:
$not_done = $assignment_count;
Then during the loop you should do a running subtraction:
$not_done -= $row['completed'];
Try this query :
SELECT
a.sender_id,
a.recipient_id,
a.form_id,
a.due_date,
a.completed,
f.name,
p.priority,
u.first_name,
u.last_name,
b.completed as completed_sum
FROM
form_assignments AS a
LEFT JOIN (
SELECT form_id,SUM(completed) FROM form_assignments GROUP BY form_id
) AS b ON (a.form_id = b.form_id)
LEFT JOIN forms AS f ON (form_id = f.id)
LEFT JOIN users AS u ON (sender_id = u.id)
LEFT JOIN priorities AS p ON (priority_id = p.id)
WHERE
recipient_id = '{$_SESSION['user_id']}'
ORDER BY due_date ASC

Create a filtered array from two MySQL table

Here's the situation.
I have two table in a DB: tblcustomfieldsvalues (for custom fields entry) and tblclients (contains client list).
tblcustomfieldsvalues has following data structure:
id => 10
relid => 13
data => somedataentry
id => 10
relid => 21
data => someotherdataentry
tblclients has following data structure:
id => 13
firstname => somename
lastname => somelastname
I have this code to create an array of relids which have id = 10:
$sql = mysqli_fetch_array(mysqli_query("SELECT * FROM `tblcustomfieldsvalues` WHERE `id` = '10'"));
$cids = array();
while ($row = $sql)
{
array_push($cids, $row['relid']);
}
Now that I have user IDs of those who have filled their custom fields with some data in the $cids array, how can I get those users details from tblclients?
Thanks in advance.
Sounds like you just need to use an INNER JOIN:
SELECT t2.*
FROM tblcustomfieldsvalues t
INNER JOIN tblclients t2 ON t.relid = t2.id
WHERE t.ID = 10
Good luck!
$sql = mysqli_fetch_array(mysqli_query("SELECT * FROM `tblcustomfieldsvalues` WHERE `id` = '10'"));
$cids = array();
while ($row = $sql)
{
//array_push($cids, $row['relid']);
$sql1 = mysqli_fetch_array(mysqli_query("SELECT * FROM `tblclients ` WHERE `id` = '$row['relid']'"));
while ($row1 = $sql1)
{
//echo your output
}
}
OR
SELECT * FROM
tblcustomfieldsvalues cv,tblclients c WHERE
cv.id = 10 and cv.id = c.id
Without knowing the table structure of tblclients I can't be sure, but it sounds like instead of doing separate queries and looping you could just use a join:
SELECT
*
FROM
tblcustomfieldsvalues
NATURAL JOIN tblclients
WHERE
id = 10

PHP MYSQL query - Strip away columns from response

Is it possible to strip away columns from the response I get in a query where I join 3 tables and need more or less all columns for the query itself so that some columns aren't visible in the response?
This is the query I have:
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_subApp.*,
tbl_tag.*
ISNULL(tbl_userDeviceNOTTag.userDevice_id) AS selected
FROM tbl_subApp2Tag
LEFT JOIN tbl_subApp
ON tbl_subApp.id = tbl_subApp2Tag.subApp_id
AND tbl_subApp.subApp_id = '".$sub."'
LEFT JOIN tbl_tag
ON tbl_tag.id = tbl_subApp2Tag.tag_id
LEFT JOIN tbl_userDeviceNOTTag
ON tbl_userDeviceNOTTag.tag_id = tbl_tag.id
AND tbl_userDeviceNOTTag.userDevice_id = '".$user."'
WHERE tbl_subApp2Tag.subApp_id = tbl_subApp.id
ORDER BY tbl_tag.name ASC ");
if(!$sth) echo "Error in query: ".mysql_error();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
You do not need to include columns in the result table, just because they are referenced elsewhere in the query. Just select the columns that you need.

MySQL return unique columname with 2 joins of equal table

I have the following query:
SELECT *
FROM scool
LEFT JOIN people as t1 ON t1.scool_fk=scool.id AND t1.lang_gk='en'
LEFT JOIN people as t2 ON t2.scool_fk=scool.id AND t2.lang_gk='fr'
...
(this is nonsense query, only for example)
With SELECT * it query returns french values
With SELECT t1.* it query returns english values
The only possible solution i know is
SELECT t1.name as name_en, t2.name as name_fr
This don't like me because i can't automatize the selects in my program
Is possible to be return all values from SELECT with tablename.columnname or other similar solution, for get values in php?
Use mysql_fetch_field and properties table and name:
<?php
mysql_connect("", "", "");
mysql_select_db("test");
$res = mysql_query("SELECT * FROM t_ai a1 CROSS JOIN t_ai a2 LIMIT 1") or die(mysql_error());
$names = array();
for ($i = 0; $i < mysql_num_fields($res); $i++) {
$meta = mysql_fetch_field($res, $i);
array_push($names, "$meta->table.$meta->name");
}
print implode($names, "\t") . "\n";
?>
$ php phptest.php
a1.id a2.id

Categories