PHP/MySQL Compare against a date - php

I'm running into a little issue concerning a datetime picker and MySQL.
I have a PHP script that should get records before (and including) the selected day. However, the dataset returns empty.
Here's the SQL part of the script:
$sql = 'SELECT `pro_title`,
`pro_part_number`,
`name` AS flag_name,
`old_val`,
`new_val`
FROM `products`
INNER JOIN `flags` ON `id` = `pro_flag_id`
INNER JOIN `flag_history` ON `pro_part_number` = `part`
WHERE `pro_flag_id` IN(:flags)
AND STR_TO_DATE(`ts`, "%y-%m-%d") <= :dateTs;';
I then use PDO to bind the params:
array(
':flags' => implode(',', $flags), # this outputs 1,2,3
':dateTs' => $date # this outputs 2019-04-30
)
I've also tried changing <= to >= to no avail (not that it should work, but thought I'd try).
I've come across a good few SO posts but nothing has actually got me there. Here is the description of the flag_history table (where ts is stored)
MariaDB [mastern]> describe `flag_history`;
+---------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| part | varchar(25) | NO | | NULL | |
| ts | datetime | YES | | CURRENT_TIMESTAMP | |
| old_val | int(4) | YES | | NULL | |
| new_val | int(4) | YES | | NULL | |
+---------+-------------+------+-----+-------------------+----------------+
And some example data:
MariaDB [mastern]> select * from `flag_history` order by `id` desc limit 5;
+-------+----------+---------------------+---------+---------+
| id | part | ts | old_val | new_val |
+-------+----------+---------------------+---------+---------+
| 24026 | PART-001 | 2019-04-30 09:42:22 | 0 | 3 |
| 24025 | PART-002 | 2019-04-30 09:42:22 | 0 | 3 |
| 24024 | PART-003 | 2019-04-30 09:42:22 | 0 | 3 |
| 24023 | PART-004 | 2019-04-30 09:42:22 | 0 | 3 |
| 24022 | PART-005 | 2019-04-30 09:42:22 | 0 | 3 |
+-------+----------+---------------------+---------+---------+
Then, using PART-001 to make sure the flag_id is actually set:
MariaDB [mastern]> select `pro_flag_id` from `products` where `pro_part_number` = "PART-001";
+-------------+
| pro_flag_id |
+-------------+
| 3 |
+-------------+
So I'm not really sure what's going wrong, the logic and everything to me (MySQL newb) looks like it should work but it's giving me empty data. I also tried changing the INNER JOIN's to LEFT JOIN's but again, didn't work.
What am I doing wrong?

I managed to solve it. As I'm really reading the flag_history table, I changed the main SELECT focus to flag_history, revised SQL:
$sql = 'SELECT `old_val`, `new_val`, `ts`, `flags`.`name` AS flag_name, `pro_part_number`, `pro_title`
FROM `flag_history`
INNER JOIN `products` ON `pro_part_number` = `part`
INNER JOIN `flags` ON `pro_flag_id` = `flags`.`id`
WHERE `ts` <= :dateTs;';
I slowly added in the INNER JOIN's and managed to get it working when using flag_history. I think the issue actually may have been down to the id field. Being an ambiguous field (flags and flag_history have the id column). Weirdly, I wasn't getting that error though (maybe as I wasn't selecting). Either way managed to resolve it by being more specific with my select and going from the read-table rather than joining it.
On a further note, removing the flags segment from the JOIN shows the constraint error. So my guess is that it didn't show first time as I was reading from a different table.

Related

Optimization of SQL with subquery and Having

Currently we are using a custom CI library to generate PDF files from documents which exist as database records in our database.
Each document is related to the contents (== rows) with a one-has-many relation. Each row has a number (field: row_span) to indicate how many lines it will use once it gets printed in the PDF.
Per PDF page that gets build, Rows needed for that page only are selected using a subquery:
$where = $this->docType."_id = ".$this->data['doc']->id." AND visible = 1";
$sql = "SELECT *,
(SELECT
sum(row_span) FROM app_".$this->docType."_rows X
WHERE X.position <= O.position
AND ".$where."
ORDER BY position ASC) 'span_total'
FROM app_".$this->docType."_rows O
WHERE ".$where."
HAVING span_total > ".(($i-1)*$this->maxRows)." AND span_total <= ".($i*$this->maxRows)." ORDER BY O.position ASC ";
$rows = $rows->query($sql);
In the code $i is the page number and $this->maxRows is loaded from the document template record which indicates how many available lines the PDF template has.
So when the SQL renders it might look like this for page 1 of an order with ID 834:
SELECT `app_order_rows`.*,
(SELECT SUM(`app_order_rows_subquery`.`row_span`) AS row_span
FROM `app_order_rows` `app_order_rows_subquery`
WHERE `app_order_rows_subquery`.`position` <= 'app_order_rows.position'
AND `app_order_rows_subquery`.`order_id` = 834
AND `app_order_rows_subquery`.`visible` = 1
ORDER BY `app_order_rows_subquery`.`position` asc) AS span_total
FROM (`app_order_rows`)
WHERE `app_order_rows`.`order_id` = 834
AND `app_order_rows`.`visible` = 1
HAVING span_total > 0
AND span_total <= 45
ORDER BY `app_order_rows`.`position` asc
And running this with EXPLAIN gives this as output:
+====+=============+=========================+======+===============+======+=========+======+======+=============================+===+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | |
+====+=============+=========================+======+===============+======+=========+======+======+=============================+===+
| 1 | PRIMARY | app_order_rows | ALL | NULL | NULL | NULL | NULL | 1809 | Using where; Using filesort | 1 |
+----+-------------+-------------------------+------+---------------+------+---------+------+------+-----------------------------+---+
| 2 | SUBQUERY | app_order_rows_subquery | ALL | NULL | NULL | NULL | NULL | 1809 | Using where | 2 |
+====+=============+=========================+======+===============+======+=========+======+======+=============================+===+
This is working great, but... When we have large orders or invoices it renders the documents very slow. This might be due to the subquery.
Does anyone have an idea on how to do the same select without subquery? Maybe we will have to go for a whole new approach to select rows and build the PDF. We are open for suggestions ^^
Thanks in advance
------------------------------- edit ------------------------------
The EXPLAIN after index creation:
+====+=============+=========================+=======+===============+============+=========+=======+======+=============+===+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | |
+====+=============+=========================+=======+===============+============+=========+=======+======+=============+===+
| 1 | PRIMARY | app_order_rows | ref | index_main | index_main | 5 | const | 9 | Using where | 1 |
+----+-------------+-------------------------+-------+---------------+------------+---------+-------+------+-------------+---+
| 2 | SUBQUERY | app_order_rows_subquery | range | index_main | index_main | 10 | NULL | 1 | Using where | 2 |
+====+=============+=========================+=======+===============+============+=========+=======+======+=============+===+
As you confirmed in the comments, the tables have no indexes.
The immediate solution would be:
create index index_main on app_order_rows (order_id, position);

load posts from each friend

I'm currently working on a "news feed" type of script and I am trying to load the posts created by the user's friends. My current code partially works; it only loads from one friend and finishes. What am I doing wrong?
<?php
$infofriends = mysql_fetch_array(mysql_query("SELECT * FROM btfriend WHERE `user_id`='".$infousr['auto']."'"));
$infofrnd = mysql_fetch_array(mysql_query("SELECT * FROM btaccs WHERE `auto`='".$infofriends['friend_id']."'"));
$posts = mysql_query("SELECT * FROM btpost WHERE `user`='".$infofrnd['user']."' ORDER BY `auto` DESC") or die('Error: '.mysql_error());
while($row = mysql_fetch_array( $posts )) {
$infobeer = mysql_fetch_array(mysql_query("SELECT * FROM btbeer WHERE `beer`='".$row['beer']."'"));
$infouser = mysql_fetch_array(mysql_query("SELECT * FROM btaccs WHERE `user`='".$row['user']."'"));
....
(Currently sloppy, I'll be editing that afterwards).
MySQL structures:
btfriend
mysql> DESCRIBE btfriend;
+-----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+----------------+
| auto | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | YES | | NULL | |
| friend_id | int(11) | YES | | NULL | |
+-----------+---------+------+-----+---------+----------------+
btaccs
mysql> DESCRIBE btaccs;
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| auto | int(11) | NO | PRI | NULL | auto_increment |
| user | varchar(150) | YES | | NULL | |
| display | varchar(150) | YES | | NULL | |
| pass | varchar(250) | YES | | NULL | |
| email | varchar(150) | YES | | NULL | |
| firstname | varchar(150) | YES | | NULL | |
| lastname | varchar(150) | YES | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
btpost
mysql> DESCRIBE btpost;
+---------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+----------------+
| auto | int(11) | NO | PRI | NULL | auto_increment |
| user | varchar(500) | YES | | NULL | |
| beer | varchar(911) | YES | | NULL | |
| img | varchar(30) | YES | | NULL | |
| rate | varchar(10) | YES | | NULL | |
| loc | varchar(1000) | YES | | NULL | |
| comment | varchar(1500) | YES | | NULL | |
| fb | varchar(10) | YES | | NULL | |
| type | int(2) | YES | | NULL | |
+---------+---------------+------+-----+---------+----------------+
It'd be great if someone could help!
First of all, you're using mysql_* functions; those have been deprecated, and will stop working at some point in the future. Look at switching to mysqli_ or PDO instead - they both make it easier to write safer code.
Secondly, you're calling your code in such a way that you're expecting it to work:
$infofriends = mysql_fetch_array(mysql_query("SELECT * FROM btfriend WHERE `user_id`='".$infousr['auto']."'"));
If the query fails, you'll be passing a boolean false to mysql_fetch_array; it's a lot easier to make each statement one at a time, and handle errors as they come up:
$friendset = mysql_query("SELECT * FROM btfriend WHERE `user_id`='".$infousr['auto']."'") or die (mysql_error());
$infofriends = mysql_fetch_array($friendset) or die (mysql_error());
That will generate an error on the appropriate line if something goes wrong - it's a little more code, but it's much easier to debug and maintain.
Finally, your actual question; you're only getting one friend, because you're only calling mysql_fetch_array() once on the friend query; that will return to the top row. A quick solution would be to loop through the results separately to generate a list, and then pass that into the second query:
$friendset = mysql_query("SELECT * FROM btfriend WHERE `user_id`='".$infousr['auto']."'") or die (mysql_error());
$friendArray = array();
while ($infofriends = mysql_fetch_array($friendset)) {
$friendArray[] = $infofriends['friend_id'];
}
$friendArray[] = $infousr['auto'];
// At this point, you have an array of friend IDs.
$posts = mysql_query("SELECT * FROM btpost INNER JOIN btaccs ON btpost.user=btaccs.user WHERE btaccs.auto IN (" . implode(',', $friendArray) . ") ORDER BY btpost.auto DESC") or die('Error: '.mysql_error());
Note that it's using an IN to retrieve all the IDs at once; you might want to add an extra parameter to the ORDER BY to arrange the posts by friend.
Note that I've not tested this, so there may be issues with the syntax, but I hope it's enough for you to get the general idea.
--
We solved this in the chat and have added $friendArray[] = $infousr['auto']; which would also include the posts from the current user. The current user's ID, along with the friend IDs, would then go into the implode function in the query. We also linked the btpost and btaccs tables because btaccs held the user's ID, while btpost held the username. Full chat transcript -alexpja
Try this with using single query with join
SELECT p.*
FROM btpost p
INNER JOIN btfriend f ON (p.`user` = f.friend_id)
WHERE f.user_id =$infousr['auto']
Then loop through all the results from query,this will give you all the posts where btpost's user is equal to the friend's id btfriend and these are the friends of your given user id $infousr['auto'] I assume $infousr['auto'] will have the user id
I think you're missing a loop. Let's break down your code:
<?php
// Here, you run a query that presumably returns multiple rows, but you're only looking at the first row:
$infofriends = mysql_fetch_array(mysql_query("SELECT * FROM btfriend WHERE `user_id`='".$infousr['auto']."'"));
// That gave you a single array of the first friend that MySQL found
// Now, you take the `friend_id` field from that single result, and you run it against the `btaccs` table to get some more information:
$infofrnd = mysql_fetch_array(mysql_query("SELECT * FROM btaccs WHERE `auto`='".$infofriends['friend_id']."'"));
// Once again, you have a single row at this point. (Although here, I'm assuming that's ok, since a user's ID probably appears only once in this table
// Now, you take the single user that you've looked up, and you find posts associated with that user:
$posts = mysql_query("SELECT * FROM btpost WHERE `user`='".$infofrnd['user']."' ORDER BY `auto` DESC") or die('Error: '.mysql_error());
I think you can see that it's the first statement that limits it to a single user. Try creating an array before running that statement, and then looping through your result set, adding to that array.
A few other things I'd seriously consider:
1) Take advantage of PHP's double-quote string substitution...
mysql_query("SELECT * FROM btfriend WHERE `user_id`='{$infousr['auto']}'"
is a little easier to read than
mysql_query("SELECT * FROM btfriend WHERE `user_id`='".$infousr['auto']."'"
2) Read up on JOINs in MySQL. Everything you've done here can actually be collapsed into a single query in MySQL. It'd be a little too much to go into detail here, but you can start with the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/join.html

How do you reference multiple lookups from the same table?

This is my first post, but I've been reading here for ages taking in a lot of great information.
Please bear with me as I try to explain my predicament. I wasn't even sure how to label my question, since I don't really know the terminology for what I'm trying to do. I'm a beginner of PHP/MySQL (this will become painfully obvious when you see my question), but I'm eager to learn.
Anyway, here goes:
I have two tables, named Games and Teams.
mysql> describe games;
+-----------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| homeTeam | int(11) | NO | | NULL | |
| awayTeam | int(11) | NO | | NULL | |
| homeScore | int(11) | NO | | NULL | |
| awayScore | int(11) | NO | | NULL | |
| homeOdds | decimal(10,2) | NO | | NULL | |
| drawOdds | decimal(10,2) | NO | | NULL | |
| awayOdds | decimal(10,2) | NO | | NULL | |
| gameDate | date | NO | | NULL | |
+-----------+---------------+------+-----+---------+----------------+
and
mysql> describe teams;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| team | varchar(255) | NO | | NULL | |
+-------+--------------+------+-----+---------+----------------+
I would like the fields Games.homeTeam and Games.awayTeam to do a lookup for their values in the Teams.id and Teams.team fields. Basically Games.homeTeam should find its equivalent in Teams.id. Simple enough. However, I would like both Games.homeTeam and Games.awayTeam to look in the Teams table within the same SQL statement.
I figured maybe something like this would work:
$result = mysql_query("SELECT * FROM Games g, Teams ht, Teams at where g.homeTeam = ht.id AND g.awayTeam = at.id ORDER BY g.gameDate") or die(mysql_error());
and then to pick the rows up:
while($row = mysql_fetch_array($result)) { echo "Home Team: " . $row['ht.team'];}
That's a no go, as I get a mysql error saying there's no index named ht.team.
I hope it's fairly clear what I'm trying to achieve here. How should I go about this? I assume I have to use aliases of some sort, but I can't wrap my head around as to what the SQL statement should look like to accomplish what I want.
Don't use SELECT * with join queries! Always be explicit about the columns you need in your SELECT list, and supply column aliases:
SELECT
/* Only select the columns you actually need, and
* supply aliases to those with similar names
*/
ht.team AS ht_team,
ht.id AS ht_id,
at.team AS at_team,
at.id AS at_id
g.homeScore,
g.awayScore,
g.homeOdds,
g.drawOdds,
g.awayOdds,
g.gameDate
FROM
Games g,
Teams ht,
Teams at
where g.homeTeam = ht.id AND g.awayTeam = at.id
ORDER BY g.gameDate
In your PHP, access them via their aliases, for example:
echo "Home Team: {$row['ht_team']}";
By the way, although your method of implicit (comma-separated tables and conditions in the WHERE clause) joins will work, using explicit joining is often recommended. It is a newer syntax, and will allow easier expansion into LEFT JOIN or RIGHT JOIN when the need arises:
SELECT
ht.team AS ht_team,
ht.id AS ht_id,
at.team AS at_team,
at.id AS at_id
g.homeScore,
g.awayScore,
g.homeOdds,
g.drawOdds,
g.awayOdds,
g.gameDate
FROM
/* Explicit JOIN syntax */
Games g,
JOIN Teams ht ON g.homeTeam = ht.id
JOIN Teams at ON g.awayTeam = at.id
ORDER BY g.gameDate
I think the problem is
you give an alias to the table only , not to the column
if there is not a column in Games table with the name team
you can call it in your loop with only
$row['team'];
However if both of table have the same name column like team
so you should do this .
select ht.team as htTeam , g.team as gTeam from Teams ht inner join
Games on ht.Id = .....
Then you can reach each team term with
$row['htTeam']
and $row['gTeam'];
and I think get used to decide a prefix for tables and the their columns

PHP mysql LEFT JOIN output

I have php-script running on top of apache. Every time when user goes to specific URL, he/she will get csv-file.
Column names are fetched like this (thanks to Daniel Figueroa :)
$csv_output .= "\n";
// get the column name from the first DB (ins.data)
mysql_select_db($db, $link) or die("Can not connect to DB1.");
$result = mysql_query("SHOW COLUMNS FROM ".$table." WHERE Field NOT IN
('ID','Key','Text')");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
// get the column names from the second DB (Cu.data)
mysql_select_db($db2, $link) or die("Can not connect to DB2.");
$result = mysql_query("SHOW COLUMNS FROM ".$table2." ");
;
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
Actual query on PHP-script goes like this:
$values = mysql_query(" SELECT ins.data.`Date`, ins.data.`Number`,
ins.data.`Email`, ins.data.`TargetId`, ins.data.`CSW`,
ins.data.`TSW`, ins.data.`CType`,
Cu.data.`Cus`, Cu.data.`Co`,Cu.data.`Ci`,
Cu.data.`SID`, Cu.data.`SType`
FROM ins.data
LEFT JOIN Cu.data ON (ins.data.TargetId = Cu.data.TargetID)
ORDER BY ins.data.ID DESC");
Output of 'desc':
mysql> desc ins.data;
+-------------------+------------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+------------------+------+-----+---------------------+----------------+
| ID | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Date | timestamp | NO | | 0000-00-00 00:00:00 | |
| Number | text | NO | | NULL | |
| Text | text | NO | | NULL | |
| Email | text | NO | | NULL | |
| TargetId | varchar(20) | NO | | NULL | |
| CSW | text | NO | | NULL | |
| TSW | text | NO | | NULL | |
| Key | text | NO | | NULL | |
| CType | text | NO | | NULL | |
+-------------------+------------------+------+-----+---------------------+----------------+
10 rows in set (0.00 sec)
mysql> desc Cu.data;
+----------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------------+------+-----+---------+-------+
| Title | decimal(15,0) | NO | | NULL | |
| Cu | text | NO | | NULL | |
| Co | text | NO | | NULL | |
| Ci | text | NO | | NULL | |
| SID | text | NO | | NULL | |
| TargetID | varchar(20) | NO | MUL | NULL | |
| SType | text | NO | | NULL | |
| empty1 | int(11) | NO | | NULL | |
| empty2 | int(11) | NO | | NULL | |
| empty3 | int(11) | NO | | NULL | |
| empty4 | int(11) | NO | | NULL | |
| empty5 | int(11) | NO | | NULL | |
| empty6 | int(11) | NO | | NULL | |
| empty7 | int(11) | NO | | NULL | |
+----------+---------------+------+-----+---------+-------+
12 rows in set (0.00 sec)
UPDATE 3:
This is no more NATURAL LEFT JOIN-issue. Replaced with LEFT JOIN.
Added fields empty1-5 to ins.data to get data to csv-file. Without fields empty1-5, only data from first db (ins.data) was on csv.file.
Now i have data on all fields but field (or column names on excel) names on csv are on wrong order and not wanted fields (columns) are visible like Title and empty1-5.
Any ideas how to fix this? Some other way to get Field names to csv-file without "SHOW COLUMNS"?
I could write with 'echo' in the beginning of csv-file values what i want. ie
"Date; Number; Email; TargetID, CSW; TSW; CType; Cu; SID; Co; Ci; SType;" but i am so newbie with PHP that i don't know how :(
Another issue is that if field ID is first column on excel, excel cannot handle that and it must be excluded from SHOW COLUMNS output.
UPDATE4: Added more empty-fields to DB2 (Cu.data) and reordered SQL-query, now all values are visible and on right order.
EDIT
First of all, your table naming schema is weird and unusual... but assuming I understand it correctly then this query should work (if it does not then rename your tables without the dots (periods) to make things less confusing:
mysql_query('SELECT ins.data.Date, ins.data.Number, ins.data.Email, ins.data.TID, ins.data.CSW, ins.data.TSW, ins.data.CType, CU.data.SID, cu.data.SType, cu.data.CU, cu.data.CO, cu.data.Ci, FROM ins.data, cu.data ORDER BY ins.data.ID DESC');
According to to the mysql_query function reference, data should not end with a semicolon when using mysql_query in PHP... i never put the semicolon in there so I don't ever have a problem, that's what I initially noticed with your script (as I said i've never tried it so I don't know if thats the issue). Should be:
$values = mysql_query("SELECT Date, Number, Email, TID, CSW, TSW, CType, SID, SType, Cu, Co, Ci FROM ins.data NATURAL LEFT JOIN Cu.data ORDER BY ID DESC");
Also, when doing JOINS, usually you specify what column belongs to what table... like in the standard mysql example here:
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT family.Position, food.Meal ".
"FROM family LEFT JOIN food ".
"ON family.Position = food.Position";
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
echo $row['Position']. " - ". $row['Meal'];
echo "<br />";
}
?>
I don't always use the JOIN commands either... you can use an alternative syntax like so:
mysql_query('SELECT ... FROM t1, t2, t3 WHERE t1.b = t2.b AND t2.c = t3.c AND t1.a = t3.a');
Try putting aliases on table names. It will make the query more readable, too:
SELECT
i.`Date`, i.Number, i.Email, i.TID, i.CSW, i.TSW, i.CType,
c.Cu, c.Co, c.Ci, c.SID, c.TID, c.SType
FROM
ins.data AS i
LEFT JOIN
Cu.data AS c
ON i.TID = c.TID
ORDER BY
i.ID DESC ;

Query result in MySQL Console does not match the result of PHP's mysql_query()

My MySQL query returns different results depending on how the query is submitted. When the query is submitted through the MySQL Console results in.
mysql> SELECT `modx`.coverage_nation.id,
-> `modx`.coverage_nation.name,
-> `modx`.coverage_national_region.id,
-> `modx`.coverage_national_region.name
-> FROM `modx`.coverage_nation_part
-> RIGHT JOIN `modx`.coverage_national_region ON (`modx`.coverage_nati
on_part.nation_regionID = `modx`.coverage_national_region.id)
-> RIGHT JOIN `modx`.coverage_nation ON (`modx`.coverage_nation_part.n
ationID = `modx`.coverage_nation.id)
-> ORDER BY `modx`.coverage_nation.name ASC, `modx`.coverage_national_region
.name ASC;
+----+---------------+------+------+
| id | name | id | name |
+----+---------------+------+------+
| 3 | Canada | NULL | NULL |
| 18 | Chad | NULL | NULL |
| 17 | Germany | NULL | NULL |
| 15 | Italy | NULL | NULL |
| 2 | Mexico | NULL | NULL |
| 19 | Nigeria | NULL | NULL |
| 14 | Russia | NULL | NULL |
| 16 | Spain | NULL | NULL |
| 1 | United States | NULL | NULL |
+----+---------------+------+------+
9 rows in set (0.00 sec)
When the same query is submitted using PHP's mysql_query it returns only one row.
$query .= "SELECT `modx`.coverage_nation.id,
`modx`.coverage_nation.name,
`modx`.coverage_national_region.id,
`modx`.coverage_national_region.name
FROM `modx`.coverage_nation_part
RIGHT JOIN `modx`.coverage_national_region ON (`modx`.coverage_nation_part.nation_regionID = `modx`.coverage_national_region.id)
RIGHT JOIN `modx`.coverage_nation ON (`modx`.coverage_nation_part.nationID = `modx`.coverage_nation.id)
ORDER BY `modx`.coverage_nation.name ASC, `modx`.coverage_national_region.name ASC;";
$resultSet = mysql_query($query) or die("query failed ".mysql_error());
while($row = mysql_fetch_array($resultSet,MYSQL_NUM)) {
// handle each result here
}
Returns only Canada. Does anyone have any ideas as to how I might solve this?
You have more than one field with the names id and name. Try changing the SELECT portion of your SQL (in the PHP code) to:
SELECT `modx`.coverage_nation.id,
`modx`.coverage_nation.name,
`modx`.coverage_national_region.id AS coverage_national_region_id,
`modx`.coverage_national_region.name AS coverage_national_region_name
Or something similar so returned fields have distinct names.
There was an error in my code somewhere. I sat down and rewrote it and it now works.

Categories