php pg_fetch_array only show first result - php

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

Related

MYSQL pickup Random row after order by

I want to pick a random row after doing an order by.
My result can sometime return 2 rows with same value. So what i want to do it that i want to select 1 row randomtly between the same rows returned.
In the below example i want to return 1 row between the 2 same rows returned.
Thanks.
select nondox, account, id
from rates2 where weight='32' and country_code='US'
and service like '%INT%'
order by nondox,account
Result of the above query is
nondox account id
276.16 610661731 25805209
276.16 610798714 2108989
391.68 610662766 1281799
Can provide more details ?
This will eliminate the similar nondox values it's not completely random but it should work.
select account, id , nondox from rates2 where weight='32' and country_code='US' and service like '%INT%' group by nondox order by nondox,account
you can use function RAND() that generates a random value for each row in the table
SELECT * FROM table_name
ORDER BY RAND()
LIMIT 1;
for more informations checkout this link
you can put the result in an array, then create a random integer with random(with limit) the output the values of the index from random.
example random outputs 2, you return array[random+1] ie array[3]

How to select one row from multiple which are with same column name in mysql?

I have a table with with columns name:
id
message
sender
chat_id
I want to get one row from number of rows with same chat_id ,during while loop fetch.
What Will be the MySQL Query
If you only want one row, one of those columns needs to have unique data so you can add it to the WHERE clause
SELECT id,message,sender,chat_id from information WHERE id=2 for example.
SELECT id,message,sender,chat_id from information WHERE chat_id=5 AND sender='mark'
OR during the while loop, match the column and grab whatever you want from it.
But again, it needs to be a unique combination of data otherwise it'll be overwritten by the previous.
while($row = $result->fetch_assoc()){
if($row['sender'] == 'mark' && $row['chat_id'] == '5'){
$thisIsMyRow = $row['id'];
}
Please could you explain more? What is it you're trying to achieve?
Say this is your query:
SELECT id,message,sender,chat_id from messages WHERE chat_id=1
You may have 200 rows that match that query. To return just one result, you can do a couple of things.
If you want the latest message, you can do this:
SELECT id,message,sender,chat_id from messages WHERE chat_id=1 ORDER BY id DESC LIMIT 1
another example, latest 5 messages
SELECT id,message,sender,chat_id from messages WHERE chat_id=1 ORDER BY id DESC LIMIT 0,5
In addition when you take it back into PHP, rather than going through the loop, you can JUST do this:
$row = $result->fetch_assoc()
As our query is only returning 1 row, you don't need to loop through. You can do this when your query returns multiple results - but it'd be better to optimise your query.
I can advise better if you are able to elaborate.
while($row = $result->fetch_assoc()){
$query = "SELECT id, message, sender,chat_id FROM messages WHERE Y = X AND Z = $K LIMIT 1";
}
replace the WHERE part with whatever column you want

MySQL JOIN pass PHP variable to two tables

I have the following MySQL query in PHP that passes a variable to complete the query:
SELECT * from mobile_tech WHERE uid=$uid order by timestamp DESC limit 0,1
I have the following MySQL JOIN that provides data from two tables:
SELECT mobile_tech.latitude, mobile_tech.longitude, mobile_tech.timestamp, mobile_tech.uid, gbl_qemplisting.EmpNo, gbl_qemplisting.FirstName, gbl_qemplisting.LastName
FROM mobile_tech, gbl_qemplisting
WHERE mobile_tech.uid=gbl_qemplisting.EmpNo AND date(timestamp)='$currentday'
group by uid
I need to combine these two queries into one with a JOIN and still passing the $uid variable to complete the query.
I've tried the following and it did not work:
SELECT mobile_tech.latitude, mobile_tech.longitude, mobile_tech.timestamp, mobile_tech.uid, gbl_qemplisting.EmpNo, gbl_qemplisting.FirstName, gbl_qemplisting.LastName
FROM mobile_tech, gbl_qemplisting
WHERE mobile_tech.uid=$uid AND gbl_qemplisting.EmpNo=$uid AND date(timestamp)='$currentday'
Your query will return a cross product between the mobile_tech and gbl_emplisting rows for $uid. If you just want one row, as in the first query, use ORDER BY and LIMIT similarly.
SELECT mobile_tech.latitude, mobile_tech.longitude, mobile_tech.timestamp, mobile_tech.uid, gbl_qemplisting.EmpNo, gbl_qemplisting.FirstName, gbl_qemplisting.LastName
FROM mobile_tech, gbl_qemplisting
WHERE mobile_tech.uid=$uid AND gbl_qemplisting.EmpNo=$uid AND date(timestamp)='$currentday'
ORDER BY mobile_tech.timestamp
LIMIT 1
Please try with this and say the result
SELECT mobile_tech.latitude,
mobile_tech.longitude,
mobile_tech.timestamp,
mobile_tech.uid,
gbl_qemplisting.EmpNo,
gbl_qemplisting.FirstName,
gbl_qemplisting.LastName
FROM mobile_tech inner join gbl_qemplisting
on mobile_tech.uid=gbl_qemplisting.EmpNo
where mobile_tech.uid=$uid AND date(timestamp)='$currentday'

How to count if value of a variable is repeated?

I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}

MySQL COUNT query results in 1 always

I'm wondering why my MySQL COUNT(*) query always results in ->num_rows to be equal 1.
$result = $db->query("SELECT COUNT( * ) FROM u11_users");
print $result->num_rows; // prints 1
Whereas fetching "real data" from the database works fine.
$result = $db->query("SELECT * FROM u11_users");
print $result->num_rows; // prints the correct number of elements in the table
What could be the reason for this?
Because Count(*) returns just one line with the number of rows.
Example:
Using Count(*) the result's something like the following.
array('COUNT(*)' => 20);
echo $result['COUNT(*)']; // 20
Reference
It should return one row*. To get the count you need to:
$result = $db->query("SELECT COUNT(*) AS C FROM u11_users");
$row = $result->fetch_assoc();
print $row["C"];
* since you are using an aggregate function and not using GROUP BY
that's why COUNT exists, it always returns one row with number of selected rows
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
Count() is an aggregate function which means it returns just one row that contains the actual answer. You'd see the same type of thing if you used a function like max(id); if the maximum value in a column was 142, then you wouldn't expect to see 142 records but rather a single record with the value 142. Likewise, if the number of rows is 400 and you ask for the count(*), you will not get 400 rows but rather a single row with the answer: 400.
So, to get the count, you'd run your first query, and just access the value in the first (and only) row.
By the way, you should go with this count(*) approach rather than querying for all the data and taking $result->num_rows; because querying for all rows will take far longer since you're pulling back a bunch of data you do not need.

Categories