sql left join not working - php

I want to get total transfered items from table inv_site_item where 'item_id' in inv_sie_item = 'item_code' in inv_items, I am getting packing also from packing table which works fine in this query only inv_site_item is giving problem.
error is: Unknown column 'inv_site_item.site_id' in 'field list'
$where .= " AND inv_items.item_code = $item_code";
$query = "SELECT inv_items.*,packing.name_en `packing_name`,"
. " COUNT(inv_site_item.site_id) `transfer_out`, COUNT(inv_site_item.location_site_id) `transfer_in` FROM inv_items"
. " left join "
. "inv_packing as packing on packing.id=inv_items.packing"
. " left join "
. "inv_site_item as transfer on transfer.item_id=inv_items.item_code"
. " WHERE item_code !='' " . $where . "";

you must use your table alias transfer instead, So:
change from
inv_site_item.site_id
to
transfer.site_id
also with inv_site_item.location_site_id to be transfer.location_site_id

For any query related errors you should always check to print the query if possible. Your "WHERE" clause is not getting populated correctly.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE item_code !=''' at line 1
This means that your query is giving error near your "WHERE" clause.
Print your $query variable to see the actual query that is built then you will be able to find the error and fix it.
<?php echo "<pre>"; print_r($query); echo "</pre>"; ?>

you must use your table alias transfer instead, So:
change from
inv_site_item.site_id
to
transfer.site_id
also with inv_site_item.location_site_id to be transfer.location_site_id
And also change $where .= " AND inv_items.item_code = $item_code"; to
$where .= "inv_items.item_code = $item_code";
and
change query statement to
$query = "SELECT inv_items.*,packing.name_en `packing_name`,"
. " COUNT(transfer.site_id) `transfer_out`, COUNT(transfer.location_site_id) `transfer_in` FROM inv_items"
. " left join "
. "inv_packing as packing on packing.id=inv_items.packing"
. " left join "
. "inv_site_item as transfer on transfer.item_id=inv_items.item_code"
. " WHERE " . $where . " AND item_code !=' '";
For let not empty clause come at last...

Related

SQL syntax error, PHP MYSQL

$sql = "SELECT post_title, post_body, post_author FROM forum_post WHERE post_id='".$pid."' forum_id='".$id."' AND post_type='o'";
if($topicPost = $mysql->prepare($sql)) {
$topicPost->bind_param('ss',$pid,$id);
$topicPost->bind_result($post_title, $post_body, $post_author);
$topicPost->execute();
$topicPost->store_result();
} else {
echo "ErrorinSQLLL, ".$mysql->error;
exit();
}
So there is my SQL query statement.
I get this printed on my page :
ErrorinSQLLL, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'forum_id='1'' at line 1
If needed I can post more of my code.
You are missing AND in your query, here post_id='$pid' forum_id='$id'.
You missed one AND, after post_id key:
"SELECT
post_title,
post_body,
post_author
FROM
forum_post
WHERE
post_id = " . $pid . "
AND
forum_id= " . $id . "
AND
post_type = 'o'";
Missing and in where condition
... WHERE post_id = " . (int)$pid . " AND forum_id = " . (int)$id . " ...
Ids are number, so without quotes.

check column if empty then do update

guys i have a large database so when i want to fully update my some column i have timeout error (i attempt some method to increase timeout and fail) But my question is i want to bypass this problem i want to update my empty column in some table. so i want to use this query code but i have blank page with no error can some one tell me what problem with that or if possible pleas tell me a good method.
$sql = 'SELECT topic_first_poster_avatar FROM ' . TOPICS_TABLE . ' WHERE topic_poster = ' . (int) $row['user_id'] . 'IF topic_first_poster_avatar = ""
SET topic_first_poster_avatar = \'' . $db->sql_escape($avatar_info);
$db->sql_query($sql);
As plalx said in the comments, you don't need a SELECT or IF, you can specify WHERE for the update statement and have multiple contraints with AND/OR.
$sql = "UPDATE ". TOPICS_TABLE ."
SET topic_first_poster_avatar = '" . $db->sql_escape($avatar_info) ."'
WHERE topic_poster = " . (int) $row['user_id'] . " AND topic_first_poster_avatar = ''";

What is wrong with this SQL IF Statement?

so I am building a search script and meed to pass on two variables, but first I want to make sure that the SQL QUery is correct so I am hard-coding the variable for now. So my variable is
$comma_separated = "'Alberta','Ontario'";
This is getting passed through to the query, which looks like this:
$sql = "SELECT * FROM persons WHERE 1=1";
if ($firstname)
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
if ($surname)
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
if ($province)
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' WHERE province IN ($comma_separated)";
$sql .= " ORDER BY surname";
and then when the query runs, I get this message:
cannot run the query because: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE province IN ('Alberta','Ontario') ORDER BY surname LIMIT 0, 5' at line 1
But to me the query looks right, what am I missing here?
Thanks in advance.
You can't have WHERE in there twice. You also seem to be trying to filter on province values in two different ways. Based on the assumption that $province will always be an array of values (even if only a single value is given), you can try this:
$sql = "SELECT * FROM persons WHERE 1=1";
if (!empty($firstname)) {
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
}
if (!empty($surname)) {
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
}
if (!empty($province)) {
array_walk($province, function($value, $key_not_used) use ($mysqli) {
return mysqli_real_escape_string($mysqli, $value);
});
$sql .= " AND province IN ('" . implode(',', $province) . "')";
}
$sql .= " ORDER BY surname";
Your SQL contains two WHERE's.
SELECT * FROM persons WHERE 1=1
AND firstname='fn'
AND surname='sn'
AND province='p'
WHERE province IN ($comma_separated)
ORDER BY surname
Change the last bit to:
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' AND province IN ($comma_separated)";
Which becomes:
AND province='p'
AND province IN ('Alberta','Ontario')
Change the last part to:
if ($province)
$sql .= " AND province IN (" . mysqli_real_escape_string($mysqli,$comma_separated) . ")";

Entering my WHERE into the query breaks it

So I have to add a WHERE query to this plugin I'm using for a reporting feature on a WordPress site. I have no time to do anything but add in another column and filter by the values in that column as there is not that much data to manage each update. The default value for the column I added is zero but I'll add new entries to represent years new people are added. However, when I filter based on the column value the whole query breaks and doesn't show up. I have no idea why. Here is the section involving its set up query displaying results.
<?php
$sql = "SELECT COUNT(*) FROM " . $wpdb->prefix . "presidentsreport_breakdown WHERE list_id = " . $atts['list_id'];
$total_breakdowns = $wpdb->get_var($sql);
$sql = "SELECT p.person_id, p.name, p.notes, p.school_year, b.breakdown_id, b.name as breakdown, b.description as breakdown_description FROM " . $wpdb->prefix . "presidentsreport_person p INNER JOIN " . $wpdb->prefix . "presidentsreport_breakdown b ON b.breakdown_id = p.breakdown_id INNER JOIN " . $wpdb->prefix . "presidentsreport_list l ON l.list_id = b.list_id";
$clean_where = " WHERE l.list_id = " . $atts['list_id'];
$where = "";
if($search != ''){
$where = " AND (p.name LIKE %s)";
$arg = '%' . $search . '%';
$args = array($arg);
}
$where = $wpdb->prepare($where, $args);
$order = " ORDER BY b.sort_order, b.breakdown_id, p.sort_name, p.name, p.person_id";
$results = $wpdb->get_results($sql . $clean_where . $where . $order);
?>
If I add anything in the variable $where it breaks the whole query. So if I add
<?php
$where = " WHERE p.school_year <= 2011";
?>
or
<?php
$where = " WHERE p.school_year = 0";
?>
Nothing will show up, For the last example if the default value is 0 everything should show up regardless. Thanks in advance for reading through!
Don't add WHERE to your variable. It is already assigned in $clean_where
$clean_where = " WHERE l.list_id = " . $atts['list_id'];
Here ------------^
You need to concatenate your addition parameters to the $where variable:
$where .= " AND p.school_year <= 2011";
There's no need of WHERE in where!

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