Error 500 Wordpress database - php

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.

Related

Mysql returned Array with Keys and Tabelle-Names - delete Keys

I have a MySQL table, where I run a query with left join:
$db = $db->first("SELECT * FROM devices LEFT JOIN customer ON devices.customerid = customer.customerid WHERE devices.hash = '".$hash."' OR devices.deviceid = '".$hash."'");
With this function:
//Select Datenbankanfrage, erste Zeile
function first($query, $restype=0) {
$this->querystring = $query;
if ( $restype==1 ) $restype=MYSQLI_ASSOC;
else $restype=MYSQLI_BOTH;
$result = $this->query($query); //Query
if ( !$result ) return false;
$row = $result->fetch_array($restype);
$result->free();
return $row;
}
But I recieve an array with keys as response:
1 => Maxii
Name => Maxii
2 => Streetfromthe
Street => Streetfromthe
How can I disable the keys (1,2) or how can I delete this in the array?
Here is a Nopaste from the full array returned:
https://nopaste.xyz/?23ccf318bbfc93fb#Oes85/9Z8+Kookk2nTLmbtObjaL8mD2aitPPrHV3v9w=
The problem comes from $restype, your second argument. It is zero by default which would use MYSQLI_BOTH, which returns fields by both index and names. You certainly want an associative array (MYSQLI_ASSOC), passing $restype to 1.
The lines that are responsible for changing the restype are:
if ( $restype==1 ) $restype=MYSQLI_ASSOC;
else $restype=MYSQLI_BOTH;
You need to replace with $result->fetch_array with $result->fetch_assoc
EDIT: In your case, leave it at fetch_array and use the function you have.
Invoke it with first($sql, 1);

Dynamic Table Name in Propel Query

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;
}
}

Return value in foreach loop in CodeIgniter

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.

next_record called with no query pending

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.

codeigniter pass array to query

I'm trying to pass an array to a model which has a query. I'm not sure how to correctly pass the array or if i have to manipulate the array somehow.
I have this array:
Array
(
[0] => 1
[1] => 2
)
I have a controller with this line:
$ratings = $this->login_model->get_ratings($mechanicIds); // get the mechanic ratings
I have this model:
function get_ratings($mechanicId)
{
$sql = "select m.mechanic_id,
m.mechanic_name,
m.city,
m.state,
count(mr.rating_id) as num_ratings,
round(avg(mr.rating_id),2) avg_rating
from mechanic m, mechanic_rating mr, rating r
where m.mechanic_id in (?)
and m.mechanic_id = mr.mechanic_id
and mr.rating_id = r.rating_id";
$query = $this->db->query($sql, $mechanicId);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else
{
return false;
}
}
It actually returns results, but the problem is it only returns the results 1 row when it should be returning 2 since there are 2 results in my array. Anyone know what i'm doing wrong?
I found this question which helped.
Below is the code I used.
Controller that contains this:
$mIds_size = count($mIds);
$i = 1;
foreach($mIds as $row)
{
if($i == $mIds_size)
{
$mechanicIds .= $row;
}
else
{
$mechanicIds .= $row.', ';
}
$i++;
}
$ratings = $this->login_model->get_ratings($mechanicIds); // get the mechanic ratings
Model which contains this:
function get_ratings($mechanicId)
{
$this->db->escape($mechanicId);
$sql = "select m.mechanic_id,
m.mechanic_name,
m.city,
m.state,
count(mr.rating_id) as num_ratings,
round(avg(mr.rating_id),2) avg_rating
from mechanic m, mechanic_rating mr, rating r
where m.mechanic_id in ($mechanicId)
and m.mechanic_id = mr.mechanic_id
and mr.rating_id = r.rating_id
group by mechanic_id";
$query = $this->db->query($sql, $mechanicId);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else
{
return false;
}
}
Change this line:
$query = $this->db->query($sql, $mechanicId);
to this:
$query = $this->db->query($sql, array(implode(', ',$mechanicId)));
as per the manual
To pass an array into a raw query (not built with helper methods) for an IN condition, use the ? placeholder without wrapping in parentheses.
When binding the array to the placeholder, you must declare your array inside of an array. In other words, the "parameters" (2nd) argument of query() method expects an array which relates to each ? in the SQL string. Because the first ? is bound to an array, the $mechanicIds array must be declared as the first element of the "parameters" argument. I have tested this advice to work successfully in a CodeIgniter3 instance that I have access to.
$sql = "SELECT m.mechanic_id,
m.mechanic_name,
m.city,
m.state,
COUNT(mr.rating_id) AS num_ratings,
ROUND(AVG(mr.rating_id), 2) AS avg_rating
FROM mechanic AS m,
mechanic_rating AS mr,
rating AS r
WHERE m.mechanic_id IN ? /* <--- here */
AND m.mechanic_id = mr.mechanic_id
AND mr.rating_id = r.rating_id";
$query = $this->db->query($sql, [$mechanicIds]);
The DB_driver.php core file contains this portion of code in compile_binds() which escapes each value in the array and wraps the comma-joined string in parentheses before returning the sql string.
...
do
{
$c--;
$escaped_value = $this->escape($binds[$c]);
if (is_array($escaped_value))
{
$escaped_value = '('.implode(',', $escaped_value).')';
}
$sql = substr_replace($sql, $escaped_value, $matches[0][$c][1], $ml);
}
while ($c !== 0);
...

Categories