I am wondering if you can make the Table name of the propel query dynamic(sort of like a variable variable)? An example would be like \"DynamicVar"Query::create(). I have it working in ifs like in my example below, but could get rid of quite a few lines if made more dynamically. The tables are all setup the same, so they can be treated like the same object they just have different names.
Currently have something like this happening:
//$dynamic is a result of grabbing it from a different table
//that corresponds to values passed by AJAX
$dyanmic = "Customer"
$query = null;
If( $dynamic == "Customer" ) $query = \CustomerQuery()::create();
If( $dynamic == something2 ) $query = \Table2Query()::create();
If( $dynamic == something3 ) $query = \Table3Query()::create();
If( $query != null ) {
$query->filterBy("something");
$query->find();
}
I played around with the code some, and the code below will work for dynamically changing the table as long as each table can be treated like the same object. You can define your $table and use it in this fashion for a function that returns the object that you want
function Get_Table($table,$id){
$query = null;
$queryClass = '\\'. ucfirst($table) . 'Query';
if ( class_exists( $queryClass ) ) {
$$dynamics = $queryClass::create()
->filterById($id)
->find();
if( $dynamics->getFirst() == null ) { return false; }
/** #var \Base\.ucfirst($table) $dynamic*/
$dynamic= $dynamics->getFirst();
return $dynamic;
}
//On Failure
else {
return false;
}
}
Related
I am trying to pull dynamic content from a database based on the wildcard subdomain.
Please see the code below.
<?php
$data = $_GET['get'];
$data = addslashes(str_replace('-',' ',$data));
$town_result = $database->getData("select * from nationwide where town = '$data' ");
if( is_object( $town_result ) )
{
$area = $town_result->fetch_assoc();
}
else
{
$region_result = $database->getData("select * from nationwide where region = '$data' ");
if( !is_object( $region_result ) ) {
header('Location: http://example.com');
}
$area = $region_result->fetch_assoc();
$area['town'] = $area['region'];
}
?>
I have tried changing = '$data' "); to LIKE '%" . $data . "%'"); but this only pulls the first row in my database.
You can review how to use fetch_assoc to get associative records.
https://www.php.net/manual/en/mysqli-result.fetch-assoc.php
You can print $area, then you can verify either array count is 1 or more than 1.
Or best way, you can print sql query and run directly in your db.
I'm getting a error 500 when i try to select something from the database:
I've test it without the select function and just return a random string and it worked. But when i try to get a value from the database i'll get an error 500.
This is the function:
public function seasons_rules($CheckIn)
{
$Request = $this->db->get_results(
$this->db->prepare(
"SELECT A.rule_id
FROM $this->booking_rules_seasons_table AS A
INNER JOIN $this->seasons_dates_table AS B
ON B.season_id = A.seasons_id
INNER JOIN $this->booking_rules_table AS C
ON A.rule_id = C.id
WHERE ('%s' BETWEEN B.start_date AND B.end_date) OR C.all_seasons = 1
",$CheckIn), ARRAY_A);
$RulesIDs = '';
if ( ( $Request == NULL ) || ( count( $Request ) == 0 ) ) {
return false;
} else {
foreach ($Request as $response) {
$RulesIDs .= $response['rule_id'].',';
}
return $RulesIDs;
}
}
When i run the query directly into database. I'll get a result back so there isn't any errors in the query.
You're passing the variable inside the string in the wrong way.
If you want to pass a variable of an object inside a string, you use this syntax:
echo "This is my string: {$obj->string}";
You're passing the variable directly without the braces.
I am having some trouble in returning values from model to controller Using CodeIgniter. I am passing two arrays from controller to model. I am checking whether both the arrays are not empty and looping them using foreach loop to fetch some values from database and returning the query to controller. Here's my current code
if (!empty($search_for_area) && !empty($search_for_requirement))
{ foreach($search_for_requirement as $search_value_1)
{
foreach($search_for_area as $search_value_2)
{
if($search_value_2 != null && $search_value_1 != null)
{
$nearbytution = $this->db->query('select name,area,contactno from tut_listing where area = "'.$search_value_2.'" and categoryfilter like "%'.$search_value_1.'%" and partner > "" group by name');
print_r($nearbytution->result());
}
}
}
//Line 1
}
print_r($nearbytution->result()); works fine and i am able to view the results. Where should i put return $nearbytution; so that i can get all the fetched values? I tried it in Line 1 but i was getting only values of last array value.
function returnStuff($search_for_area,$search_for_requirement) {
$arr_area = array();
$arr_filter = array();
if ( ! empty($search_for_area) and ! empty($search_for_requirement)) {
foreach($search_for_requirement as $search_value_1) {
foreach($search_for_area as $search_value_2) {
if($search_value_2 != null && $search_value_1 != null) {
$arr_area[] = $this->db->escape($search_value_2);
$arr_filter[] = $this->db->escape_like_str($search_value_1);
}
}
}
}
$str_area = 'NULL';
if ($arr_area)
$str_area = implode(', ', $arr_area);
$str_filter = "'^-$'";
if ($arr_filter)
$str_filter = "'(".implode('|', $arr_filter).")'";
$query = $this->db->query("
SELECT name, area, contactno
FROM tut_listing
WHERE area IN ({$str_area}) AND categoryfilter REGEXP {$str_filter} and partner > '' group by name
");
return $query->result();
}
Seriously, do consider this approach. You only need to bother the poor Mysql server with one call and you get all the data you want at the same time.
Apart from that, practice consistent style in your code. It will save both your time and your hair in the long run.
CodeIgniter escape()
MySQL REGEXP
Try this in the loop:
$nearbytution[] = $this->db->query('select name,area,contactno from tut_listing where area = "'.$search_value_2.'" and categoryfilter like "%'.$search_value_1.'%" and partner > "" group by name')->result();
return $nearbytution;may then be placed at your "Line 1". It will contain an array of query results.
Unless I misunderstand your question why don't you just store all the results in a big array and then return that array?
function returnStuff($search_for_area,$search_for_requirement) {
$data = array();
if (!empty($search_for_area) && !empty($search_for_requirement)) {
foreach($search_for_requirement as $search_value_1) {
foreach($search_for_area as $search_value_2) {
if($search_value_2 != null && $search_value_1 != null) {
$nearbytution = $this->db->query('select name,area,contactno from tut_listing where area = "'.$search_value_2.'" and categoryfilter like "%'.$search_value_1.'%" and partner > "" group by name');
$data[] =$nearbytution->result());
}
}
}
}
return $data;
}
Now $data will be an array of results, each containing the query results. If your result set has to be cleaned up (to remove duplicates for instance) you can just loop through it and do that cleanup.
What you could also maybe do is build a large SQL query in your foreach loops and then just do that one big query and return the results.
I want to call a PHP function :
$rights = $user->recupererDroitCreateur($_SESSION[CODE_USER]);
Code of recupererDroitCreateur is :
function recupererDroitCreateur($user_id) {
$ret = array();
$sSQL = "SELECT cm.class_menu_code
FROM menu m
LEFT JOIN classe_menu cm
ON m.class_menu_code = cm.class_menu_code
WHERE m.menu_deleted = 0 AND m.menu_visible = 1 AND cm.class_menu_parent IS NULL AND cm.class_menu_deleted = 0
ORDER BY cm.class_menu_lib, m.menu_titre";
$this->db->query($sSQL);
while ( $this->db->next_record() ) {
$code = $this->db->f('class_menu_code');
$strMenus = $code.";";
$this->recupererMenus($code, $code, $user_id, $strMenus);
}
return (explode(";", $strMenus));
}
Code of recupererMenus is :
function recupererMenus($classRoot, $classParentDirect, $user_id, &$menus)
{
$sSQL1 = "SELECT class_menu_code FROM classe_menu WHERE class_menu_parent = '$classParentDirect' AND class_menu_deleted = 0";
$this->db->query($sSQL1);
while ( $this->db->next_record() ) {
$this->recupererMenus($classRoot, $this->db->f('class_menu_code'), $user_id, $menus);
}
$sSQL = "SELECT m.menu_code
FROM menu m
LEFT JOIN classe_menu cm
ON m.class_menu_code = cm.class_menu_code
WHERE m.menu_deleted = 0 AND m.menu_visible = 1 AND cm.class_menu_parent = '$classParentDirect' AND cm.class_menu_deleted = 0
ORDER BY cm.class_menu_lib, m.menu_titre";
$this->db->query($sSQL);
while ( $this->db->next_record() )
{
$menus .= $this->db->f('menu_code').";";
}
}
In runtime there is the error next_record called with no query pending : the error output tells the lines which cause the error and it says the line corresponding to this statement : while ( $this->db->next_record() ) { , there is also line pointing to the statement $this->recupererMenus($code, $code, $user_id, $strMenus);
So what is wrong in my codes ?
In recupererMenus you recursively call recupererMenus. Since there's no query identifier passed to next_record, using multiple querys will create a big mess.. When you return from the recursive call, you are going to try to fetch the next record with next_record for a previous query, but your DB framework doesn't know about this..
I don't know the framework you use, but you either have to pass the identifier (if it's possible at all), or first fetch all the results, and then do the recursive call.
I'm trying to write a single function that queries a database, with results dependent on what is passed.
So far I have the following, but I can't help thinking there's a more succinct way to achieve this.
Additionally if I use a value of 0 all results get returned - like the 0 is a value of false, even if I pass it as a string.
I notice within WordPress strings are passed into functions (e.g. cat=1&posts_per_page=5). I couldn't quite figure out how this worked, but it looks like a nicer way of doing things.
Any help appreciated.
public static function sub_packages($subname_id = false, $region_id = false, $recurrence = false) {
global $wpdb, tbl_packages;
if ( $subname_id ) $subname_id = " `package_subname` = $subname_id";
if ( $region_id ) $region_id = " `package_region` = $region_id";
if ( $recurrence ) $recurrence = " `package_recurrence` = $recurrence";
// one
if ( $subname_id && !$region_id && !$recurrence )
$filter = " WHERE $subname_id";
elseif ( !$subname_id && $region_id && !$recurrence )
$filter = " WHERE $region_id";
elseif ( !$subname_id && !$region_id && $recurrence )
$filter = " WHERE $recurrence";
// two
elseif ( $subname_id && $region_id && !$recurrence )
$filter = " WHERE $subname_id AND $region_id";
elseif ( $subname_id && !$region_id && $recurrence )
$filter = " WHERE $subname_id AND $recurrence";
elseif ( !$subname_id && $region_id && $recurrence )
$filter = " WHERE $region_id AND $recurrence";
// three
elseif ( $subname_id && $region_id && $recurrence )
$filter = " WHERE $subname_id AND $region_id AND $recurrence";
return $wpdb->get_results( "SELECT * FROM ". tbl_packages . $filter, ARRAY_A);
}
Check out how DataTables does this:
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
Of course there is.
What do you want sql query to return? (single record, multi-record (array like), all data)
Which cells you want to select?
What is the table name you want to do your query on?
Where are the DB Table cell names & values to do query?
How do you order returned results?
How do you limit (paginate) results?
These are the first questions you have to ask yourself when you try to create universal query functions / methods.
Here is a simple example;
function getData ($tableName= "members", $type = "array", $select = "*", $data = NULL, $order = array("id"=>"DESC"), $pagination = array("100"=>NULL)) { }
Now code above has some features;
$tableName
Obvious (:
$type
Array = Helps you to do query with an array and returns results as an array. $data must be an array.
id = Helps you to do a query with specific ID. $data must be integer.
all = Returns all data. You just need to use $type = all and $select = "*" (or any cell you want to select)
single = When you don't know ID but you need single result. $data must be an array.
$select
If you have big database and if you use all the time * to select all cells which you don't even use, this will slow your pages down. If you want to select only the cells you need, you can use this.
$data
This can be array or integer depending on $type.
You can use it this way;
array("username" => "admin");
Here you can use some extras with regex;
array("!username" => "LIKE!admin");
so when you are looping $data to put it in your query, if you see in the beginning of array key !, this might mean, don't use AND, use OR.
If you see in the beginning of array value LIKE! use it this way;
WHERE username LIKE 'admin'
$order
This is also obvious.
$pagination
array(100 => 0) Array key is limit, array value is offset.
Believe me you want to do something like this in order to make your life easy.
Of course I will suggest you to use PHP 5.3's feature static and make a databaseQuery class. This way you don't need to type $tableName in the first place and easier to work with OOP.
Simply your imagination is limit (:
I hope this helps.
After the examples above I needed something a little more specific to the queries I wanted to perform.
http://professionaldilettante.com/how-to-pass-parameters-as-query-string-to-your-php-functions/2010.11.22 runs though parsing arguments as a string, and as such I came up with this
private function parse_args($args) {
// error check
if( !is_string($args) )
throw new Exception("\n\nfunction parse_args() expects a string, ". gettype($args). " passed\n\n");
if( strpos($args,"&") ):
// if str contains &, assume multiple params
$parts = explode("&",$args);
for( $i=0, $len=count($parts); $i<$len; $i++ ):
$tmp = explode("=",$parts[$i]);
$parsed[$tmp[0]] = $tmp[1];
endfor;
else:
$tmp = explode("=",$args);
$parsed[$tmp[0]] = $tmp[1];
endif;
return $parsed;
}
public static function sub_packages($args) {
global $wpdb, $tbl_packages;
$args = Packages::parse_args($args);
// build query.
$sql = "SELECT * FROM $tbl_packages";
if ( count($args) > 0 ) {
$i = 0;
foreach ( $args as $arg => $value) {
if ( $i == 0 ) $sql .= " WHERE";
elseif ( $i != $count ) $sql .= " AND";
$sql .= " `$arg` = $value";
$i++;
}
}
return $wpdb->get_results( $sql, ARRAY_A);
}