PHP/SQL fetch multiple values on SUM SQL statement - php

This is a bit of a complicated issue to explain but here goes:
I have an SQL statement:
SELECT
SUM(time.timein),
time.reasonforabsence
WHERE
staff.id = time.staff_id
AND
staff.department_id = department.id
AND
(staff_name LIKE '%$staffsearch%')
GROUP BY
staff.id
ORDER BY
time.dateadded
ASC;
From this statement I need to pull the values time.reasonforabsence but as this is text and the statement is grouped, I cannot seem to do this. Does anyone know if there is a way for me to pull them possibly into a PHP array.
The time.reasonforabsence has multiple possible values.
Sorry for the vagueness I am writing this in a rush. Let me know if there is anymore info needed and I will add it tomorrow.

What you can do is return an aggregated string
SELECT
SUM(time.timein),
GROUP_CONCAT(time.reasonforabsence)
...
You can optionally use DISTINCT if you don't want repeated reasons. On php you'll have split them

Related

PHP - Remove quotes in MySQL query [duplicate]

I am trying to refer to a column name to order a query in an application communicating with an Oracle database. I want to use a bind variable so that I can dynamically change what to order the query by.
The problem that I am having is that the database seems to be ignoring the order by column.
Does anyone know if there is a particular way to refer to a database column via a bind variable or if it is even possible?
e.g my query is
SELECT * FROM PERSON ORDER BY :1
(where :1 will be bound to PERSON.NAME)
The query is not returning results in alphabetical order, I am worried that the database is interpreting this as:-
SELECT * FROM PERSON ORDER BY 'PERSON.NAME'
which will obviously not work.
Any suggestions are much appreciated.
No. You cannot use bind variables for table or column names.
This information is needed to create the execution plan. Without knowing what you want to order by, it would be impossible to figure out what index to use, for example.
Instead of bind variables, you have to directly interpolate the column name into the SQL statement when your program creates it. Assuming that you take precautions against SQL injection, there is no downside to that.
Update: If you really wanted to jump through hoops, you could probably do something like
order by decode(?, 'colA', colA, 'colB', colB)
but that is just silly. And slow. Don't.
As you are using JDBC. You can rewrite your code, to something without bind variables. This way you can also dynamically change the order-by e.g.:
String query = "SELECT * FROM PERS ";
if (condition1){
query = query+ " order by name ";
// insert more if/else or case statements
} else {
query = query+ " order by other_column ";
}
Statement select = conn.createStatement();
ResultSet result = select.executeQuery(query);
Or even:
String columnName = getColumnName(input);
Statement select = conn.createStatement();
ResultSet result = select.executeQuery("SELECT * FROM PERS ORDER BY "+columnName);
ResultSet result = select.executeQuery(
"SELECT * FROM PERS ORDER BY " + columnName
);
will always be a new statement to the database.
That means it is, like Thilo already explained, impossible to "reorder" an already bound, calculated, prepared, parsed statement. When using this result set over and over in your application and the only thing, which changes over time is the order of the presentation, try to order the set in your client code.
Otherwise, dynamic SQL is fine, but comes with a huge footprint.

select from a select statement in php & mySQL

I am trying to add filters to a DB search. I have a search that takes some text and tries to find items with that text in the title. I also have a price range filter. That code is below and works just fine
$sql = "SELECT * FROM items where title LIKE '%". $title ."%' AND price > '". $price1 ."' AND price < '".$price2."' Limit 70";
Now I am trying to more and more filters. Is there a select from the above code's output? I don't want to just keep making a longer SELECT statement with tons of if statements. I'd prefer to take the output of the previous select and refine that with another select. Is this possible?
EDIT 1 Context:
Users are the ones entering the information. This is for searching the items on my site.
There's no other useful way than adding lots of different conditions to your WHERE cause, if you use plain SQL. It is possible to use several nasted SELECT statements in your query, but this makes your code neither any more readable nor faster.
A more elegant solution is the usage of query objects or another form of object-oriented query abstraction (e.g. ZendDB).
You can use some of the mysql string functions like INSTR(), MATCH which will make your life a little easy and also help the readability of the code.
You can also use REGEXP and NOT REGEXP for pattern matching . The list of string functions are here.

Make SQL recognize a variable from PHP/html selected option

I think the answer to this may be simple, but being new to SQL I am still growing. Here's my dilemma. I have a php array of options with 10 values. When any one option is selected it is passed into a variable named "spots". I have 10 SQL SELECT statements that pull 1 of 10 different tables. The issue is that I do not know exactly what to do in order to get the SQL to recognize which value was selected and based on which was selected show that specific table data. (This would be easy if I were able to use the JavaScript Switch statement, but I do not know an equivalent for that)
EXAMPLE:
PHP
$spots = ["Report1","Report2","Report3","Report4","Report5","Report6","Report7","Report8","Report9","Report10"];
SQL
SELECT *, FROM Report5
ORDER BY TW ASC;
Now how do I get SQL to loop through an array to find a match, then depending on that match select from a list of commands (for example like a JavaScript switch statement)?
Use variable substitution:
foreach ($spots as $spot) {
$sql = "SELECT * FROM $spot ORDER BY TW ASC";
// perform the SQL query using $sql, do what you want with the results
}
Make sure you've validated that the values in $spots are valid if they're coming from the user. Otherwise you'll be subjecting your code to SQL injection.

Combining two PHP sql statements into one

I'm after a little help in the quest for cleaner code...
Current code which is working fine. Wondering if I can make it into one SQL statement as opposed to two...
$sql = "INSERT INTO table_a (1,2,3,4) VALUES ('$1','$2','$3','$4');";
$result = mysql_query($sql,$mysql_link);
$id = mysql_insert_id();
$sql2 = "INSERT INTO table_b (1,2,3,4) VALUES ('$id','$5','$6','$7');";
$result2 = mysql_query($sql2,$mysql_link);
How can I combine these two to work within my current php script?
Thanks!
An insert in two different tables is not possible.
If you want to reduce your query count you may have to reconsider your database structure.
As mentioned above, you can't combine them, because inserts are in 2 different tables, although you could write a stored procedure (with necessary parameters) containing both of these queries and call that procedure in PHP instead of writting those statements... It would help to tell the reason you want to do that, because i can't understand if you want to get more compact (reusable) code, or improve the performance of your DB...
When I see another question of this kind, I am always wondering, why noone asks how to combine ALL sql queries of the script into one. All SELECTs, INSERTS, UPDATES. Wouldn't it be logically?
What's the strange desire to combine? What's the point in it? What's wrong in 2 separate queries?
When you eat, do you mix a salad, a soup, a main dish, a drink into one bowl and then consume it? No? Why do you want to put all the queries into same bowl then?

Query a Query - MySQL and PHP

I was recently trying to do a project*, which caused me to ask this question. Although since then I've found an alternative solution, I am still curious if what I envisioned doing is, in any way, possible.
Essentially, I am wondering if there is anyway to perform a MySQL query on a MySQL query result in php. For example:
$result = mysql_query("SELECT * FROM foo WHERE bar=".$barValue);
AND THEN, be able to perform multiple queries on $result:
$newResult = mysql_query("SELECT * FROM $result WHERE otherBar=".$barValue);
OR
$otherNewResult = mysql_query("SELECT * FROM $result WHERE otherOtherBar=".$barValue." ORDER BY foobar ASC");
AND so on and so forth...
I realize that I could append the original query with my new WHERE statements and ORDER BYs, but that causes my to query the database unnecessarily and it prevents me from writing more objected oriented code (because I can't pass around a result to be queried, but rather have to requery the database in every function...)
Any advice, pieces of code, frameworks, or ramblings appreciated.
*BTW, my project was having to query a large database of people for people born in certain age groups and then query those age groups for different demographics.
Edit
No, writing a custom function to query the database is not worth the object-orientation (and modifiability) it would give me
You could do a nested query in the same SQL query and keep PHP out of it:
'SELECT * FROM (SELECT * FROM foo WHERE bar="something") AS q1 WHERE q1.bar2 = "something else"'
The question has already been answered. However following explanation will help someone who might be interested in knowing the details of it.
What are Nested query / subquery:
Subqueries are also known as nested queries. A subquery is a SELECT statement within another statement. MySQL supports all SQL standards and additionally provides MySQL specific features.
Why should I use Subquery:
Subquery is structured and it is possible to isolate each parts of statement
Subquery is more readable that complex joins and unions
Subquery provides alternative means to perform action which otherwise would require complex joins and unions
What Subquery returns:
A subquery can return a single value, a single row, a single column, or a table. These are called scalar, column, row, and table subqueries.
Reference: http://dev.mysql.com/doc/refman/5.7/en/subqueries.html
http://www.w3resource.com/sql/subqueries/nested-subqueries.php

Categories