help with a query - php

i have a function where i get the ratings of the selected user by id,
it gets the ratings from one type of things, the ratings of a diff type of things and then does a+b
i know it's not very optimized but i'm focus on making all work...
this i do it like this
function votos_usuario($id){
$previa = "SELECT id FROM preguntas WHERE id_usuario = '$id'";
$r_previo = mysql_query($previa);
$ids_p = '0, ';
while($items_previos = mysql_fetch_array($r_previo)){
$ids_p .= $items_previos['id'].", ";
//echo "ids pregunta usuario: ".$items_previos['id']."<br>";
}
$ids = substr($ids_p,0,-2);
//echo $ids;
$consulta = "SELECT valor FROM votos_pregunta WHERE id_pregunta IN ( $ids )";
//echo $consulta;
$resultado = mysql_query($consulta);
$votos_preguntas = 0;
while($voto = mysql_fetch_array($resultado)){
$votos_preguntas = $votos_preguntas + $voto['valor'];
}
//$votos_preguntas= 0;
//$votos_preguntas = mysql_query("SELECT SUM(valor) FROM votos_pregunta WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_usuario = '$id')");
$previa_r = "SELECT id FROM recetas WHERE id_usuario = '$id'";
$r_previo_r = mysql_query($previa_r);
$ids_r = '0, ';
while($items_previos_r = mysql_fetch_array($r_previo_r)){
$ids_r .= $items_previos_r['id'].", ";
//echo "ids pregunta usuario: ".$items_previos['id']."<br>";
}
$ids = substr($ids_r,0,-2);
$consulta_b = "SELECT valor FROM votos_receta WHERE id_receta IN ( $ids )";
//echo $consulta;
$resultado_b = mysql_query($consulta_b);
$votos_recetas = 0;
while($voto_r = mysql_fetch_array($resultado_b)){
$votos_recetas = $votos_recetas + $voto_r['valor'];
}
$total = $votos_preguntas + $votos_recetas;
return $total;
}
Now the Question,
how can i do it to get all users ordered by rating desc ???? i just can't see it :S

SELECT uid, SUM(Votes)
FROM (
SELECT p.id_usuario uid, SUM(vp.valor) votes
FROM preguntas p JOIN votos_pregunta vp ON p.id = vp.id_pregunta
GROUP BY p.id_usuario
UNION ALL
SELECT r.id_usuario uid, SUM(vr.valor) votes
FROM recetas r JOIN votos_receta vr ON r.id = vr.id_receta
GROUP BY r.id_usuario
) rs
GROUP BY uid
ORDER BY SUM(Votes) DESC
instead of your php loop and all the sub queries, you can use this single query to get what you want:
SELECT (
SELECT SUM(vp.valor)
FROM preguntas p JOIN votos_pregunta vp ON p.id = vp.id_pregunta
WHERE p.id_usuario = '$id')
+ (
SELECT SUM(vr.valor)
FROM recetas r JOIN votos_receta vr ON r.id = vr.id_receta
WHERE r.id_usuario = '$id'
)

Also, when you're only using the associative keys in the result array, using mysql_fetch_assoc() is much, much faster than mysql_fetch_array().
Same applies to using mysql_fetch_row() instead when you're just using the numerical keys.

Related

MySQL - Join part of query to a new query?

I've got the following code which queries a table. Then it uses the result to make another query. That result is then used to make a third query.
But how do I grab the userid field from the 2nd query in order to grab a name from a users table and join that to the result of the 3rd query?
Please note once I figure out the code I will convert this to a prepared statement. It's just easier for me to work with legacy code when figuring out queries.
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "SELECT opid, userid from audioposts WHERE audioid = $newaudio" ;
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$opid = $row[opid];
$opuserid = $row[userid];
$getreplies =
"SELECT * from audioposts ap WHERE opid = $opid AND opid
NOT IN (SELECT opid FROM audioposts WHERE audioposts.opid = '0' )";
$getreplyresults = $dblink->query($getreplies);
if ($getreplyresults->num_rows>0) {
while ($row = $getreplyresults->fetch_assoc()) {
$dbdata[]=$row;
}
}
}
}
}
} "SELECT * from audioposts ap WHERE opid = $opid AND opid
NOT IN (SELECT opid FROM audioposts WHERE audioposts.opid = '0' )";
$getreplyresults = $dblink->query($getreplies);
if ($getreplyresults->num_rows>0) {
while ($row = $getreplyresults->fetch_assoc()) {
$dbdata[]=$row;
}
}
}
}
}
}
echo json_encode($dbdata);
The result I need are rows of json encoded instances of $getreplyresults with the $row[userid] from the original result joined to each row.
Here's what I did in the end. Now I just have to figure out how to convert this to a prepared statement in order to avoid malicious injection.
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "
SELECT ap.audioid, ap.title, us.name FROM audioposts ap
INNER JOIN audioposts a2 ON a2.audioid = ap.opid
INNER JOIN users us ON us.id = a2.userid
WHERE ap.opid = $newaudio AND ap.opid <> '0'
";
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$dbdata[]=$row;
}}}}

I get a NULL value from var_dump when assigning a variable to an array in my select query

I have written a SELECT Query to concatenate a person's name and email address. I then want to echo this string.
Here is the code:
$sqldiv = "Select concat(p1.display_name, " - ", p1.user_email) AS Contact FROM wp_players p1
JOIN wp_divisions2 d2 ON p1.id = d2.div_player1_id
JOIN wp_leagues lg ON d2.div_league_ID = lg.league_id
WHERE d2.player_div_id = 2105
ORDER BY d2.div_wins DESC, d2.div_loss ASC, d2.div_rating DESC";
$resdiv = mysqli_query($link, $sqldiv);
$div = array();
while ($rowdiv = mysqli_fetch_array($resdiv)) {
$div[] = $rowdiv[0];
}
echo var_dump($div[0]);
If I use this SELECT QUERY it works:
$sqldiv = "Select p1.display_name FROM wp_players p1
JOIN wp_divisions2 d2 ON p1.id = d2.div_player1_id
JOIN wp_leagues lg ON d2.div_league_ID = lg.league_id
WHERE d2.player_div_id = 2105
ORDER BY d2.div_wins DESC, d2.div_loss ASC, d2.div_rating DESC";
$resdiv = mysqli_query($link, $sqldiv);
$div = array();
while ($rowdiv = mysqli_fetch_array($resdiv)) {
$div[] = $rowdiv[0];
}
echo var_dump($div[0]);
The only difference is that I am using concat. If I run the SELECT Query through SQL I get the output in a single string, which I assume is correct to set $div as an array.
What am I doing wrong?

Three SELECT and two jsons

I created a SELECT to get my communities.
And create two SELECTs to get the communities I'm following.
But I get just my communities.
I do not get the communities I'm following.
$user_id = $_GET["id"];
$row1 = array();
$row2 = array();
// get my communities
$res1 = mysql_query("SELECT * FROM communities where user_id = '$user_id'");
while($r1 = mysql_fetch_assoc($res1)) {
$row1[] = $r1;
}
// get "id" of my communities I'm following
$res = mysql_query("SELECT * FROM communities_follow where user_id = '$user_id'");
while($r = mysql_fetch_assoc($res)) {
$coid = $r["coid"];
// get my communities I'm following
$res2 = mysql_query("SELECT * FROM communities where id = '$coid'");
while($r2 = mysql_fetch_assoc($res2)) {
$row2[] = $r2;
}
}
$resp = array_replace_recursive($row1, $row2);
print json_encode( $resp );
The inner join will get you those communities only, where you are following:
SELECT c.* FROM communities c
INNER JOIN communities_follow cf ON c.id = cf.coid
WHERE cf.user_id = '$user_id';
Or, without a JOIN:
SELECT * FROM communities
WHERE EXISTS (SELECT 1 FROM communities_follow cf
WHERE c.id = cf.coid AND cf.user_id = '$user_id')
Try this sql.
SELECT * FROM communities c LEFT JOIN communities_follow cf ON c.user_id = cf.user_id where
cf.user_id = '$user_id';

Selecting only amount with values greater than 0 in sql

I have this table
The table contains amount with values that has both negative and positive signs. I was able to fetched the sum of positive amount but after the sumation I have zero values which I don't want to show - it fetched all values.
Objective: fetch sum of amount and return amount with no zero values.
What I tried so far
$ques = "select * from company";
$checks22y = sqlsrv_query($conn, $ques);
$row22y = sqlsrv_fetch_array($checks22y, SQLSRV_FETCH_ASSOC);
$daty = $row22y['BRSES_DATE']->format('Y-m-d H:m:i');
$com = $row22y['branch'];
$query = "SELECT distinct ".$limitresult." Member.Branch,Member.GL_No,Member.Ac_NO,Member.BRANCH+Member.GL_NO+Member.AC_NO
AS BRGLAC,Customer.Cust_No,Customer.Name,Group_Name,ID_CARD,Subgroup as subgroup2,
Cust_Type,Cust_Sex,Cust_Cat,Area_Code,Cust_Type,Dobirth,Address,Ref_No,Bank_VNO,Cust_Ca2,
nType,Group_Code FROM Member INNER JOIN CUSTACC ON Member.Branch = CustAcc.Branch AND
Member.GL_NO = CustACC.GL_No AND Member.AC_NO = CustACC.AC_No
INNER JOIN Customer ON Member.Branch = Customer.Branch ".$branchid." AND Member.Cust_No = Customer.Cust_No ".$accnos." WHERE
CUSTACC.Exp_Date < '$daty' AND MEMBER.Gl_NO IN (SELECT Coa.GL_NO FROM Coa WHERE Product = 'S' ) AND cust_type IN ('IND','GRP','MEM') ";
$check = sqlsrv_query($conn, $query);
$i = 1;
while($rows = #sqlsrv_fetch_array( $check, SQLSRV_FETCH_ASSOC)) {
$ac = $rows['Ac_NO'];
$br = $rows['Branch'];
//Second sub query
$get ="select ac_no, gl_no, SUM(amount) as OutBalance,MAX(Batch_Date) AS Last_Trx2 from memtrans where gl_no like '2001%'
and ac_no='$ac' group by ac_no, gl_no HAVING SUM(amount) > 0
";
$check2 = sqlsrv_query($conn, $get);
$rowb = sqlsrv_fetch_array( $check2, SQLSRV_FETCH_ASSOC);
//Third sub query, OD history
$od = "select od_limit from custacc where ac_no='$ac' and od_limit > '0'";
$odc = sqlsrv_query($conn, $od);
$rowbo = sqlsrv_fetch_array( $odc, SQLSRV_FETCH_ASSOC);
}
The outcome
If you look at the Outstanding Balance you will see zero values appearing.
The secon sub query is where the fetching of Outstanding Balance took place.
Just solved it.
Here is the query I later used:
SELECT distinct ".$limitresult." member.Branch,Member.GL_No,Member.Ac_NO,Member.BRANCH+Member.GL_NO+Member.AC_NO
AS BRGLAC,Customer.Cust_No,Customer.Name,Group_Name,ID_CARD,Subgroup as subgroup2,Cust_Type,Cust_Sex,Cust_Cat,Area_Code,Cust_Type,Dobirth,Address,Ref_No,Bank_VNO,Cust_Ca2,nType,Group_Code, SUM(memtrans.amount) as OutBalance,MAX(memtrans.Batch_Date) AS Last_Trx2,company.BRSES_DATE, company.branch, CustACC.od_limit FROM Member INNER JOIN CUSTACC ON Member.Branch = CustAcc.Branch AND Member.GL_NO = CustACC.GL_No AND Member.AC_NO = CustACC.AC_No INNER JOIN Customer ON Member.Branch = Customer.Branch AND Member.Cust_No = Customer.Cust_No INNER JOIN memtrans ON memtrans.ac_no = member.ac_no INNER JOIN company ON company.branch = member.branch ".$branchid." ".$accnos." WHERE CUSTACC.Exp_Date < company.BRSES_DATE AND CUSTACC.od_limit > '0.00' AND MEMBER.Gl_NO IN (SELECT Coa.GL_NO FROM Coa WHERE Product = 'S' ) AND cust_type IN ('IND','GRP','MEM') group by memtrans.ac_no, memtrans.gl_no,company.branch, member.branch, member.gl_no,Member.ac_no,
Customer.cust_no, Customer.name, Customer.group_name,Customer.id_card,Customer.subgroup,Customer.cust_type,
Customer.cust_sex, Customer.cust_cat,Customer.area_code,Customer.dobirth,Customer.address,Customer.ref_no, Customer.Bank_VNO,Customer.cust_ca2,Customer.ntype,Customer.group_code,company.BRSES_DATE,CUSTACC.od_limit HAVING SUM(memtrans.amount) > 0)
Thanks guys. From a grateful heart.

Get highest sum value from two tables

Here is my code:
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
<tr> <?php echo $sum; ?></tr>
}while($row_query1 = mysql_fech_assoc($result));
I need to get the highest value of $sum from this loop. Can anyone help?
You can do like this.. take a temporary variable($temp) which can have check upon the sum variable($sum).
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
$temp = 0;
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
if($temp < $sum)
$temp = sum;
echo "<tr>$sum</tr>";
}while($row_query1 = mysql_fech_assoc($result));
echo "maximum sum :".$temp;
I would advice doing a JOIN instead of performing the sub queries yourself:
select user, sum(column) + sum(column1) as total
from table1
INNER JOIN table2 ON names = user
GROUP BY user
The rest should be straightforward in code.

Categories