I'm trying to execute SQL query with table gateway which contain COUNT(*) expression in ZF2. This is function in my model:
public function brKomentariUred(){
$sql = $this->tableGateway->getSql();
$select = $sql->select();
$select->columns(array('brKomentari' => new \Zend\Db\Sql\Expression('count(komentarID)'), 'uredId' => 'ured'));
$select->group('ured');
//echo $sql->getSqlStringForSqlObject($select); die();
return $this->tableGateway->selectWith($select);
}
When the query is printed it is correct
SELECT count(komentarID) AS `brKomentari`, `komentar`.`ured` AS `uredId` FROM `komentar` GROUP BY `ured`
In the controller I'm trying to call the query with this code
foreach($this->getKomentarTable()->brKomentariUred() as $r){
$arr = $this->object_to_array($r);
print_r($arr);
}
It doesn't return number of elements and devicesID as it is written in SELECT, but return as SELECT * FROM komentar, but with no values. Is this right code or I'm making some error in my code? Other queries are OK.
Thanks in advance for your help.
In your place I would do the following steps:
replace the expression object with new \Zend\Db\Sql\Expression('COUNT(komentarID)')
I wouldn't use an alias in group by operator, it may not work. So,
replace this $select->group('ured') with
$select->group('komentar.ured')
Also, the result processing should be simplified:
$resultSet = $this->getKomentarTable()->brKomentariUred();
print_r($resultSet->toArray());
Related
I am working on codeigniter project, I need to migrate whole database mysql to sql server, for that i am getting issue in select query, I can see in sql server round brackets are not supported around the table name, here is my codeigniter query
$this->db->_protect_identifiers=false;
$this->db->select('*')->from('tb_card',false);
$this->db->where('company_id',$this->company_id,FALSE)->get()->row_array();
This select query generates below query
SELECT * FROM (tb_card) WHERE company_id = 27
You can see there is round brackets around the table name, i want to remove this, can anyone please help me to resolve this issue ?
Finally got the solution
(/system/database/drivers/odbc/odbc_driver.php
In this path need to change the function like this way
function _from_tables($tables)
{
/*if ( ! is_array($tables))
{
$tables = array($tables);
}
return '('.implode(', ', $tables).')';*/
if ( ! is_array($tables))
{
return strstr($tables, ',') ? '('.$tables.')' : $tables;
}
else
{
return count($tables) > 1 ? '('.implode(', ', $tables).')' : end($tables);
}
}
Can you able use simple $this->db->query($sql) method, instead of Active Record.
$result = $this->db->query('SELECT * FROM tb_card WHERE company_id = 27');
printr($this->db->last_query());
printr($result->result());
you can use $this->db->get(); if you want select * (all)
for example, is something like....
function getcompany($company_id)
{
$this->db->where('company_id',$company_id);
$query = $this->db->get('tb_card');
return $query->result();
}
those function will return like so
SELECT * FROM 'tb_card' WHERE 'company_id' = $company_id
hope its answer your question.
please use this arcsecond symbol in table name tb_card
$this->db->_protect_identifiers=false; $this->db->select('*')->from('`tb_card`',false); $this->db->where('company_id',$this->company_id,FALSE)->get()->row_array();
I'm using SQL in Yii framework.
I need to show the person's latest active week (it's number and date).So I wrote following code:
public function latestWeek()
{
$datalogin=//the login is working fine
$sql ="SELECT w.number,MAX(w.start_date)
FROM tbl_person_week t, tbl_week w
WHERE t.person_id=$this->id AND t.week_id=w.id";
$query = mysqli_query($datalogin, $sql);
return $query;
}
Now , I checked this query on the server and it works fine (almost) but first thing: I need to convert it into string , because yii's CgridView can't read it , and I couldn't find a working solution for this.
Second: on the server , it gave me the max date indeed , but not it's correct number , but the first number available. How can I fix this as well?
Queries like that should never be used in objective framework. If yu want to execute your own query, you should do it this way:
$sql = "your sql code";
$array = Yii::app()->db->createCommand($sql)->queryAll();
As result you will get multidimensional array with selected columns and rows
If you want to use it in grid view, you should do it this way:
$count = Yii::app()->db->createCommand($sql)->queryScalar();
$dataProvider = new CSqlDataProvider($sql, array('totalItemCount'=>$count));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'grid-id',
'dataProvider'=> $dataProvider,
));
You can also use connection other than Yii::app()->db. Check CDbConnection class in docs.
edit: if you wanna use queries like mysql_fetch_assoc, check out also queryRow() method instead of queryAll()
Use Mysql_fetch _array
public function latestWeek()
{
$datalogin=//the login is working fine
$sql ="SELECT w.number,MAX(w.start_date)
FROM tbl_person_week t, tbl_week w
WHERE t.person_id=$this->id AND t.week_id=w.id";
$query = mysqli_query($datalogin, $sql);
while($row = mysqli_fetch_array($query)){
echo $row;
}
}
Assuming from your qu. that you want the week number and start date as one string, you have to concatenate the two columns in the sql.
You also need to specify that the week number is from the row with the maximum start date, which isn't as simple as you might first think.
I don't like injecting the person_id straight into SQL, it isn't awful in this case but is a bad habit to get into security-wise. There are binding methods available in the framework and I agree with Arek, that you should lean on the yii framework as much as possible.
To get the scalar string value, if you are insisting on using your own SQL.. I suggest the following:
$sql='
SELECT CONCAT('Week ',tw.number,' starting ',tw.start_date)
FROM tbl_week tw
JOIN (
SELECT MAX(twi.start_date) max_start_date
FROM tbl_week twi
JOIN tbl_person_week tpwi
ON tpwi.week_id = twi.id
AND tpwi.person_id = :person_id
) i
ON tw.start_date = i.max_start_date;
';
$command=Yii::app()->db->createCommand($sql);
$command->bindParam(":person_id", $this->id);
return $command->queryScalar();
I am trying to count rows of bookdetails table where display_id is as argument. Say i passed $id='3'. But i am not getting the output.
I think the code which i am trying is wrong. Please help me to write this query correctly
//--- Counting the rows of bookdetails of table where display_id is as argument-------------------------------------------------------------
public function record_count_for_secondtopBooks($id) {
$this->load->database();
return $this->db->count_all("bookdetails",array('display_id'=>$id));
}
count_all returns the number of rows in a particular
echo $this->db->count_all('my_table');
Try this
$this->db->where('display_id', $id);
$this->db->from('bookdetails"');
$this->db->count_all_results();
count_all accepts only one argument and that is table name. So you will get count of all records in that table. as written in manual:
Permits you to determine the number of rows in a particular table.
Submit the table name in the first parameter. Example:
$this->db->where('display_id',$id);
$result = $this->db->count_all("bookdetails");
or Chain em'
$result = $this->db->where('display_id',$id)->count_all("bookdetails");
check:
echo'<pre>';
print_r($result);
echo'</pre>';
Just try this,
$this->db->where('display_id', $id);
$query = $this->db->count_all('bookdetails');
return $query;
please try below code
public function record_count_for_secondtopBooks($id) {
$this->db->where('display_id',$id);
$q = $this->db->get('bookdetails');
return $q->num_rows();
}
try this
public function record_count_with_where($table_name,$column_name,$type)
{
$this->db->select($column_name);
$this->db->where($column_name,$type);
$q=$this->db->get($table_name);
$count=$q->result();
return count($count);
}
I have the following function that does not work and I'm having the hardest time trying to figure it out. I'm 12 and just learning, so forgive me:
function get_answer() {
$answer = $this->db->query("SELECT COUNT(questions) FROM possible_quest WHERE questions='something'");
return $answer;
}
When I run the following SQL query in phpmyadmin, it returns the expected result
SELECT COUNT(questions) FROM possible_quest WHERE questions='something'
How do I get this working in CodeIgniter using my function above?
The PHP error I get is
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Could be:
function get_answer()
{
$query = $this->db->query("SELECT COUNT(questions) AS count FROM possible_quest WHERE questions='something'");
$count = $query->row(); // returns an object of the first row
return $count->count;
// OR
$count = $query->row_array(); // returns an asociative array of the result
return $count['count'];
}
Another thing: if you want to pass 'something' as a variable, you can use parametrized query, like
$sql = "SELECT COUNT(questions) AS count FROM possible_quest WHERE questions = ?";
$query = $this->db->query($sql, array($something));
which has the benefit of escaping automatically your variable, so you don't worry about sql injections.
You need to setup to the count.
Heres what you need to do is
$answer = $this->db->query("SELECT COUNT(questions) as count FROM possible_quest WHERE questions='something'")->first_row()->count;
//$answer is now setup to be count
One line. Thats the beauty of CI
You're getting that error because
return $answer;
should be
return $answer->result();
The error you are getting is related to the fact that $this->db->query returns a result object, so you cannot use $answer directly as a string.
I suggest that you use print_r($answer) to see what could be going wrong with your conversion of objects to strings, if you have such a function in your model.
CodeIgniter has functions for building queries and returning the count:
function get_answer() {
$this->db->from("possible_quest");
$this->db->where("questions", "something");
return $this->db->count_all_results();
}
NOTE: The name of the function 'get_answer' doesn't match what you're actually doing. It looks like you're getting a count of questions, not an answer, so you should name it to something that makes more sense, like 'get_question_count'.
I recommend you to use an Active Record with method chaining when possible:
public function getAnswer() {
return
$this->db->
select('id')->
where('questions', 'something')->
get('possible_quest')->row()->count
;
}
or
public function getAnswer() {
return
$this->db->
select('id')->
from('possible_quest')->
where('questions', 'something')->
get()->row()->count
;
}
It's secure, easy to use, easy to understand and read. Don't listen to people saying that a single-line code is something good because a good code should be readable.
I am trying to write a PHP function which gets the sum of values in 1 column of a table. MY SQL statement works just fine. However, when I write my function and attempt to echo the variable into my HTML code, it returns '0'.
Here is my function:
function get_asset_value($org_ID) {
global $db;
$query = "SELECT SUM(asset_value) FROM assets
WHERE org_ID = '$org_ID'";
$asset_sum = $db->query($query);
$asset_sum = $asset_sum->fetch();
return $asset_sum;
In my HTML, I have the following:
<?php echo $asset_sum; ?>
I'm not sure if this has to do with the "fetch" portion of my function. I really don't know what fetch does but I tried copying/modifying this piece of code from a working function (which doesn't return the sum, but it is a select statement).
Thank you!
In addition to
SELECT SUM(asset_value) AS the_sum FROM assets WHERE ord_ID = '$ord_ID';
...
return $asset_sum['the_sum']
by Brad,
you better do
$safer = mysql_real_escape_string($org_ID);
then do,
SELECT SUM(asset_value) AS the_sum FROM assets WHERE ord_ID = '$safer';
...
return $asset_sum['the_sum']
SELECT SUM(asset_value) AS the_sum FROM assets WHERE ord_ID = '$ord_ID';
...
return $asset_sum['the_sum'];
The issue is, you are returning an entire record, rather than just the field you want.
Also, judging by the way you are inserting that ID in your query, I suspect you are open to SQL injection. You should really learn to do prepared queries with PDO.