Displays WHERE for two conditions in the same column - php

-----------------------------------------------------
| id | posts_id | users_id | ratings |
-----------------------------------------------------
| 1 | 7 | 20 | 5 |
| 2 | 8 | 20 | 3 |
| 3 | 7 | 21 | 4 |
-----------------------------------------------------
Table name: mytable
\I want to make sure that ratings between posts_id and users_id are matched on the same column.
$query = $conn->query("SELECT ratings FROM mytable WHERE posts_id=7 and users_id=20");
$row = $query->fetch_array();
echo $row['ratings'];
This query does not work. I know there must be something wrong.
I want to get results: 5
What is the best query to show ratings?
----------------UPDATE-----------------------------
Sorry, my first problem lies with the connection, and now it is resolved.
But now there is a new problem.
I want to display the total sum of the rating results.
My new code
$Rate = $conn->query("SELECT * FROM mytable WHERE posts_id=7");
while ($Rated = $Rate->fetch_array()) {
echo $Rated['ratings'] + $Rated['ratings'];
}
For example on posts_id=7
Here I expect 5 + 4 = 9
But my code results exactly 54 + 54
How to fix this code?

For the updated question, this code should be work. We can use sum() function. Check here sum() function
$Rate = $conn->query("SELECT sum(ratings) as ratings FROM mytable WHERE posts_id=7");
while ($Rated = $Rate->fetch_array()) {
echo $Rated['ratings'];
}

Related

SQL query returns one row too few

SOLUTION: Make sure you don't 'use up' any $responses->fetch_assoc()s before the while loop.
I performed mysqli_fetch_array($responses);.
In php I have this sql query (simplified for your convenience, but the problem remains)
$sql = "SELECT id, content FROM responses ORDER BY RAND()";
$responses = $conn->query($sql);
where the responses table looks like this:
+----+----------+--------+------+
| id | content | userId | part |
+----+----------+--------+------+
| 4 | peewee | 31 | 1 |
| 5 | tallinn | 31 | 1 |
| 6 | dewey | 31 | 1 |
| 7 | stanford | 31 | 1 |
+----+----------+--------+------+
That doesn't format properly so all you need to know is that the id and content rows are different for each entry while the rest is the same for each.
The problem is, when I do a while loop on $responses like so:
while ($row = $responses->fetch_assoc()) {
$responseId = $row["id"];
$content = $row["content"];
echo " id: ".$responseId;
echo " content: ".$content;
}
I always get 1 record fewer than there are. In this case, since there are 4 rows, I would only see 3 echoed. However, it is not always the same 3, nor are they in the same order. If I remove the ORDER BY RAND() clause, then it is always the first record which is left out.
Thanks in advance
Cheers

How can I optimize query to run faster (Query inside a Query)

This query will take around 5 seconds to complete. I mean when I refresh or navigate to the page it will take 5 seconds to complete the browser loading and to display the total counts.
Here is what I want to achieve, FIRST is to get the MAX value of the systemID (ID) based on the empID.
But before the First query ends I made another query the will get the row where the empID has a JUMP value on the eStatus col.
This is to compare the year difference of the latest data startDate of the empID and to his previous JUMP endDate.
Here is my table
---|-------|-----------|------------|---------
ID | empID | startDate | endDate | eStatus
---|-------|-----------|------------|---------
1 | 10 | 2001-1-31 | 2001-12-31 |
2 | 10 | 2002-1-31 | 2002-12-31 |
3 | 22 | 2001-1-31 | 2001-12-31 |
4 | 10 | 2003-1-31 | 2003-12-31 | JUMP
5 | 10 | 2004-1-31 | 2004-12-31 |
6 | 22 | 2002-1-31 | 2002-12-31 | JUMP
7 | 10 | 2005-1-31 | 2005-12-31 |
8 | 22 | 2003-1-31 | 2003-12-31 |
9 | 22 | 2004-1-31 | 2004-12-31 |
10 | 10 | 2006-1-31 | 2006-12-31 | JUMP
11 | 10 | 2007-1-31 | 2007-12-31 |
12 | 10 | 2008-1-31 | 2008-12-31 |
13 | 10 | 2009-1-31 | 2009-12-31 | JUMP
14 | 10 | 2010-1-31 | 2010-12-31 |
15 | 10 | 2011-1-31 | 2011-12-31 |
the First query will get the max ID by group of empID.
---|-------|-----------|------------|---------
ID | empID | startDate | endDate | eStatus
---|-------|-----------|------------|---------
15 | 10 | 2011-1-31 | 2011-12-31 |
9 | 22 | 2004-1-31 | 2004-12-31 |
the Second query will get the empID row that has a JUMP data on the eStatus Col
---|-------|-----------|------------|---------
ID | empID | startDate | endDate | eStatus
---|-------|-----------|------------|---------
4 | 10 | 2003-1-31 | 2003-12-31 | JUMP
6 | 22 | 2002-1-31 | 2002-12-31 | JUMP
10 | 10 | 2006-1-31 | 2006-12-31 | JUMP
13 | 10 | 2009-1-31 | 2009-12-31 | JUMP
6 | 22 | 2002-1-31 | 2002-12-31 | JUMP
Now I can compute the date difference from startDate of 1st query and enddate of 2nd query. If it is greater than 2 the it will count to my final count.
THANK YOU SO MUCH IN ADVANCE and KEEP SAFE.
Here is my code:
<?php
$counterA= 0;
$counterB= 0;
$finalCount = 0;
$result = mysqli_query($con,"SELECT empID,endDate FROM tablerecord
WHERE ID IN (SELECT MAX(ID) FROM tablerecord GROUP BY empID)");
while ($row=mysqli_fetch_assoc($result )) {
$counterA++; //count how many result based on the above query
$emp_max = $row['empID']; //Get emp ID based on max ID
endDate_result = $row['endDate']; //Get endDate based on max ID
$resultPrevious=mysqli_query($con,"SELECT empID,startDate FROM tablerecord
WHERE empID = '$emp_max' AND eStatus = 'JUMP' ");
while ($rowPrevious=mysqli_fetch_assoc($resultPrevious)) {
$counterB++; //count how many result based on the above query
$dateA=date_create($rowPrevious['startDate']);
$dateB=date_create($endDate_result);
$diff2=date_diff($dateA,$dateB);
$numLenght = $diff2->y;
if ($numLenght > 2) {
$finalCount++;
}
}
}
echo $counterA;
echo "<br>";
echo $counterB;
echo "<br>";
echo $finalCount;
?>
if I understand correctly, what you want is to select all data that have eStatus value jump.
why not simply SELECT empID,startDate FROM tablerecord WHERE empID IN(SELECT MAX(ID) FROM tablerecord) AND eStatus = 'JUMP'?
or, if you want the unique value of empID, SELECT empID,startDate FROM tablerecord WHERE empID IN(SELECT DISTINCT(ID) FROM tablerecord) AND eStatus = 'JUMP'
all my query above will not produce any result
you might want to try multiple select in your query for a crude way to get it all in one go
select * from tablerecord where empID in(SELECT empID FROM tablerecord WHERE ID IN (SELECT MAX(ID) FROM tablerecord group by empID)) and eStatus = 'JUMP'
in this way, you only query the DB one time and the rest can be done with your PHP code
I would use this query to get all needed data :
# Get first and last jump for each empID
SELECT *
FROM tablerecord t1
WHERE t1.ID = (
SELECT MIN(t2.ID)
FROM tablerecord t2
WHERE t1.empID==t2.empID
) or t1.ID = (
SELECT MAX(t3.ID)
FROM tablerecord t3
WHERE t1.empID==t3.empID
)
And then some PHP to run through, comparing each pairs
$result = mysqli_query($con,"the_previous_query....");
$row_to_compare_with =false;
while ($row=mysqli_fetch_assoc($result )) {
if ($row_to_compare_with == false) {
$row_to_compare_with = $row;
} else {
// Compare $row_to_compare_with with $row, both having same empId
// do your thing here...
$row_to_compare_with = false;
}
}

do the math for each data in database sql post result to database in php

I'd like to fetch data from my 2 sql database and do some math and post the result in database
let's say my table1 is like this
+---+---+----------------------------+
| A | B | C |
+---+---+----------------------------+
| 2 | 9 | result from A*B*D*E in php |
| 1 | 8 | result from A*B*D*E in php |
| 4 | 7 | result from A*B*D*E in php |
| 3 | 6 | result from A*B*D*E in php |
| 6 | 5 | result from A*B*D*E in php |
| 6 | 5 | result from A*B*D*E in php |
| 5 | 4 | result from A*B*D*E in php |
+---+---+----------------------------+
and my table2 is like this
+---+----+
| D | E |
+---+----+
| 1 | 9 |
| 2 | 7 |
| 3 | 8 |
| 4 | 6 |
| 5 | 5 |
| 6 | 3 |
| 7 | 2 |
+---+----+
so far what i've done
// database connection
include_once("config.php");
// Query
$query = mysqli_query($conn, "SELECT * FROM table1");
$query2 = mysqli_query($conn, "SELECT * FROM table2");
//Source1
while($user_data1 = mysqli_fetch_array($query))
{
$A[] = $user_data1['A'];
$B[] = $user_data1['B'];
}
//Source2
while($user_data2 = mysqli_fetch_array($query2))
{
$D[] = $user_data2['D'];
$E[] = $user_data2['E'];
}
foreach (array_combine($A, $B) as $ValueA=> $ValueB)
{
foreach (array_combine($D, $E) as $ValueD=> $ValueE)
{
$result1 = $ValueA*$ValueB*ValueD*ValueE;
$val = 0.123;
$result2[] = $result1*$val;
}
$final result = min($result2);
echo round($final result, 2);
unset($result2);
}
I haven't inserted the database yet
still echoing for debug if the math is correct
somehow this code found some bug
for example using my database the final result only echo/showing 6 math result
because in table1 row 5 and 6 has same data
btw of course in my table1 and 2 has primary key
To change C in this case, you don't even need PHP. To UPDATE a value in MySQL with multiple tables just add them with a , when selecting the tables, like this:
UPDATE table1,table2 SET C = table1.A * table1.B * table2.D * table2.E WHERE C IS NULL;
Executing this code once will update all rows so that C = A*B*D*E as wanted where C is not yet set or NULL. If you want to update all rows you can just remove the WHERE condition
Note: Sometimes (at least for me) SQL will give a warning when having no WHERE condition in the SQL query. To bypass this just add WHERE 1=1 at the end.
Just for my understanding: you want to calculate a value for your calculation you need some data from table 1 that is clear, but also from table2 But which one? I guess you want to use the data from the same row ( so row 1 from table1 and row 1 from table2, row 2 from table 1 and row 2 from table2 ) right? Now you have an problem because when you make a select * from table You do not know in which order they give back from your database. Most time it may be the same order as you have input them, but there is no garantie. You have sayed you have an primary key on each table, how have you defined them? I guess you may have a id column, so you can join your table on that id?

Query multiple Tables using PHP and MySQL

I am currently working on a system. This is how my tables look like:-
sales table:-
ID | avatar | ident
-------------------------------------
1 | img/photo11 | CCS7771
2 | img/photo32 | INL0987
3 | img/photo32 | INL0987
4 | img/photo6 | URS8827
5 | img/photo32 | INL0987
6 | img/photo9 | NSU8837
7 | img/photo3 | PPP9998
kudos table:-
ID | sale_id | ident_id
-------------------------------------
1 | 1 | INL0987
2 | 4 | INL0987
3 | 7 | INL0987
4 | 1 | KKU8837
5 | 1 | URS8827
6 | 4 | SHD8837
So I have this like system, and when A user press the like button to the table row, it stores the sales.id and sales.ident into another tables named kudos, like you can see above.
I am trying to query to see how many people have given kudos for each post. You can see in the above tables, example: the sales.id 1 has gotten 3 kudos from INL0987, KKU8837 and URS8827. I have tried a few different ways, but I cant seems to find a solution for this. This is what I have tried:
/* $resultSet = $mysqli->query("SELECT kudos.sale_id as makesName, sales.ident AS modelsName from kudos,sales where kudos.sale_id = '42' AND kudos.ident_id = sales.ident"); */
$resultSet = $mysqli->query("SELECT kudos.sale_id as TheID, sales.ident AS TheIdent from kudos,sales where kudos.sale_id = '42' AND sales.id = kudos.sale_id");
echo $resultSet->num_rows;
while ($rows = $resultSet->fetch_assoc()) {
$iid = $rows['TheID'];
$iident = $rows['TheIdent'];
echo "<br><br>TheID: $iid";
echo "<br>TheIdent: $iident";
}
Can someone help me out here? I can figure out what I am doing wrong.
I am trying to query to see how many people have given kudos for each post
I think you just want aggregation:
select sale_id, count(*) no_kudos
from kudos
group by sale_id
If you also want to include sale_ids that have no match in kudos, then you can use a correlated subquery:
select id, (select count(*) from kudos k where k.sale_id = s.id) no_kudos
from sales s

DISTINCT * is not withdrawing the duplicity (MYSQL)

i already done everything to remove this duplicity on the database
On selecting a checkbox on the sectio "Bairros" i utilized as Array
for($m=0; $m<count($_POST["bairros"]); $m++){// LOOP 1
$pesquisar=($_POST["bairros"][$m]);
//Copy bairros(Array) and esporte (POST)
$query = "SELECT DISTINCT * FROM cadastro WHERE
(esporte1 = '".$_POST["esportes"]."' OR
esporte2 = '".$_POST["esportes"]."' OR
esporte3 = '".$_POST["esportes"]."' OR
esporte4 = '".$_POST["esportes"]."')
AND
(bairro1 = '".$pesquisar."' OR
bairro2 = '".$pesquisar."' OR
bairro3 = '".$pesquisar."' OR
bairro4 = '".$pesquisar."')
AND
ativarAparecer='sim' ORDER BY nomeCompleto ASC LIMIT 20";
$esporte= new consultar();
$esporte->executa($query);
//Loops
for($l=0; $l<$esporte->nrw; $l++){ //LOOP 2
echo $esporte->data["nomeCompleto"]."<br />";
$esporte->proximo();
} //close LOOP2
} //close LOOP1
Detail: this function object oriented, I believe that i'm doing something wrong at SQL or MYSQL, perhaps something is missing there.
SELECT DISTINCT *
Stop There. DISTINCT * can do what? Duplicate of what? it cant do that. Give it a field name to see unique values.
For example
SELECT DISTINCT nomeCompleto
Let's break this down. The DISTINCT clause will return unique sets based on the selected columns.
Let's say you have a table:
a | b | c
=========
1 | 2 | 3
1 | 1 | 3
1 | 2 | 4
Now if you SELECT DISTINCT a FROM table, you would get:
1
but if you SELECT DISTINCT a, b FROM table, you would get:
a | b
=====
1 | 2
1 | 1
That's because {1,2} is different from {1,1}, even though the a column is the same between those two sets.
Obviously, doing SELECT DISTINCT * FROM table would give you the original table because it uses all three columns as a "composition" of the unique set. If we amended the table to look like this:
a | b | c
=========
1 | 2 | 3
1 | 1 | 3
1 | 2 | 4
1 | 2 | 3
Then your result of SELECT DISTINCT * FROM table would give:
a | b | c
=========
1 | 2 | 3
1 | 1 | 3
1 | 2 | 4
because of the duplicate result set of {1, 2, 3}. However, since most tables have an auto-incrementing identifier as the primary key, there is almost always no difference between SELECT * and SELECT DISTINCT *.
Perhaps you're looking to GROUP BY a certain column?
How would I be using GROUP this in my script? Column that there are several equal records are this bairro, bairro2, bairro3, bairro4. Inside it is in numbers
bairro1 | bairro2 | bairro3 | bairro4
14 | 14 | 15 | 27
34 | 15 | 14 | 30
27 | 45 | 12 | 14

Categories