I have this query working as expected:
$sql = '
SELECT s.rowid
, f.fk_soc
, s.nom
, f.datef
, sc.fk_soc
, sc.fk_user
, u.rowid
, u.firstname
, u.lastname
FROM societe s
JOIN societe_commerciaux sc
ON s.rowid = sc.fk_soc
JOIN user u
ON sc.fk_user = u.rowid
LEFT
JOIN facture f
ON s.rowid = f.fk_soc
GROUP
BY s.rowid
HAVING MAX(f.datef) <= CURRENT_TIMESTAMP - INTERVAL '.$db->escape($dlo).' DAY
';
$resql = $db->query($sql);
if (!$resql) {
dol_print_error($db);
}
Background:
user - table with the user's first name and last name with primary identif. rowid
Societe - table with client names s.nom
primary identif. rowid
facture - table with client's invoices with date datef
and fk_soc
which is the client id (s.rowid)
societe_commerciaux - makes the connection which user is representative for each client by matching fk_soc
(which is actually s.rowid) with fk_user (which is u.rowid)
The working script lists all clients that don't have an invoice for a period set with the $dlo
and the name of the sales representative.
What I am trying to do is, to adjust the result to show clients without invoices for a particular sales representative i.e. the user.
I have a working script, that populates Dropdown select
<form>
<select name='repselect' onchange='showUser(this.value)'>
<option value="here comes the value for id of sales representative 1">Sales Representative name 1</option>
<option value="here comes the value for id of sales representative 2">Sales Representative name 2</option>
</select>
</form>
The ID in the Value field is bot rowid
from table users and fk_ser
from table societe_commerciaux.
I also have a working ajax script to populate the results.
The script is working as if I put print $sql;
in it, I can see the query after I select a user.
What I am struggling with is how to adjust the above query to show only the results for the sales representative selected from the drop-down. I am passing this id to a file 'script.php' in which I have $userid = intval($_GET['q']);
followed by the query. I can handle the output. It's just the query I am not able to adjust properly.
This query return users representative information from the clients who last invoice (facture) date is less than (CURRENT_TIMESTAMP - INTERVAL) or never had an invoice:
$sql = '
SELECT
u.rowid,
u.firstname,
u.lastname
FROM societe s
INNER JOIN societe_commerciaux sc ON s.rowid = sc.fk_soc
INNER JOIN user u ON sc.fk_user = u.rowid
WHERE s.rowid NOT IN (
SELECT f.fk_soc
FROM facture f
GROUP BY f.fk_soc
HAVING MAX(f.datef) > CURRENT_TIMESTAMP - INTERVAL ' . $db->escape($dlo) . ' DAY)
GROUP BY u.rowid, u.firstname, u.lastname
';
You should use prepared statement and no paste the parameter $dlo in a plain query, to prevent sql injection.