public function test_passing_string() {
$this - > load - > model(array('registration/Registration_model', 'Jawaban_lab_model'));
$registration = new Registration_model();
$jawaban_lab = new Jawaban_lab_model();
$id = "kuda4";
$jawaban_lab - > load($id); //load jawaban_lab from id
$manualy_written_registration_number = "REG/FM/130102-0001";
echo "registration number from jawaban_lab->registration_number : ".$jawaban_lab - > registration_number
.
"<br> registration number from manualy_written_registration_number : ".$manualy_written_registration_number;
//$registration->load($jawaban_lab->registration_number);
$registration - > load($manualy_written_registration_number);
echo "<br> patient id : ".json_encode($registration - > PatientID);
}
Before go to the question, I will explain my code.
On test_passing_string() function, I call 2 model, and create object for each model there are $registration and $jawaban_lab.
To load data from model I create a load() function. load() has two parameters: column_value and column_name. The default value for column_name is that model's Primary Key.
BUT
The problem comes from
$registration->load($jawaban_lab->registration_number);
I can't retrieve any $registration object data, then I test it by passing the value manually by write this:
$manualy_written_registration_number = "REG/FM/130102-0001";
$registration - > load($manualy_written_registration_number);
And the result appear, doesn't that mean my load() function is fine?
Then I check value inside $jawaban_lab->registration_number by echoing it, surprisingly it display same value as my $manualy_written_registration_number variable.
This is screenshoot in my browser when I run test_passing_string() function:
Using $manualy_written_registration_number value
Using $jawaban_lab->registration_number value
Why can't I use the value from
$jawaban_lab->registration_number even though it has the same value as
my manually writen registraiton number?
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
// using custom column.
$query = $this->dbs->get_where($this::DB_TABLE, array(
$column_name => $column_value
));
} else {
// using column primary key .
$query = $this->dbs->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $column_value
));
}
if ($query->row()) {
$this->populate($query->row());
}
}
I use multiple database using CodeIgniter 3, registration_model from SQL server and jawaban_lab from MySQL, jawaban lab have column registration_number to store registration_model primary key
var_dump
First of all thanks to rlanvin and Nirajan N Raju
from rlanvin's comment, i find out the problem is come from codeigniter's query helper, because when i enable codeigniter profiling sql server query return "SELECT CASE WHEN (##OPTIONS | 256) = ##OPTIONS THEN 1 ELSE 0 END AS qi"
so i think codeigniter might be cannot generate query so i create the query manually
i change
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
// using custom column.
$query = $this->dbs->get_where($this::DB_TABLE, array(
$column_name => $column_value
));
} else {
// using column primary key .
$query = $this->dbs->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $column_value
));
}
if ($query->row()) {
$this->populate($query->row());
}
}
to this
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
$query = $this->dbs->query("SELECT * FROM " . $this::DB_TABLE . " WHERE " . $column_name . " LIKE '" . trim($column_value) . "'");
} else {
$query = $this->dbs->query("SELECT * FROM " . $this::DB_TABLE . " WHERE " . $this::DB_TABLE_PK . " LIKE '" . trim($column_value) . "'");
}
if ($query->row()) {
$this->populate($query->row());
}
}
Related
I've got a stored procedure which looks like this:
-- GET INVITES
DROP PROCEDURE IF EXISTS pda.get_invite;
DELIMITER //
CREATE PROCEDURE pda.get_invite ( code varchar(100), invitator_id bigint )
BEGIN
SELECT * FROM pda_invites
WHERE (pda_invites.invitator_id = invitator_id || invitator_id IS NULL)
AND (pda_invites.code = code || code IS NULL);
END //
CALL get_invite ( 'cec95191-23db-11e9-86d7-26374278e97f', NULL );
That works in phpmyadmin and deliver the desired result.
Now on php side, I've got some kind of query builder in a procedure class with registered arguments, which looks like this:
public function toSQL ( ) {
// Make sure params are set
if ( $this->ready == false ) {
throw new Exception ( 'Called unready procedure ' . $this->PROCEDURE_NAME . '.' );
return false;
}
// Build query
$sql= 'CALL ' . $this->PROCEDURE_NAME . '( ';
$i = 0;
foreach ( $this->args as $arg ) {
$param = $this->params[ $i ][ $arg['NAME'] ];
// Apply valid null values
if ( $param == null || $param == 'null' ) {
$sql = $sql . 'NULL';
// Apply varchar strings
} else if ( $arg['TYPE'] == 'varchar' ) {
$sql = $sql . '\'' . $param . '\'';
// Apply numeric values
} else {
$sql = $sql . $param;
}
if ( ($i+1) < $this->args_count ) {
$sql = $sql . ', ';
}
$i++;
}
$sql = $sql . ' );';
return $sql;
}
In my DB Service I trigger that by calling:
$sql = $procedure->toSQL();
$result = $con->query($sql);
echo($sql);
echo json_encode($result);
That results in following equivalent query string which is also reflected by the mysql log:
CALL get_invite( 'cec95191-23db-11e9-86d7-26374278e97f', NULL );
But the problem and question is that it produces an empty result:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
Have anyone a clue why it coulds behave this way?
I am new to codeigniter and working on a project where I need to add search filters on a page. The way its been setup under applications/core there is a MY_Model.php file and here it the get_result function it.
function get_result() {
$this->db->from($this->tableName . ' ' . $this->alias);
$this->db->select($this->selectFields, FALSE);
for($j=0;$j<count($this->arrJoins);$j++){
$this->db->join($this->arrJoins[$j][0], $this->arrJoins[$j][1], $this->arrJoins[$j][2]);
}
$this->db->like($this->arrLike);
$this->db->or_like($this->arrOrLike);
if(isset($this->custLikeStr) && count($this->custLikeStr) > 0){
$this->db->where($this->custLikeStr);
}
$this->db->where($this->arrWhere);
$this->db->order_by($this->sortBy, $this->sortOrder);
$query = $this->db->get()->result();
//echo '<br>'.$this->db->last_query();
return $query;
}
There is a get_where function to build all where clauses
function get_where() {
foreach($this->arrWhereInputs as $arrWhereInput) {
if(isset($this->$arrWhereInput) && $this->$arrWhereInput != ''){
$this->arrWhere[$this->fieldAlias[$arrWhereInput].'.'.$arrWhereInput] = trim($this->$arrWhereInput);
}
}
return $this->arrWhere;
}
And in the model file for the application so under application/models here is there is a select function we need to call to get results.
function select(){
/* for search list */
$this->arrLikeInputs = array('stock_title', 'stock_id', 'price_band', );
$this->arrWhereInputs = array();
$this->arrWhere = array();
if ($this->input->post('record_per_page') != '') {
$records_per_page = $this->input->post('record_per_page');
} else {
$records_per_page = ROWS_PER_PAGE;
}
if (!(isset($this->record_per_page) && $this->record_per_page != '')) {
$this->record_per_page = ROWS_PER_PAGE;
}
$this->arrLike = $this->get_like();
$this->arrWhere = $this->get_where();
$this->arrWhere['SC.isDeleted'] = 0;
/* for search list */
if ($this->countQuery == 1) {
$this->db->from($this->tableName . ' ' . $this->alias);
$this->countSelectFields = 'COUNT(SC.stock_id) as cnt';
$result['count'] = $this->get_count();
}
$result['resultarr'] = $this->get_result();
$result['record_per_page'] = $records_per_page;
return $result;
}
Now I want to add where in to my query and I have tried a few ways but it just does not work.
I am getting confused on to where I am going wrong on such a simple thing.
So I have added a get_wherein function.
function get_wherein() {
foreach($this->arrWhereInInputs as $arrWhereInInput) {
if(isset($this->$arrWhereInInput) && $this->$arrWhereInInput != ''){
$this->arrWhereIn[$this->fieldAlias[$arrWhereInInput].'.'.$arrWhereInInput] = trim($this->$arrWhereInInput);
}
}
return $this->arrWhereIn;
}
So I added $this->arrWhereIn['Field'] = $arr which does not work and also tried to to call $this->db->where_in('field',$array) in the select function directly that does not work either. In both the cases it gets ignored and the query is build without the "and where in".
Where am I going wrong and how to build this query?
I have this HTML form which has so many fields that someone can use to query data from MySQL table using multiple conditions. The form has select boxes, text boxes and check boxes, and date inputs.
I have this function which is ineffective
public function search(Request $request)
{
// loop through the defined fields
foreach($this->fields as $field){
// if the field is set and not empty
if(is_array($request->get($field))){
foreach ($request->get($field) as $value) {
$this->conditions[] = "`$field` = '" . $value . "'";
}
} else {
if(isset($_POST[$field]) && $request->get($field) != '') {
$data = $request->get($field);
if($field == 'bf_ref_no'){
$data = is_numeric( substr($request->get($field), 0, 2) ) ? 'BF'.$request->get($field) : $request->get($field) ;
}
$this->conditions[] = "`$field` = '" . $data . "'";
}
}
}
// builds the query
$query = "SELECT invoices.id as inv_id, invoices.created_at as inv_date, invoices.amount_paid, invoices.amount, csv_data_final.* FROM csv_data_final
LEFT JOIN invoices ON invoices.parent_id = csv_data_final.id ";
// if there are conditions defined
if(count($this->conditions) > 0) {
// append the conditions
$query .= "WHERE " . implode (' AND ', $this->conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
$results = DB::select( $query );
$borders = DB::table('borders')->orderBy('id', 'DESC')->get();
return view('track.track-withdata', compact('results', 'borders'));
}
This code doesn't work for dates using BETWEEN keyword.
I'm using the last version of ADOdb PHP (5.18) to make some queries in a SQL Server database.
I select data in this way:
$rS = $localDb->Execute($sql);
if (!$rS) {
echo "Error: " . $localDb->ErrorMsg() . "\n";
}
else {
$tot = $rS->RecordCount();
echo " " . $tot . " record da inserire...\n";
while (!$rS->EOF) {
$id = $rS->fields['id'];
$field1 = $rS->fields['field1'];
$field2 = $rS->fields['field2'];
$rS->MoveNext();
}
}
All works, and I fetch data, but when a field in the database's current row is NULL, the relative element in $rS->fields has the value of the value of the last not-NULL row for the same field.
This is a big problem because I don't have correct data in the current row.
I tried search for this problem but I did not find any solution.
Coud you help me, please?
Look into adodb5/adodb.inc.php and find the GetRowAssoc function. It should be the following defintion:
function GetRowAssoc($upper=ADODB_ASSOC_CASE_UPPER)
{
$record = array();
if (!$this->bind) {
$this->GetAssocKeys($upper);
}
foreach($this->bind as $k => $v) {
if( array_key_exists( $v, $this->fields ) ) {
$record[$k] = $this->fields[$v];
} elseif( array_key_exists( $k, $this->fields ) ) {
$record[$k] = $this->fields[$k];
} else {
# This should not happen... trigger error ?
$record[$k] = null;
}
}
return $record;
}
I want to fetch contents with multiple filters, right now there's only one.
For Example:
SELECT * FROM Table1 WHERE status=true AND category = 'Camera' AND
model = 'Samsung' AND type = 'New'
I want to create an array for it. But as I'm a newbie in this one not getting a lead.
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter = 'AND cat_id=' . $filter;
}
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . $filter;
Any help will be appreciated.
This will get you closer to the solution, though it will not replace the cat_id in the query, which will certainly be wrong - though impossible to do too much more without the array structure:
function getAllRequests($filter)
{
$addfilter="";
if(!empty($filter))
{
foreach($filter as $val)
{
$addfilter. = ' AND cat_id=' . $val .'\'';
}
}
return $addFilter;
}
$myFilters=getAllRequests($filter);
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
On the other hand, if your array is strucutred in a way like this:
array{ category => camera, model => samsung); // etc
you could use the following:
function getAllRequests($filter)
{
$addfilter="";
if(!empty($filter))
{
foreach($filter as $key => $val)
{
$addfilter. = " AND `$key` = '$val'";
}
}
return $addFilter;
}
$myFilters=getAllRequests($filter);
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
Edit: You can loop through all the filters in the following manner:
function getAllRequests()
{
$addfilter="";
if(!empty($_REQUEST))
{
foreach($_REQUEST as $key => $val)
{
$addfilter. = " AND `$key` = '$val'";
}
}
return $addFilter;
}
$myFilters=getAllRequests();
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
You don't need to pass the $_REQUEST (which will work for both GET and POST) as it already a superglobal.
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter = 'AND cat_id=' . $filter;
}
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . $addfilter;
You can use another approach, which is using optional parameters and it will make your WHERE clause dynamic as you want. In this approach you pass all parameters' values directly to the sql query which should look like so:
SELECT *
FROM Table1
WHERE 1 = 1
AND (#status IS NULL OR status = #statusParam)
AND (#category IS NULL OR category = #categoryParam)
AND (#model IS NULL OR model = #modelParam)
AND (#type IS NULL OR type = #typeParam)
Then If any of the parameters #statusParam, #categoryParam, #modelParam or #typeParam passed to the query with NULL values, then the comparison with the column holding that value will be ignored. I used the predicate 1 = 1, in case all the values passed to the query with all NULL values in the case all the WHERE clause will be ignored as it won't presented, since WHERE 1 = 1 always true and it will be like SELECT * FROM Table1.
use this
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter .= 'AND cat_id=' . $filter;
}
return $addfilter;
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . getAllRequests($filter);
When you are sending array make sure it has indexes
$conditions = array('category' => 'Camera', 'model' => 'Samsung' , 'type' => 'New')
Now loop through it. in your else condition
foreach($conditions as $key =>$value){
$addfilter .= 'AND ' . $key . ' = ' . $value;
}