MySQL automaticly delete duplicate row - php

I want to display all data from the function below, however whenever the function is called, MySQL only returns one row if there are duplicates. What is the problem with my SQL Query?
$sql_response1 = "SELECT *
FROM ".TABLE_PREFIX."tests_answers A, ".TABLE_PREFIX."tests_results R, ".TABLE_PREFIX."members M
WHERE A.question_id=".$q_id." AND R.result_id=A.result_id AND R.final_score<>'' AND R.test_id=".$_GET['tid']." AND M.member_id =A.member_id AND M.member_id IN ($in_text)
GROUP BY A.answer ORDER BY A.answer";
$result_responsed = mysql_query($sql_response1, $db);
while ($row_answer = mysql_fetch_array($result_responsed)) {
$x++;
$response_member = $row_answer['first_name'];
$response_answer = $row_answer['answer'];
$response_department = $row_answer['department_name'];
$x--;
$objPHPExcel->getActiveSheet()->setCellValue(A.$x, $response_answer.' '.'('.$response_member.' - '.$response_department.')');
$x++;
}
Let's say that the column result_id has two instances of the value foo, only one row will be returned. How do I show ALL results without MySQL truncating duplicate rows?

Your problem is that GROUP BY groups together - basically, collapses - all rows with the specified value in common. In this case, that means it will show only one row with a given value for A.answer.

You're using the GROUP BY query which will return only one result and it will remove duplicates. If you're trying to sort the results use ORDER BY without using GROUP BY as well.
$sql_response1 = "SELECT *
FROM ".TABLE_PREFIX."tests_answers A, ".TABLE_PREFIX."tests_results R, ".TABLE_PREFIX."members M
WHERE A.question_id=".$q_id." AND R.result_id=A.result_id AND R.final_score<>'' AND R.test_id=".$_GET['tid']." AND M.member_id =A.member_id AND M.member_id IN ($in_text)
ORDER BY A.answer";
For more background information on the GROUP BY function check out the informative page on W3Schools

Related

php pg_fetch_array only show first result

i query to check if a point(input) is intersect with polygons in php:
$sql1="SELECT ST_intersects((ST_SetSRID( ST_Point($startlng, $startlat),4326))
, zona_bahaya.geom) as intersek
FROM zona_bahaya";
$query1 = pg_query($conn,$sql1);
$check_location = pg_fetch_array($query1);
if (in_array('t',$check_location)) {
dosemthing1;}
else {dosomething2;}
it's work peroperly before i update the data
after data updated, it's only show the first row when i check the pg_fetch_array result. here is the result {"0":"f","intersek":"f"} .
i try to check from pgadmin and it's can show 8 result (1 true(intersected) and 7 false(not intersect)) using updated data with this query:
SELECT ST_intersects((ST_SetSRID( ST_Point(110.18898065505843, -7.9634510320131175),4326))
, zona_bahaya.geom) as intersek
FROM zona_bahaya;
to solve it, i order the query result descended so the 'true' gonna be the first like this:
order by intersek desc
anybody can help me to findout way it just only show the first row???
here some geom from STAsText(zonabahaya.geom) not all of them : MULTIPOLYGON(((110.790892426072 -8.19307615541514,110.791999687385 -8.19318330973567,110.794393723931 -8.1927980624753,110.794586347561 -8.19205508561603,110.795329324421 -8.19120203811094,110.796540101525 -8.19023891996003,110.797503219676 -8.18933083713203,110.798576408472 -8.18919324882476,110.79929186767 -8.18957849608512,110.800337538805 -8.19059664955894,110.800585197758 -8.19150473238694,110.80022746816 -8.19238529755349,110.799787185576 -8.19290813312112,110.799589319279 -8.19300706626968,110.798788231202 -8.19299429992581,110.798537293576 -8.19311976873883,110.79850269889 -8.1933090511224,110.798620939451 -8.19433728092441)))
In order to filter only the records that intersect you have to use ST_Intersects in the WHERE clause:
SELECT *
FROM zona_bahaya
WHERE ST_Intersects(ST_SetSRID(ST_Point(110.18, -7.96),4326),zona_bahaya.geom);
Since you're dealing with points and polygons, perhaps you should take a look also at ST_Contains.
In case you want to fetch only the first row you must set a limit in your query - either using LIMIT 1 or FETCH FIRST ROW ONLY -, but it would only make sense combined with a ORDER BY, e.g.
SELECT *
FROM zona_bahaya
JOIN points ON ST_Intersects(points.geom,zona_bahaya.geom)
ORDER BY gid
FETCH FIRST ROW ONLY;
Demo: db<>fiddle

Relational table query gives me a null value in the field 'id' in table

I am creating a query and I used the LEFT JOIN to join two tables. But I'm having trouble in getting the fb_id value from the table, it gives me an empty result. Here is my code:
$sql = "SELECT * FROM tblfeedback a LEFT JOIN tblreply b ON a.fb_id = b.fb_id WHERE a.fb_status = 1 ORDER BY a.fb_id DESC";
$res = $con->query($sql);
....
....
The query above would give me a result like this :
I think that's why I don't get the fb_id value is because the last column is null. How do I get the value of fb_id from the first column? Thanks. I am really having trouble with this. I hope someone can enlightened my mind.
You should give an alias to the column in the parent table, because the column names are the same in both tables. When fetch_assoc() fills in $row['fb_id'], it gets the last one in the result row, which can be NULL because it comes from the second table.
SELECT a.fb_id AS a_id, a.*, b.*
FROM tblfeedback a
LEFT JOIN tblreply b ON a.fb_id = b.fb_id
WHERE a.fb_status = 1
ORDER BY a_id DESC
Then you can access $row['a_id'] to get this column.
More generally, I recommend against using SELECT *. Just select the columns you actually need. So you can select a.fb_id without selecting b.fb_id, and it will always be filled in.
Because you are using a left join, the 2 rows in your result set image are the rows from tblfeedback whose fb_id were not found in tblreply. We know this is true because all the tblreply columns in the result set are null.
With that said, its not real clear what you are asking for. If you are asking how you access the tblfeedback.fd_id column from your query via php, you can use the fetch_array method and use the 0 index.
$sql = "SELECT * FROM tblfeedback a LEFT JOIN tblreply b ON a.fb_id = b.fb_id WHERE a.fb_status = 1 ORDER BY a.fb_id DESC";
$res = $con->query($sql);
while($row = $res->fetch_array()) {
echo "fb_id: " . $row[0] . "<br>";
}

Why do i double my display in json

So i fetch my data from two tables in my php and encode it in one json object. I got everything i needed except that it doubles the display. And my teamone is located in the matches tables. instead of starting from array 0, it starts after the schedules tables. Which is array 7. I dont know why this happen.
Here is my php.
$sql = "SELECT * from schedule, matches;";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
$result = mysqli_query($con,$sql);
$response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("start"=>$row[4],"end"=>$row[5],"venue"=>$row[6], "teamone"=>$row[8], "teamtwo"=>$row[9],
"s_name"=>$row[17]));
}
echo json_encode (array("schedule_response"=>$response));
mysqli_close($con);
?>
Here is my display. As you can see there are four displays but in my database it only has 2. It doubles the display. How do i fix this? Thanks
{ "schedule_response":[
{"start":"2016-11-10 00:00:00","end":"2016-11-04 00:00:00","venue":"bbbb","teamone":"aaa","teamtwo":"bbb",
"s_name":"hehehe"},
{"start":"2016-11-23 00:00:00","end":"2016-11-24 00:00:00","venue":"bbbbbbbb","teamone":"aaa","teamtwo":"bbb",
"s_name":"hehehe"},
{"start":"2016-11-10 00:00:00","end":"2016-11-04 00:00:00","venue":"bbbb","teamone":"ehe","teamtwo":"aha",
"s_name":"aaa"},
{"start":"2016-11-23 00:00:00","end":"2016-11-24 00:00:00","venue":"bbbbbbbb","teamone":"ehe","teamtwo":"aha",
"s_name":"aaa"}]}
I need to get the teamone, teamtwo and s_name values from the matches while i need the start, end and the venue from the schedule table in one query.
Schedule table
Matches Table
Because of your SQL query, you should not forget to perform some form of a grouping (the way you select results from both table defines that):
$sql = "SELECT * from schedule s, matches m GROUP BY s.id"; //I assume that your table schedule has an `id`
Or, you can rework the query to be more readable:
$sql = "SELECT s.*, m.* FROM schedule s
INNER JOIN matches m ON m.schedule_id = s.id
GROUP BY s.id"; //I assume that you have such database design that you have defined foreign key on table `matches`.
Of course, the INNER JOIN above could be LEFT OUTER JOIN - it all depends on your database design.
I think it is the problem with mysqli_fetch_array().
Can you please change mysqli_fetch_array() to mysqli_fetch_assoc()

Left join MySql/PHP

Whilst populating a table based on ids and labels from different tables, it appeared apparent there must potentially be a better way of achieving the same result with less code and a more direct approach using LEFT JOIN but i am puzzled after trying to work out if its actually capable of achieving the desired result.
Am i correct in thinking a LEFT JOIN is usable in this instance?
Referencing two tables against one another where one lists id's related to another table and that other table has the titles allocated for each reference?
I know full well that if theres independent information for each row LEFT JOIN is suitable, but where theres in this case only several ids to reference for many rows, i just am not clicking with how i could get it to work...
The current way i am achieving my desired result in PHP/MySQL
$itemid = $row['item_id'];
$secid = mysql_query(" SELECT * FROM item_groups WHERE item_id='$itemid' ");
while ($secidrow = mysql_fetch_assoc($secid)) {
//echo $secidrow["section_id"]; //testing
$id = $secidrow["section_id"];
$secnameget = mysql_query(" SELECT * FROM items_section_list WHERE item_sec_id='$id' ");
while ($secname = mysql_fetch_assoc($secnameget)) {
echo $secname["section_name"];
}
}
Example of the data
Item groups
:drink
:food
:shelf
Item List
itemId, groupId
Group List
groupId, groupTitle
The idea so outputting data to a table instead of outputting "Item & Id Number, in place of the ID Number the title actually appears.
I have achieved the desired result but i am always interested in seeking better ways to achieve the desired result.
If I've deciphered your code properly, you should be able to use the following query to get both values at the same time.
$itemid = $row['item_id'];
$secid = mysql_query("
SELECT *
FROM item_groups
LEFT JOIN items_section_list
ON items_section_list.item_sec_id = item_groups.section_id
WHERE item_id='$itemid'
");
while ($secidrow = mysql_fetch_assoc($secid)) {
//$id = $secidrow["section_id"];
echo $secidrow["section_name"];
}

MySql displaying results in same order no matter "array-order"

I am using "solr" search engine to query an index for classifieds that match a given criteria. The results are the ID:numbers of the classifieds, which I then use to find all matches in a MySql database with those ID:s.
The ID:s returned are put into an array.
As you can see below the array is imploded.
Then I use the "IN" to find all matches.
$solr_id_arr_imploded = implode("', '", $solr_id_arr);
$query = "SELECT mt.*, $sql_tbl.* FROM classified mt LEFT JOIN $sql_tbl ON
$sql_tbl.classified_id = mt.classified_id WHERE mt.ad_id IN ('$solr_id_arr_imploded')";
$sql_tbl is the category chosen by the user, in this case lets say it is "cars".
My problem is this:
I have the ID:numbers in an order (inside the array), but MySql doens't "care" about this order. MySql displays the oldest item first no matter what order the array is in.
So here is one same query displayed with two different "array-directions":
SELECT mt.*, fordon.* FROM classified mt LEFT JOIN fordon ON fordon.classified_id = mt.classified_id WHERE mt.ad_id IN ('Bmw_520i_Svensksald_784332731', 'Bmw_M3_Svensksald_755599519', 'Bmw_M3_E46_Full-utrustad_338210082')
SELECT mt.*, fordon.* FROM classified mt LEFT JOIN fordon ON fordon.classified_id = mt.classified_id WHERE mt.ad_id IN ('Bmw_M3_E46_Full-utrustad_338210082', 'Bmw_M3_Svensksald_755599519', 'Bmw_520i_Svensksald_784332731')
As you can see the ID:s are reversed in the second query above... But they are still displayed in the same order anyways. Why?
Should I use some other method of finding all MySql matches with ID:s from an array?
Ideas?
Thanks
This should do it:
SELECT mt.*, $sql_tbl.* FROM classified mt
LEFT JOIN $sql_tbl
ON $sql_tbl.classified_id = mt.classified_id
WHERE mt.ad_id IN ('$solr_id_arr_imploded')
ORDER BY FIELD(mt.ad_id,'$solr_id_arr_imploded')
See Order By Field in Sorting Rows.
MySQL will return the data in the order it "wants" (I suppose it'll be the order of the clustered index, or something like that), if you do not specify an order by clause.
If you want to change the order in which MySQL returns the results, you'll have to add an order by clause.
If that's not possible in your case, you'll have to re-order the elements from the PHP code -- for instance, instead of displaying the results from what MySQL returns, you should iterate over the list of ids returned by Solr, and display the results starting from there.
Basically, you'll first execute the MySQL query to fetch the results :
SELECT mt.*, fordon.*
FROM classified mt
LEFT JOIN fordon ON fordon.classified_id = mt.classified_id WHERE mt.ad_id IN (
'Bmw_520i_Svensksald_784332731', 'Bmw_M3_Svensksald_755599519',
'Bmw_M3_E46_Full-utrustad_338210082'
)
Then you can loop over those results, in PHP, storing them in an associative array (pseudo-code) :
$hash = array();
foreach ($db_results as $elem) {
$hash[$elem->ad_id] = $elem;
}
$hash will contain the data, indexed by id.
And, then, you'll display the data, using what Solr returned as a starting point for the loop (pseudo-code) :
foreach ($solr_results as $id_solr) {
echo $hash[$id_solr]->some_field . '<br />';
}
With this, you will :
display the results in the order returned by Solr
not do an additionnal (and possibily costly) sort on the database-side.

Categories