I have a problem where some variables are probably (I can't know for sure) not inserted into the final statement. Here is my example:
Works:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING('.$field.') LIKE "%'.$searchterm.'%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
//$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
//$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug Output:
debug01
Does not work:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING($field) LIKE "%$searchterm%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug output:
debug02
Basically the second example returns no result, while the first one works just fine.
Any idea why?
You are not using N1QL parameters correctly. You must decide if you are evaluating your parameters in PHP or in N1QL.
The field name cannot be a N1QL parameter, so you evaluate it in PHP:
TOSTRING('.$field.') LIKE ...
The search term should be a N1QL parameter, so you add wildcards in PHP and then pass it to N1QL as a parameter:
$searchterm = '%'.$searchterm.'%'
TOSTRING('.$field.') LIKE $searchterm ...
Related
Apologize for the repeated question. Return multiple values from database with function. I tried executing code, the function returns one value, where I want all the values of id and name.
Database: id and name has 9 rows. Is there anything I was missing in my code.
function readdata() {
$sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
foreach ($sth as $s) {
$object = new stdClass();
$object->id = $s->id;
$object->name = $s->name;
return $object;
}
}
$rd = readdata();
echo $rd->id;
echo $rd->name;
May be something like this:
function readdata() {
$sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
$out = [];
foreach ($sth as $s) {
$object = new stdClass();
$object->id = $s->id;
$object->name = $s->name;
$out[] = $object;
}
return $out;
}
$rd = readdata();
//and here
foreach($rd as $obj){
echo $obj->id;
echo $obj->name;
}
This is more a suggestion than an answer. Why re-inventing the wheel? PDO already is capable of returning classes and also fetching all results into an array.
function readdata(PDO $db): array
{
$sth = $db->prepare('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
$sth->execute();
return $sth->fetchAll(PDO::FETCH_CLASS);
}
$objects = readdata($db);
$objects is now an array. Each element contains a stdClass object with each column name as property.
foreach($objects as $object) {
echo $object->id, PHP_EOL;
echo $object->name, PHP_EOL;
}
Your foreach loop intends to run through all values of the array $sth, but returns only with the FIRST one.
You can just return $sth to get the whole array, or build a new array and append to it:
$ret = array();
foreach ($sth as $s) {
...
$ret[] = $object;
}
and then
return $ret;
I have the following function which fetches some data from a MySQL table:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
var_dump($row);
};
echo $data
}
How can I push all the returned data into an array, where each member is indexed by a number?
Do I need to use echo or return at the end? They seem to have the same effect.
EDIT: Is this the correct way of returning results of the query? I am passing it to the front-end.
$questionData = $controller->readQuestion($quizType, $questionId);
return $questionData;
In general your function must looks like:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
return $query;
}
But, you have to look what is inside $query variable. If it is array - just return this array, if not - maybe it is some iterator, hence you have to check it and try to find method like toArray or something like that... Otherwise, you have to do something like:
$data = [];
foreach ($query as $row) {
$data[] = $row;
};
return $data;
Now you can use this function like:
var_dump(readQuestion($quizType, $questionId));
Take a look up here on how to secure your data.
Anyway, as I said in the comment you cannot use echo on an Array. And you can't do anything with the output of var_dump.
Change var_dump($row); for $data[] = $row;
and change echo $data; for return $data;
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
$data=$row;
};
return $result;
}
I want to pass multiple id in where condition how to do it?
A query fetches org_id from database.
now I want to pass that in my where condition, so how to do it?
I tried foreach loop:
Below is my code:
$devices = $this->activation_m->get_activated_devices();
$org_id = array(); // create org_id array
foreach ($devices as $row)
{
$org_id[]= $row['org_id']; // assign ids into array
//$companys =$this->data['devices'] = $this->activation_m->get_company($org_id); // don't call again and again
}
//Now $org_id is array
$companys =$this->data['devices'] = $this->activation_m->get_company($org_id);
echo $this->db->last_query();
Model Code
public function get_activated_devices()
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.site_key = activation.site_key');
$this->db->from('activation');
$query =$this->db->get();
$result = $query->result_array();
return $result;
}
public function get_company($org_id)
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
$this->db->where('company.id IN',(implode(',',$org_id))); // see the change here
$this->db->from('company');
$query =$this->db->get();
$result = $query->result_array();
return $result;
}
now currently my query passes only one org_id , I want to pass all the org_id I get from my first query.
You can use where_in from active-records codeigniter
as
$devices = $this->activation_m->get_activated_devices();
$org_id = array();
foreach ($devices as $row)
{
$org_id[] = $row['org_id'];
}
$companys =$this->data['devices'] = $this->activation_m->get_company($org_id);
if( $companys->num_rows() > 0 )
{
echo "<pre>";
print_r( $companys->result());
echo "</pre>";
}
And for Model
public function get_company($org_ids = array())
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
$this->db->where_in('company.id', $org_ids ); //this is condition
$this->db->from('company');
return $this->db->get();
}
You can use codeigniter's $this->db->or_where() for the purpose. Just traverse the array of organization id's and apply or_where conditions.
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
foreach($org_id as $org)
{ // where $org is the instance of one object of active record
$this->db->or_where('company.id',$org);
}
$this->db->from('company');
$query =$this->db->get();
$result = $query->result_array();
return $result;
Another way to do this is to make a custom query by traversing the array like this and appending where clauses in string.
I am trying to integrate my regular php build script into wordpress. I am stuck in a place where the function works perfectly before, but not in wordpress environment.
In the code below, I am getting blank array in my ajax request whereas I do have results inside myFunc (I have tested by putting wp_send_json inside).
Do I need to change anything to work with PHP globals in wordpress?
$final = array();
function myFunc(){
global $wpdb;
global $final;
$sql = 'SELECT .......';
$result = $wpdb->get_results($sql);
if($wpdb->num_rows > 0){
foreach ( $result as $row ) {
$final[] = $row->pdate;
}
return true;
}
return false;
}
myFunc();
wp_send_json($final);
You can use following statements to get updated value from function.
$arr = array();
function myFunc($new_arr){
global $wpdb;
$sql = 'SELECT .......';
$result = $wpdb->get_results($sql);
if($wpdb->num_rows > 0){
foreach ( $result as $row ) {
$new_arr[] = $row->pdate;
}
}
//It will return updated array if result having rows.Otherwise return empty array.
return $new_arr;
}
$final = myFunc($arr);
if(!empty($final))//if block will be execute if myFunc doesn't return empty array.
{
wp_send_json($final);
}
That should work but globals are nasty things to use and will often conflict I'd suggest just returning the array from the function.
e.g.
function myFunc(){
global $wpdb;
$final = array();
$sql = 'SELECT .......';
$result = $wpdb->get_results($sql);
if($wpdb->num_rows > 0){
foreach ( $result as $row ) {
$final[] = $row->pdate;
}
return $final;
}
return false;
}
$myFuncReturn = myFunc();
if($myFuncReturn !== false){
wp_send_json($myFuncReturn);
}
My function:
function sql_query($s, $x) {
$query = mysql_query($s);
global $mysql;
while($mysql = mysql_fetch_array($query)) {
return;
}
}
Now it's work only with $mysql variable:
echo $mysql['username'];
How to make it works only with:
sql_query("select * from users where id = '1' limit 1", "varname");
$varname['username'];
I want to set a SQL Query and Variable name in function, like:
sql_query("sqlquery", "variable");
echo $variable['id'];
Thanks for reply!
function sql_query($s, &$x) {
global $mysql;
$query = mysql_query($s);
$result = mysql_fetch_array($query);
foreach($result as $key => $value) {
$x[$key] = $value;
}
}
This should assign each variable that is returned by the query to a key in array $x (assuming it is an array). Notice that I am passing $x by reference instead of by value, eliminating the need to return anything.