PHP JOIN Two MySQL table in result - php

I have two MySQL table for insert comment data and reviews data like this :
comments:
|id|post_id|text|name|timestamp|approved|parent_id|type|ip|
reviews:
|id|postID|comments_id|reviewfield1|reviewfield2|reviewfield3
in action I insert for each comments One reviews. Now, I need to show/print comment list with comment name and text + reviewfield1 reviewfield2 reviewfield3 for each comments where comments is approved like this :
commenter 1
text
reviewfield1
reviewfield2
reviewfield3
TRY:
"SELECT name,text,timestamp FROM " . COMMENTS . " LEFT JOIN " . REVIEWS . " WHERE " . COMMENTS . ".id = " . REVIEWS . ".comments_id AND
post_id = ? AND type = ? AND approved = 1 ", $id, $type"
But this not work for me. how do generate this with PHP JOIN method?

You are making mistake in the query. It must be like this:
"SELECT name,text,timestamp,reviewfield1 FROM " . COMMENTS . " LEFT JOIN " . REVIEWS . " ON " . COMMENTS . ".id = " . REVIEWS . ".comments_id WHERE
post_id = ? AND type = ? AND approved = 1 ", $id, $type"
And you can select rows from the second(joined) table, same as the first one.

Related

Return query with missing/different data only

i have a form where you can select category and will return products that are in this category
$query = $this->db->query("SELECT id, name FROM " . DB_PREFIX . "shared_products_product WHERE category = '" . (int)$id . "' AND status != 2");
Result
Array
(
[0] => Test 1
[1] => Test 2
[2] => Test 3
)
Than you can select only Test 1 and Test 2 to insert in different table
$this->db->query("INSERT INTO " . DB_PREFIX . "shared_products_view SET product_id = '" . (int)$product_id . "', shared_product_id = '" . (int)$shared_product_id . "', category_id = '" . (int)$cat_id . "'");
When i run 1st query how will i get result that still not inserted into shared_products_view for current category_id ?
you need to join table and check if value is already existing
Like this
$query = $this->db->query("SELECT `spp`.id, `spp`.name
FROM " . DB_PREFIX . "shared_products_product `spp`
LEFT JOIN " . DB_PREFIX . "shared_products_view `spv` ON `spp`.`id`=`spv`.shared_product_id
WHERE category = '" . (int)$id . "' AND status != 2 AND `spv`.shared_product_id IS NULL");
When you run your second query, the INSERT, the row will be added, unless you have an error. One thing that comes to mind is you seem to insert integers as strings.
It is better to use PDO and bindValue() and explicitly state it is an integer.
If I understand you right, you want to know if the INSERT succeeded. (Is that correct?)
In that case check the result of your command $this->db->query("INSERT ...").
You didn't mention what database handle $this->db is, but I expect it will return false on failure.
I highly recommend you study this hands-on guide first before proceeding:
https://phpdelusions.net/pdo

Error: Column 'id' in field list is ambiguous php mysqli

I have two table :
news:
|id|title|image|timestamp|....
tags:
|id|books_id|...
for result:
("SELECT id,title,front_thumbs,short_desc,timestamp,counter,author,
FROM " . NEWS . " LEFT JOIN " . TAGS . " ON " NEWS . ".id = " . TAGS . ".content_id WHERE
" . TAGS . ".tags_id = ? AND approved = 1 ORDER BY timestamp DESC LIMIT 10", $id)
but I see this error:
Error: Column 'id' in field list is ambiguous
how do fix this error?
When both tables have same field name it gets ambiguous and to solve this
use SELECTNEWS.id or TAGS.id which table's id you are using:
"SELECT NEWS.id,title,front_thumbs,short_desc,timestamp,counter,author,
FROM " . NEWS . " LEFT JOIN " . TAGS . " ON " NEWS . ".id = " . TAGS . ".content_id WHERE
" . TAGS . ".tags_id = ? AND approved = 1 ORDER BY timestamp DESC LIMIT 10", $id)
You need alias. Yuo have 2 tables both with column id. In your select you request id without specifying which of them you need.
You need to specify table here (before id):
... ("SELECT id,title,front_thumbs,short ...

PHP fix Column 'id' in field list is ambiguous without change column name

I have this vode for show result using PHP join method:
$DB_QUERY = mySqli::f("SELECT name,id, " . AUTHOR . ".id,author_id,book_id FROM " . AUTHOR . " JOIN " . AUTHORS . " ON
" . AUTHOR . ".id = " . AUTHORS . ".author_id WHERE " . AUTHORS . ".book_id = ? ORDER BY name ASC LIMIT 8 ", $id);
foreach($DB_QUERY as $row){
echo $row['id'];
}
Now I see this :
Column 'id' in field list is ambiguous
I now this error when I have two column with name id. how do fix this error without change id name in one column?!
EDIT:
author table:
id|name|
authors table:
id|author_id|book_id
$DB_QUERY = mySqli::f("SELECT author.name, author.id as a_id,
authors.id as as_id, authors.author_id, authors.book_id
FROM author INNER JOIN authors ON author.id = authors.author_id
WHERE authors.book_id = ? ORDER BY name ASC LIMIT 8 ", $id);
For instance.
Then your field real names haven't changed but in your php you can use their temporary "nicknames" a_id and as_id.
Though I am not sure you need authors.id for anything... if it is only your PK on the table maybe you should drop it and use authors.author_id and authors.book_id as your PK... or.. if you are not bringing content from other tables with it... just don't mention it on your select.
You have selected id in your query without any alias & you are applying join on Author & Authors table. I think as both tables contains id column you are getting the error.
Try this
$DB_QUERY = mySqli::f("SELECT name, " . AUTHORS . ".id, " . AUTHOR . ".id,author_id,book_id FROM " . AUTHOR . " JOIN " . AUTHORS . " ON
" . AUTHOR . ".id = " . AUTHORS . ".author_id WHERE " . AUTHORS . ".book_id = ? ORDER BY name ASC LIMIT 8 ", $id);

threaded comments using php mysql

I have this table for insert comments data:(comments)
|id|message|timestamp|approved|parent_id|name|email|
and this table for insert reviews for comments:(reviews)
|id|cid|review_field1|review_field2|review_field3|...
php function :
function _comments_($id,$type){
$DB = mySqli::f("SELECT id,name,email,message,timestamp,review_field_1,review_field_2,review_field_3 FROM " . NEWS_COMMENTS . " LEFT JOIN " . NEWS_REVIEWS . " ON " . NEWS_COMMENTS . ".id = " . NEWS_REVIEWS . ".cid WHERE
pid = ? AND type = ? AND approved = 1 ORDER BY timestamp DESC LIMIT 12", $id, $type);
foreach($DB as $row){
$commentdata[] = $row;
}
return $commentdata;
}
for result:
<?PHP
$comments_list = _comments_('125','news');
foreach($comments_list as $row):
?>
/// HTML tags
<?PHP
$endforeach;
?>
This worked for me and show list of comments and reviews for each comments.
Now i need to show threaded comments(parent) for each comment.
how do can i show threaded comments ?!
NOTE: for parent comment i dont send reviews.

SQL INSERT from SELECT producing duplicate records

I'm learning PHP and Zend Framework. The following PHP function is supposed to fill a temporary table using "INSERT INTO ... SELECT" style query. However, when I SELECT * from the newly appended table, I see that most but not all of the new records have been duplicated once. I have deleted the contents of the table each time I run this scripts. Anyone know why there would be duplicates?
public function fillTableByOfficeName($officeName) {
if ($officeName != '') {
$officePhrase = "b.oof_name ='" . $officeName . "' AND ";
} else {
$officePhrase = '';
}
$whereAddenda = $officePhrase .
"a.fil_bool_will_file_online = false AND " .
"a.fil_bool_confirmed = false AND " .
"a.fil_bool_duplicate = false AND " .
"a.fil_bool_not_found = false AND " .
"(a.fil_res_id_fk NOT IN (4,7,10) OR a.fil_res_id_fk IS NULL) AND " .
"a.fil_will_recorder_rec_id IS NULL AND " .
"d.tag_description NOT IN (
'Already a trust client',
'Not received from local office',
'Southtrust client (already centralized)')";
//"a.fil_date_of_transfer_to_will_recorder IS NULL";
$sql = "INSERT INTO adds(fil_id,REC_ID,FIRST_NAME,LAST_NAME,MIDDLE_INITIAL,SSN," .
"MAILING_ADDRESS_1,MAILING_ADDRESS_2,CITY,STATE,ZIP_CODE,PHONE_NUMBER,BIRTH_DATE," .
"ORIGINATION_OFFICE,FILE_LOCATION,WILL_DATE,LAST_CODICIL_DATE,TRUST_DATE,REV_TRUST,POA_DATE) " .
"SELECT a.fil_id_pk, " .
"a.fil_will_recorder_rec_id, " .
"a.fil_first_name, " .
"a.fil_last_name, " .
"a.fil_middle_name, " .
"a.fil_ssn, " .
"a.fil_mailing_address_1, " .
"a.fil_mailing_address_2, " .
"a.fil_city_address, " .
"a.fil_state_address, " .
"a.fil_zip_code_fk, " .
"a.fil_phone_number, " .
"a.fil_date_of_birth, " .
"b.oof_name, " .
"a.fil_box_id_fk, " .
"a.fil_date_of_will, " .
"a.fil_date_of_last_codicil, " .
"a.fil_date_of_trust, " .
"a.fil_notes, " .
"a.fil_date_of_poa " .
"FROM files a, origination_offices b, nn_files_tags c, tags d " .
"WHERE " .
"a.fil_oof_id_fk = b.oof_id_pk AND " .
"a.fil_id_pk = c.fil_id_fk AND " .
"d.tag_id_pk = c.tag_id_fk AND " .
$whereAddenda;
$this->getAdapter()->query($sql);
return $this;
}
The way you are joining the table will give you the cartesian product of the rows from the tables (all pairs of matching rows are returned).
With no specific knowledge of the domain, I would guess at the tags table - if you've got multiple tags for a particular file, you will get multiple copies of the file in your result set (one per each matched tag).
As you're not using tags fields in the result set, just the where clause, the solution would be to get rid of tags / nn_files_tags from the main query, and in your where clause, use NOT EXISTS to check for matching rows in the tags table, something like:
AND NOT EXISTS (SELECT tag_id_pk FROM tags WHERE tags.tag_id_pk ...
You are using C for a many to many relationship. For example, if you have invoices between companies and customers and you select from join of them, you will get as many rows as you have invoices. From that, if you only select the company name and costumer name, you will have many duplicates because the same pair has produced many invoices.
This is the same issue you have here.
As asc99c said, you could use an inner select to make your WHERE clause without joining on that relationship or you could use the DISTINCT key word (which effectively is a group by on everything in your SELECT clause). I would think the INNER SELECT solution more efficient (yet I could be totally wrong about that), but the DISTINCT way is 8 key press away...

Categories