I have a codeigniter model function which queries a database and sends the result back to the controller, encoded as json.
the entire function is shown below:
function get_skufamily_cube($q){
$sql=("select min([Pieces]) as ProductCode from
(SELECT
[ProductCode]
,[Description]
,[Length]
,[Pieces]
,[Thickness]
,[Width]
,([width]*1000) w2
,([thickness]*1000) t2
,REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','') AS l2
,concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')) AS pc
,REPLACE([ProductCode],concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'') as grade
,CONCAT(([width]*1000),([thickness]*1000),REPLACE([ProductCode],concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options
FROM [hammerhead].[dbo].[ProductList]) as p
where Options like '%$q%' ");
$query=$this->db->query($sql);
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['ProductCode']));
echo $row['ProductCode']; // to see database result and troubleshoot
}
$this->output->set_content_type('application/json')->set_output(json_encode($row_set));
}
}
$q is being passed successfully to the query and the output of the query in echo $row['ProductCode']; is consistent with the result I require. in this case it is 108. the database query returns a single result in a single field.
For some reason, this is no tbeing passed back tot he controller correctly.
Controller is:
$this->load->model('Sales_model');
if (isset($_POST['data'])){
$q = strtolower($_POST['data']);
$data = $this->Sales_model->get_skufamily_cube($q);
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
}
In my developer tools, I can see the server response
108NULL. 108 being my echo and NULL being the json response. if I remove the echo this is simply NULL.
Laslty, I need to populate the input in my table row with the value. my view jquery syntax for this is:
$.post('get_skufamily_cubes', {data:selectedObj.value},function(result)
{
$(this).find('input[id^="cubesperbundle"]').val(result);
});
Currently nothing is populated. the html input name and id is:cubesperbundle but has the row number appended to it hence the 'input[id^="cubesperbundle"]'
Any assistance would be appreciated.
Thanks and Regards,
The mistake i see is that you are not returning anything to controller.
Model
function get_skufamily_cube($q)
{
$Query="select
min(Pieces) as ProductCode
from (SELECT
ProductCode,
Description,
Length,
Pieces,
Thickness,
Width,
(width*1000) w2,
(thickness*1000) t2,
REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','') AS l2,
concat((width*1000),(thickness*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')) AS pc,
REPLACE(ProductCode,concat((width*1000),(thickness*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'') as grade,
CONCAT((width*1000),(thickness*1000),REPLACE(ProductCode,concat((width*1000),(thickness*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options
FROM hammerhead.dbo.ProductList) as p
where Options like '%$q%'";
return $this->db->query($Query)->row();
}
Controller
function getJson(){
$this->load->model('Sales_model');
if (isset($_POST['data'])){
$q = strtolower($_POST['data']);
$viewData = $this->Sales_model->get_skufamily_cube($q);
$data_json = json_encode($viewData);
echo $data_json;
}
}
EDITS:
Change the return instruction in model function.
$result = $this->db->query($Query)->row();
return $result->ProductCode;
Related
i have question i don't know better approach to do it in mysql. I have a table in mysql with list of regex's each regex represent a company order number
i want to be able to compare a number to that list to get which company this number belongs to. the lazy way is to list all the regex in php and then using loop to get the company , but i want to do this using the power of mysql .
Like #Mech mention this might be vague.
i will try to explain it more :
I have two tables table with actual regex pattern in plain text in a column like "^[8]{1}[0-9]{10}$"
and this pattern belong to a company , there is more than 500 regex patterns .
Thank you.
Here you go #BM2ilabs. A function as requested :)
carrierID(88888141234);
function carrierID($ordernum) {
// create a connection to your db here
// fetch data needed for loop
$sql = "SELECT regex, carrier_id FROM `company_tbl_from_image`";
// fetch results
$results = $conn->query($sql);
// loop through $results
foreach ($results as $result) {
// individually check against each regex in the table
$regex = $result[regex];
// find first instance of $regex, where the $ordernum is unique, there should only be one match
if (preg_match('/'.$regex.'/', $ordernum)) {
$carrier_id = $result[carrier_id];
break; // remove break to show other matches
}
}
// check if $carrier_id is empty
if ($carrier_id <> "") {
echo $carrier_id;
} else {
echo "No carrier ID found.";
}
}
MySQL only option. Just search this:
SELECT carrier_id FROM `company_tbl_from_image` WHERE 'order number' REGEXP regex
Can someone help me convert this query so that my result set is in different format?
$sessions = new Session();
$results = $sessions->where('session_status', $status)->where('application_period_id', (int) ApplicationPeriod::all()->last()->id)->get()->pluck('speaker_id');
$speakers = Speaker::whereIn('id', $results)
->with('session.audiancesession.audiances')
->with('session.subjectsession.subjects')
->with(['session' =>
function ($query) use($status) {
$query->where('session_status', '=', $status);
}])->orderBy('last_name')->get();
This is requested via Ajax(axios)... Now this is how result is formatted:
Obj->data(array of objects)->[0]->name
->address
->session(array of objects)
->[0]->time
->fee
My issue is that my session parameter is array and there can only ever be (1) so I don't need to to be an array and I would like to have object (json) instead.
Thank you!
You might have more success if you change your client-side code to work with an array of sessions each session having its speaker, that means your original query would be like
$sessions = Sessions::with([
'speaker', 'audiancesession.audiances', 'subjectsession.subjects'
])->where('application_period_id', (int) ApplicationPeriod::orderBy('id','DESC')->first())->get();
Note the order by -> first in the ApplicationPeriod makes it so you don't have to get all application periods from the database to memory.
Then your client side should handle an array of sessions.
You can transform the above slightly using to get a similar result to what you need:
$speakers = $sessions->map(function ($session) {
$speaker = collect($session->speaker->toArray());
$speaker->put('session', collect($session->toArray())->except('speaker'));
return $speaker;
})->orderBy('last_name','DESC');
Though I wouldn't guarantee the result here as I've not tested it on your (complex looking) data.
in my app I have a special class to work with DB.
And I have methods that SELECT data from BD and return the result as an array. But when I try to cover this methods with PHPUnit, I always have NULL in return.
here is my piece of code
public function getData($id) {
$selectQuery = $dataBase->query('SELECT * FROM table WHERE id = :id');
$selectQery->bindInt(':id', $id);
$selectQuery->execute();
$result = $selectQuery->toArray();
return $result;
}
before getting result I can see with debuger that SQL query is ok, ID is binded and the method has to return an array. and it returns if to run the method in my app. But the test gives NULL result.
How can I cover this method with tests and make sure that it returns a correct array of data?
I have a query:
"SELECT Time, Date, Name, Email FROM table"
It converts the results to json to be passed via ajax, the problem is I want a new column in the sql, so I add it to the query:
"SELECT Time, Date, Name, Email, Address FROM table"
now the json encode does not work, I have tried changing data types and using UTF-8 however this did not work, none of the others are using UTF-8 but still work anyway, Thanks.
This is my code to encode to json which does work until I add the new collumn from sql
if ($result = $mysqli->query($query)) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
Solved
The problem was the last column i was trying to get was called "Show" for some reason sql does not like this, i renamed this column to "lol" (temporary) and it works!
I am trying to set up a filter on my website. Here, I am trying to pass (2) variables (neighborhood and business category). My problem is when only (1) of them is true and the other is false or one variable does not exist. I am trying to pull this data from my URL
mydomain.com/controller/function/neighbrohood/biz-category
which translates
mydomain.com/ny/find/$neighborhood/$biz_filter
When I have both variables then there is no problem.
How do I resolve the page with only 1 of the 2 variables there?
Here is my model:
public function search($neighborhood = null, $biz_filter = null) {
$neighborhood = $this->uri->segment(3);
$biz_filter = $this->uri->segment(4);
// SELECT
$this->db->select('*');
// MAIN TABLE TO GRAB DATA
$this->db->from('biz');
// TABLES TO JOIN
$this->db->join('city', 'city.city_id = biz.biz_cityID');
$this->db->join('zip', 'zip.zip_id = biz.biz_zipID', 'zip.zip_cityID = city.city_id');
$this->db->join('state', 'state.state_id = city.city_stateID');
$this->db->join('neighborhood', 'biz.biz_neighborhoodID = neighborhood.neighborhood_id');
$this->db->join('biz_filter', 'biz_filter.bizfilter_bizID = biz.biz_id');
$this->db->join('biz_category', 'biz_filter.bizfilter_bizcategoryID = biz_category.bizcategory_id');
// RETURN VARIABLES
$this->db->where('neighborhood.neighborhood_slug', $neighborhood);
$this->db->where('biz_category.bizcategory_slug', $biz_filter);
// ORDER OF THE RESULTS
$this->db->order_by('biz_name asc');
// RUN QUERY
$query = $this->db->get();
// IF MORE THAN 0 ROWS ELSE DISPLAY 404 ERROR PAGE
if($query->num_rows() > 0){
return $query;
} else {
show_404('page');
}
}
Example. Say I am looking for a Restaurant in Little Italy:
URL = mydomain.com/ny/find/little-italy/restuarants
This part, I can resolve the query correctly and display the data. The issue is when there is no neighborhood or no category, I cannot figure out how to resolve the data.
I am new to codeigniter and a self-taught programmer, trying to figure this out as I go. Any help would be much appreciated.
Thank you in advance.
first of all it is optional to get the variables from the uri
$neighborhood = $this->uri->segment(3);
$biz_filter = $this->uri->segment(4);
You already have that from your function parameter.
You can check the condition where your $neighborhood or $biz_filter is available or not then you can use condition in your query.
Something like this
if($neighborhood) { // query for neighborhood } elseif($biz_filter) {}
Thanks
First of all you should get the variable values from your controller not your model, you should then pass such values to your controller from your model, its bad coding practice to allow your view interact with the model.
Also, if you want a value of "-" set for the variable. You should set "-" as the return value right from the parameters being passed to the controller.
What you should do is go to your controller and give it the two parameters, set default values for both and also go to your model and make it receive two parameters also, pass the parameters to the model when calling from the controller. Then get back if there are any more errors.