How to write select Query in MySQL? - mysql

I want to write a select query where i user have to pass two input ID and SourceID.
But here is the twist, Input ID is mandetory and SourceID is Optional. I want to write a select query where if a user passes only Input ID then my select query will filter data based on ID but if user passes both ID and SourceID then user should Get Data based on Both Filters.
I am pretty much new to database query so i am not able to figure out how to do this?
My request body:
<body>
<p:GetEntryByID xmlns:p="http://abcFarm.org/">
<!--Exactly 1 occurrence-->
<xs:ExistingID xmlns:xs="http://abcFarm.org/">?</xs:ExistingID>
<!--0 to 1 occurrence-->
<xs:TargetSourceID xmlns:xs="http://abcFarm.org/">?</xs:TargetSourceID>
</p:GetEntryByID >
</body>
I have written a sql query which is not working as:
select * from entry WHERE ID='ID1' AND (e.SourceID='SourceID1' Or ID='ID1');
But this is not fulfilling my above need.
Please Help.Thanks in advance.

Try this,
SELECT *
FROM entry
WHERE ID = 'ID1' AND
SourceID = COALESCE('SourceID1', SourceID)
What it means is that when NULL is passed in SourceID1, the value that will be compared with column SourceID is the value of the column itself.

$id = "Your_ID1";
$SourceID1 = "Your_SourceID1";
if($id){
$query = "select * from entry WHERE ID=$id";
if($SourceID1){
$query .= " AND SourceID = $SourceID1";
}
$query .= ";";
}

Related

How to compare Comma Seperated value to get existing value

I have Table as Production with field name as production_code
Production_code have value like this,
Id production_code
1 P101,P102,P103,P105
2 P103,P106,P102
3 P104
4 P102,P105,P111
------ I have value on PHP page like $p_code='P102,P109';
Now I want to fetch rows from Table Production_code where any code is exist in production_code of variable $p_code
please help me .. what mysql query should i use
You can use function FIND_IN_SET, like:
SELECT * FROM yourTable
WHERE FIND_IN_SET('P102', production_code) OR FIND_IN_SET('P109', production_code)
Solution.
<?php
$p_code='P102,P109'; //example
$condition = '';
foreach(explode(',',$p_code) as $r){//explode convert $p_code string into array. then apply foreach for compare every element of array From database saved value
$condition .= 'FIND_IN_SET("'.$r.'", production_code) OR ';
}
$condition = rtrim($condition,' OR '); //this remove last occurence of OR from condition
echo $sql = 'SELECT * FROM yourTable
WHERE '.$condition;
?>

What's wrong with this SQL query WHERE AND clause?

Previously, this was working:
$patient_story_set_photos = $wpdb->get_results('SELECT * FROM wp_before_after WHERE patientID = '.$post->ID.' AND patient_display = 1');
However, when I try to add another AND condition like this:
$patient_story_set_photos = $wpdb->get_results('SELECT * FROM wp_before_after WHERE patientID = '.$post->ID.' AND patient_display = 1 AND period_taken = '.$set->period_taken);
I get the following error on screen:
WordPress database error: [Unknown column '1hour' in 'where clause']
SELECT * FROM wp_before_after WHERE patientID = 8175 AND patient_display = 1 AND period_taken = 1hour
Can't see why there's a problem, are you not allowed to use multiple AND conditions in SQL?
The problem is not the AND, the problem is your 1hour, 1hour unquoted means a reference to an object (database, table) named 1hour, you need to quote '1hour'.
If you write
SELECT * FROM wp_before_after
WHERE patientID = 8175
AND patient_display = 1
AND period_taken = '1hour'
you will compare the field periodtaken to a string (CHAR,VARCHAR,TEXT) equal to '1hour'.
I assume period_taken is a field typed CHAR,VARCHAR or TEXT
Before anything, DO NOT CONCATENATE SQL STRINGS nowadays it is a MUST (see how to do it properly https://stackoverflow.com/a/60496/3771219)
The problem you are facing is because, I presume, that the period_taken field is some sort of Char/Varchar/String field and when you are filtering by a "Stringy" field you must sorround your literals values with single quotes:
SELECT *
FROM wp_before_after
WHERE patientID = 8175
AND patient_display = 1
AND period_taken = '1hour'
Hope this help

mysqli select from two tables with one of them have multiple records

<?php
select1($conn);
function select2 ($conn,$id ,$name)
{
$stmt = $conn->prepare("SELECT def FROM define WHERE wordkey = ?");
mysqli_stmt_bind_param($stmt, 'i', $id);
$stmt->execute();
$stmt->bind_result($def);
while($stmt->fetch()) {
echo "here"; // for testing
$wordArray += $def;
//I will make a call to the js function here sending id, name and wordArray
}
//$stmt->close();
}
function select1 ($conn){
$stmt2 = $conn->prepare("SELECT id , name FROM words");
$stmt2->execute();
$stmt2->bind_result($id, $name);
while($stmt2->fetch()) {
select2 ($conn,$id ,$name);
}
}
?>
I want to ask question I have words table and def table. in def table i have multiple definitions for the same words.id. Is it possible to select them in one query statement ?
words table have id , name
def table have id, wordkey , definition
I want to retrieve name and for each name select all its definitions so that I will then call a javascript function (id, name, defArray)
to display each name with the array of its definitions.
I thought of doing it through 2 select statement, but the problem is the select2 function is not working.
As I can assume from the very limited details from your question.
Try
select a.name, b.definition from words a, def b where a.id=b.word_id
In the above query we are simply accessing the data from multiple tables.
Please supply some more explanation (possibly with code) for precise bug fixings.
Hope it helps, All the best!
Assuming the following:
words
ID | Word
definitions
ID | WordID | Definition
SELECT D.Definition AS definition, W.Word AS word
FROM definitions D, words W
WHERE W.ID = D.WordID
ORDER BY W.Word ASC
This will display rows of definitions, ordered by the word they correspond to.

Get results from WPDB

I have this scenario that I can't figure out:
Inside table wp_comment I need to list all user_id (not duplicate) with comment_type=complete.
I tried this:
$results = $GLOBALS['wpdb']->get_results( "SELECT * FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'", ARRAY_A );
$corsisti = $results[user_id];
// I need to print only ids to put this array in
get_users( include=> '$corsisti' )
The database screenshot:
You can use the wpdb::get_col() method to retrieve an array with values from a single column:
$corsisti = $GLOBALS['wpdb']->get_col( "SELECT `user_id` FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'");
Then simply use the result in get_users (you do not need the quotes):
$users = get_users( include=> $corsisti );

SQL SELECT with table name in query

I have simple query:
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query("SELECT DATE(date_time) AS day_h
FROM `$table_name`
");
and it is working ok.
But I must do this query with table name and when I try this:
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query("SELECT `$table_name`.DATE(date_time) AS day_h
FROM `$table_name`
");
or
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query("SELECT v_c_holi_2012.DATE(date_time) AS day_h
FROM `$table_name`
");
this is not working (Fatal error: Call to a member function fetch_assoc() on a non-object).
What I 'm doing wrong?
The date function should not have the table prefix since it is a system function.
Instead you need to put the table alias before your field date($table_name.date_time).
By the way, you don't need to if you select from only one table.
I believe $table_name.DATE(date_time) should be DATE($table_name.date_time)
You should apply the table name to the thing that's in the table (i.e. the field name), not the DATE function (which has nothing to do with your table).
i.e.
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query(
"SELECT DATE(`$table_name`.`date_time`) AS `day_h`
FROM `$table_name`"
);