dynamic value sql - sql

My dropdown return value 2014 and 2015
<select><option value="2014">2014</option>
<option value="2015">2015</option>
</select>
and my query is:
$sql = "SELECT name, value
FROM sales
WHERE year IN ('2015') ";
How I can do my query dynamic, depend on dropdown?
Thank you!

Get the selected value, place it into a variable, then assemble the query string, concatenating the command and this variable.
I recommend some data binding framework to perform this kind of task for you.
What's your development environment? PHP?
Try this with PHP:
$stmt = $conn->prepare("SELE‌​CT name, value FROM sales WHERE year = :year");
$stmt->bind_param(":‌​year", $year); $year = $_POST['year'];
$stmt->execute()

Related

Date comparison on Kayako Query Language - KQL

I am using Kayako Querying Language and trying to get the query to return all closed/resolved, closed/unresolved, and review tickets from a specified month. When I run the query, every ticket ever comes up, and it seems to ignore the date function I am using. What am I doing wrong?
SELECT COUNT(*) AS Total
FROM ‘Tickets'
WHERE ‘Tickets.Creation Date’ = month(June 2016) AND ‘Tickets.Status’ = ‘Closed’ OR ‘Tickets.Status’ = ‘Resolved’ OR ‘Tickets.Status’ = ‘Unresolved'
GROUP BY ‘Tickets.Status'
Thanks.
Replace the date comparison in your WHERE clause for this:
WHERE 'Tickets.Creation Date':Month = 6 and 'Tickets.Creation Date':Year = 2016
Be also careful with the quotes, you sometimes use ‘ and others '

How to write database/SQL query in Yii2, with and without a model

I have a table with multiple column and I want to return a column name using another column name as search criteria. How do I achieve this in yii2?
Below is sample code, normal sql should be:
$name = SELECT type_name FROM ProductTable WHERE type_id = 1;
echo $name;
This should return the value of the column type_name where the value of the column type_id equals 1. I tried this, but it doesn't work
$type_name = ProductTable::find()->where(['type_id' =>$model->type_id]);
$type_name = Product::find(['type_name'])->where(['type_id' =>$model->type_id]);
I also tried this, but I guess it was wrong
I hope my question is clear enough and any help will he appreciated
and u could also use createCommand!
$name = \Yii::$app->getDb()->createCommand("SELECT type_name FROM ProductTable WHERE type_id=:typeId", ['typeId'=>$model->type_id])->queryAll();
For a general introduction to Yii2's ActiveRecord, see the guide: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
If you want the complete row and have a model, you're just missing a one():
Product::find()->where(['type_id' =>$model->type_id])->one();
If you do have a Model defined and just want a single value, try:
Product::find()->select('type_name')->where(['type_id' =>$model->type_id])->scalar();
Which basically generates an ActiveQuery via the model, and changes it to return only the first column in the first row of matched results.
If you do NOT have a model, you could also generate a normal query without ActiveRecord usage (http://www.yiiframework.com/doc-2.0/yii-db-query.html)
$name = (new Query())->select('type_name')
->from('ProductTable')
->where(['type_id' =>$model->type_id])
->scalar();
I assume you generated ProductTable by using Gii module.
Also, if type_id column is a primary key:
$product = ProductTable::findOne($model->type_id);
if($product !== null) { $product->typeName /*... read value ...*/}
or to get all records
$products = ProductTable::findAll($model->type_id); //match all records.
for any other column use the following syntax instead:
$product = ProductTable::findOne(['type_id' => $model->type_id]);
Use following code to get type_name
$PTable=ProductTable::find()->select('type_name')->where(['type_id' =>$model->type_id])->one();
echo $PTable->type_name;

How to count the number of rows with a date from a certain year in CodeIgniter?

I have the following query.
$query = $this->db->query('SELECT COUNT(*) FROM iplog.persons WHERE begin_date LIKE '2014%'');
I need to count the number of columns with a begin_date in the year 2014.
When I run this script I'm getting an error:
Parse error: syntax error, unexpected '2014' (T_LNUMBER) in C:\xampp\htdocs\iPlog2\application\controllers\stat.php on line 12
I was trying to change my CI script to
$query = $this->db->query('SELECT COUNT(*) FROM iplog.persons WHERE begin_date LIKE "2014%"');
but it caused an error.
You mean, count ROWS:
So for that, just count the number of rows you have based on a condition:
$year = '2014'
$this->db->from('iplog');
$this->db->like('begin_date', $year);
$query = $this->db->get();
$rowcount = $query->num_rows();
First, you have a simple typo regarding the use of single quotes. Your complete sql string should be double quoted so that your value-quoting can be single quoted.
Second, you are using inappropriate query logic. When you want to make a comparison on a DATE or DATETIME type column, you should NEVER be using LIKE. There are specific MYSQL functions dedicated to handling these types. In your case, you should be using YEAR() to isolate the year component of your begin_date values.
Resource: https://www.w3resource.com/mysql/date-and-time-functions/mysql-year-function.php
You could write the raw query like this: (COUNT(*) and COUNT(1) are equivalent)
$count = $this->db
->query("SELECT COUNT(1) FROM persons WHERE YEAR(begin_date) = 2014")
->row()
->COUNT;
Or if you want to employ Codeigniter methods to build the query:
$count = $this->db
->where("YEAR(begin_date) = 2014")
->count_all_results("persons");
You could return all of the values in all of the rows that qualify, but that would mean asking the database for values that you have no intention of using -- this is not best practice. I do not recommend the following:
$count = $this->db
->get_where('persons', 'YEAR(begin_date) = 2014')
->num_rows();
For this reason, you should not be generating a fully populated result set then calling num_rows() or count() when you have no intention of using the values in the result set.
Replace quotes like this :
$query = $this->db->query("SELECT COUNT(*) FROM iplog.persons WHERE begin_date LIKE '2014%'");
Double quote your entire query, then simple quote your LIKE criteria.

multiple parameter "IN" prepared statement

I was trying to figure out how can I set multiple parameters for the IN clause in my SQL query using PreparedStatement.
For example in this SQL statement, I'll be having indefinite number of ?.
select * from ifs_db where img_hub = ? and country IN (multiple ?)
I've read about this in
PreparedStatement IN clause alternatives?
However I can't figure it out how to apply it to my SQL statement above.
There's not a standard way to handle this.
In SQL Server, you can use a table-valued parameter in a stored procedure and pass the countries in a table and use it in a join.
I've also seen cases where a comma-separated list is passed in and then parsed into a table by a function and then used in a join.
If your countries are standard ISO codes in a delimited list like '#US#UK#DE#NL#', you can use a rather simplistic construct like:
select * from ifs_db where img_hub = ? and ? LIKE '%#' + country + '#%'
Sormula will work for any data type (even custom types). This example uses int's for simplicity.
ArrayList<Integer> partNumbers = new ArrayList<Integer>();
partNumbers.add(999);
partNumbers.add(777);
partNumbers.add(1234);
// set up
Database database = new Database(getConnection());
Table<Inventory> inventoryTable = database.getTable(Inventory.class);
ArrayListSelectOperation<Inventory> operation =
new ArrayListSelectOperation<Inventory>(inventoryTable, "partNumberIn");
// show results
for (Inventory inventory: operation.selectAll(partNumbers))
System.out.println(inventory.getPartNumber());
You could use setArray method as mentioned in the javadoc below:
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)
Code:
PreparedStatement statement = connection.prepareStatement("Select * from test where field in (?)");
Array array = statement.getConnection().createArrayOf("VARCHAR", new Object[]{"AA1", "BB2","CC3"});
statement.setArray(1, array);
ResultSet rs = statement.executeQuery();

Search select statement

I am creating a page which would have different field for the user to search from.
e.g. search by:
Grade: -dropdownlist1-
Student name: -dropdownlist2-
Student ID: -dropdownlist3-
Lessons: -dropdownlist4-
Year: -dropdownlist5-
How do I write the select statement for this? Each dropdownlist would need a select statement which would extract out different data from the database.
But, I want to write ONE select statement which can dynamically choose the dropdownlist options. Instead of writing many many select statement.
Lets say;
Grade: -dropdownlist1- ; default value(all)
Student name: -dropdownlist2-; default value(all)
Student ID: -dropdownlist3-; 0-100 is choosen
Lessons: -dropdownlist4-; A-C is choosen
Year: -dropdownlist5-; 2009 is choosen
It depends on the language you're using between SQL and the page. But test the dropdown for a non-generic value and then add in a where clause:
sql = "select * from people where 1 = 1";
if(dropdownlist.value != "All")
sql += "and name like '%" + dropdownlist.value + "%' ";
(watch out for SQL Injection though)
Extending to Tom's answer,
Create a view first which will contain the needed record set. Query on the view.