I have this query in my PHP class:
$this->query = "SELECT a.x, b.y, c.z FROM aaa a INNER JOIN bbb b ON b.ida = a.ida ";
$this->query.= "INNER JOIN ccc c ON c.idb = b.idb WHERE a.ida = :ida";
$this->stmtparam = array(':ida' => $this->ida);
return parent::fillArray(); // it fills a PDO FETCH_ASSOC array and returns it as JSON
suppose that this is a 10 times more complicated query and I have many of this in a company information system;
My question is: Is it possible to make an stored function in postqresql which do the same and returns a SET of many tables, then fetch the results into an associative array in php?
Does it worth to do it?
postgresql does not have stored procedures, but you can write a function which is essentially the same thing. I prefer to put complex queries into a function. This way you can make fixes and performance improvements on the database side instead of having to push out new PHP code each time.
Here's a resource that demonstrates how to create a pg function and call it from PHP:
http://pgedit.com/resource/php/pgfuncall
Related
I am trying to get a list of calendars - some public some private. Access to the private calendars is managed through a bridging table that lists calendar id (ccalId) and user id (cuserId). I can achieve this but using 3 SQL queries.
Is it possible to achieve this using just one query? I have tried JOINs but it never seems to work.
$calModel->where('calTeam',session()->get('teamId'));
$calModel->where('calType','public');
$calModel->where('calStatus','active');
$data = $calModel->get()->getResultArray();
$calUserModel->select('ccalId');
$calUserModel->where('cuserId', session()->get('id'));
$callist = $calUserModel->get()->getResultArray();
$newarray = implode(", ", $callist);
$calModel->where('calTeam',session()->get('teamId'));
$calModel->whereiI('id', $newarray);
$data2 = $calModel->get()->getResultArray();
$data = array_unique(array_merge($data,$data2), SORT_REGULAR);
Not every time the codeigniter query builder is the best solution. In my opinion for more complex queries it is better to do direct query to the database, instead of using models.
You can easily do a query with 2 joins to get all the results without the useless data. That would work faster and would look cleaner in your code.
I need to execute my function inside a query like this
$re = $bddp->prepare("SELECT * FROM `shop`, `hours` WHERE isOpen('`hours`.`day1`') = true";
$re->execute();
hours.day1 is a varchar with opening hours of monday like this "10:00-14:00"
Function isOpen test if its open or not and return true or false
The question is who i can send hours.day1 like a variable into isOpen function in WHERE isOpen('hours.day1') ?
Its not possible to use PDO prepare or execute for this ?
In the SQL query you can use only MySQL native functions, stored functions/procedures and User-Defined Functions (UDF).
I think that you would not have a problem if the table structure was right (start-end times were in the separate columns). Then you would able to achieve your goal only with a few conditions in the WHERE part.
If the data amount (rows count) is not big, then you can just select all rows and done the validation in the PHP side.
I'm new to OO PHP and I have created a Database Class, And I have a problem when I build My SELECT Query With the JOIN method.
If I do the Querys in Functions.
<?php
require_once("class.Database.php");
function test1($db) {
$test1 = $db->Select("*")
->From("Table1")
->Join("Table2","table_2_id = table_1_id")
->Join("Table3","table_3_id = table_2_id")
->BuildSelect();
return $test1;
}
function test2($db) {
$test2 = $db->Select("*")
->From("Table4")
->Join("Table5","table_5_id = table_4_id")
->Join("Table6","table_6_id = table_5_id")
->BuildSelect();
return $test2;
}
echo test1($db);
echo "<br>";
echo test2($db);
?>
The problem is that the First function - test1 will print out -
SELECT * FROM Table1 LEFT JOIN Table2 ON table_2_id = table_1_id LEFT JOIN Table3 ON table_3_id = table_2_id - Which is good
But then the second function test2 will print out -
SELECT * FROM Table4 LEFT JOIN Table2 ON table_2_id = table_1_id LEFT JOIN Table3 ON table_3_id = table_2_id LEFT JOIN Table5 ON table_5_id = table_4_id LEFT JOIN Table6 ON table_6_id = table_5_id
The test2 function seems to be printing out the Values from the test1 function's JOIN method as well as its own Values from the JOIN method.
Can someone please help.
Your addition of the Reset() method is what you needed.
All of your member variables except your join array were being reset on each call. For example:
$this->where = trim($where);
Which will replace your where member every time you call your Where() method. In contrast, you are doing this in your Join() method:
$this->join[] = ...
Which adds a value to the end of the member array rather than rewriting what is already in the array. It has the same affect as using array_push() (see here)
One last suggestion I was going to make was to call Reset() at the end of BuildSelect() so that you wouldn't have to remember to do so in your queries, but it looks like you did that. My recommendation, however, would be to change this:
self::Reset();
To this:
$this->Reset();
In reality, either will work and PHP makes them functionally the same for what you are trying to accomplish, but other languages aren't as forgiving. :: is designed to be used to call static members, but earlier versions of PHP do the "automagic" thing of realizing that you are calling from an instantiated class and treating self:: the same as $this->
My understanding is that later versions of PHP (5.3+) refer to what is contained in scope at the point of definition, not the point of execution when you use self::. In most cases, you are going to want to reference the scope of the class at execution time. The two notes I have about that are:
I have never allowed the use of self:: when $this-> is
appropriate, so what I am saying here is only hearsay (I have
never tested it to be true)
Given the fact that your Reset() method doesn't do any form of
logic on instantiated variables, it won't have any adverse affect on
the specific code you are using. But it is best to start with good
coding habits. Some time down the road, this practice WILL bite you if you
continue coding in PHP.
PHP can be great when you are first learning, but the things that make it great for learning often come back to haunt you when you get to making any project of long-lasting consequence if you are not coding deliberately.
Helo,
I have a stored procedure that has 7 IN parameters and 3 OUT parameters.
I need to pass 7 parameters IN from PHP, execute the query with procedure, and retrieve the 3 OUT parameters.
I am using mysqli with persistent connection mode enabled. (For load considerations)
What is the most efficient way to execute the query and get results?
I need something that doesn't affect other concurrently running PHP scripts, and that cleans the result itself, and that is straightforward.
This is what my application is (simplified) (not a working example, just how i wish it was)
$inParam1 = 'wer';
$inParam2 = 'fewf';
$inParam3 = 'dsf';
$inParam4 = 'vccv';
$inParam5 = '34t3';
$inParam6 = 'ter';
$inParam7 = 'ert';
$query = "CALL my_procedure('$inParam1', '$inParam2', '$inParam3', '$inParam4', '$inParam5', '$inParam6', '$inParam7', #outParam8, #outParam9, #outParam10); SELECT #outParam8, #outParam9, #outParam10;";
$result = $mysql_query($query);
list($outParam1, $outParam2, $outParam3) = mysql_fetch_array($result);
echo $outParam1; // String param #1 that my procedure returned as an OUT variable
echo $outParam2; // String param #2 that my procedure returned as an OUT variable
echo $outParam3; // String param #3 that my procedure returned as an OUT variable
If somebody could show how this code could look in reality, please please would be great!
I am obviously using mysqli with proper connection, and such, but the examples I have found in internet are really confusing and seem to be inefficient, I am also worried if it will conflict with other clients, because it works like "nextResult" and other some strange functions.
Many thanks!
PHP 5.3, MySQL 5.5
Try looking here. As im not overly familiar with this. :)
http://www.mysqltutorial.org/stored-procedures-parameters.aspx
You need to create a query first. This query will then be stored in the database as a callable procedure. Then later using whatever language you can call the procedure.
DELIMITER //
CREATE PROCEDURE GetUserByCountry(IN countryName VARCHAR(255))
BEGIN
SELECT name, email
FROM users
WHERE country = countryName;
END //
DELIMITER ;
Then calling it.
CALL GetUserByCountry('mexico')
Returns all users names and emails who live in mexico.
I believe if you want to create a dynamic query string such as yours, you need to put {} around your variables in the string.
$query = "CALL my_procedure('{$inParam1}', '{$inParam2'}, '{$inParam3}', '{$inParam4}', '{$inParam5}', '{$inParam6}', '{$inParam7}', #outParam8, #outParam9, #outParam10); SELECT #outParam8, #outParam9, #outParam10;";
I am using MVC with PHP/MySQL.
Suppose I am using 10 functions with different queries for fetching details from the database.
But at other times I may want to get only the count of the result that will be returned by the query.
What is the standard way to handle such situation.
Should I write 10 more functions which duplicate almost whole query and return only the count.
Or
Should I always return the count also with the result set
Or
I can pass a flag to indicate that the function should return count only, and then based on the flag I will dynamically generate the (select part of) query.
Or
Is there a better way?
Now that mysql supports sub-queries, you can get counts for any query using:
$count_query="SELECT COUNT(*) FROM ($query)";
How hard was that?
However this approach always means that you are running two queries instead of just the one (I'm not sure if MySQL would necessarily be able to use a cached result set for the count - try it out and see).
If you've already fetched the entire result set it'll probably be faster counting the rows in PHP than issuing another query.
There are 2 functions in MySQL which would return the number of matched rows prior to application of a limit statement:
SQL_CALC_FOUND_ROWS and FOUND_ROWS()
see
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
C.
If you want only number of rows matched certain criteria, you shouldn't use a count of the result, but another query that select only count(*) instead.
If you need both data and it's count, why don't you just use count() on the resulting array?
another way is to use some class that can return both data and it;s count, but not different classes for the each 10 queries but one single database access class.
I'd go with the flag idea.
Writing 10 more functions and copy/pasting code does not help readability at all. If you always also return the count, that means that whenever you're only interested in the count, the database still has to generate and transmit the full result set which might be grossly inefficient.
With the flag, you'd have something like
function getData($countOnly=false) {
// ...generate FROM and WHERE clause
if ($countOnly) {
$query = 'SELECT COUNT(*) '.$query;
} else {
$query = 'SELECT field1, field2, ...'.$query.' ORDER BY ...';
}
...
}
I would generally try to have as much code as possible shared between methods. A possibility would be to :
have one select() and one count() functions
each one building the specific part of the query
and one buildFromAndWhere() function to build the parts of the query that are common.
and have select() and count() use that one
Written in pseudo-code, it could look a bit like this :
function select($params) {
return "select * "
. from()
. where($params)
. "limit 0, 10";
}
function count() {
return "count(*) as nbr "
. from()
. where();
}
function from() {
return "from table1 inner join table1 on ... ";
}
function where($params) {
// Use $params to build the where clause
return "where X=Y and Z=blah";
}
This way, you have as much common code as possible in the from() and where() functions -- considering the hard part of the queries is often there, it's for the best.
I prefer having two separate functions to select and count ; I think it make code easier to read and understand.
I don't like the ideas of one method returning two distinct data (list of results and the total count) ; and i don't really like the idea of passing a flag either : looking at the function's call, you'll never know what that parameter means.