sqli sum of a column codes not working - mysqli

I am trying to sum of a column of database table by the following cods, but it's not working:
$sqli = "SELECT sum(total_salary) AS totSalary FROM allsalary WHERE month_session = '$month_name' and org_session = '$org_name' and desig_session = '$desig_name' ORDER BY ID ASC ";
$stmt = $mysqli->prepare($sqli);
$stmt->execute();
$stmt->store_result();
$totl = $stmt->fetch();
$total_salary = $totl['totSalary'];
echo $total_salary;
But I could fetch the table correctly.
Now I want to sum the column named 'total_salary', I need a suggestion.....

You are missing two essential functions here, bind_param() and bind_result()
$sql = "SELECT sum(total_salary) FROM allsalary WHERE month_session = ?
and org_session = ? and desig_session = ? ORDER BY ID ASC";
$stmt = $mysqli->prepare($sql);
$sttmt->bind_paran("sss",$month_name,$org_name,$desig_name);
$stmt->execute();
$stmt->bind_result($total_salary);
$stmt->fetch();
echo $total_salary;

Related

Column is not updating in postgresql

I tried to update my table like below:
$query = "select *
FROM sites s, companies c, tests t
WHERE t.test_siteid = s.site_id
AND c.company_id = s.site_companyid
AND t.test_typeid = '20' AND s.site_id = '1337'";
$queryrow = $db->query($query);
$results = $queryrow->as_array();
foreach($results as $key=>$val){
$update = "update tests set test_typeid = ? , test_testtype = ? where test_siteid = ?";
$queryrow = $db->query($update,array('10','Meter Calibration Semi Annual',$val->site_id));
}
The above code is working good. But in update query , The column test_typeid is not updated with '10'. Column test_typeid is updating with empty value. Other columns are updating good. I dont know why this column test_typeid is not updating? And the column test_typeid type is integer only. I am using postgreSql
And My table definition is:
What i did wrong with the code. Kindly advice me on this.
Thanks in advance.
First, learn to use proper JOIN syntax. Never use commas in the FROM clause; always use proper explicit JOIN syntax.
You can write the query in one statement:
update tests t
set test_typeid = '10',
test_testtype = 'Meter Calibration Semi Annual'
from sites s join
companies c
on c.company_id = s.site_companyid
where t.test_siteid = s.site_id and
t.test_typeid = 20 and s.site_id = 1337;
I assume the ids are numbers, so there is no need to use single quotes for the comparisons.

Zend 2: How do I execute multiple SQL queries using Zend\Db\Adapter?

Im executing this query:
$query = "
Select * From table1 Where id = 1;
Select * From table2 Where name = 'test';
";
With \Zend\Db\Adapter\Adapter:
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
How can I access the second result?
$rawResult->next() only returns values from first query.
Use two different queries.
/*
* First Query
*/
$query = "
Select * From table1 Where id = 1
";
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
/*
* Second Query
*/
$query = "
Select * From table2 Where name = 'test'
";
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
I don't believe it works the way you had it to where two queries in a row are sent this way.
To avoid code duplication you can wrap the duplicated code into a method.
$rawResult1 = $this->getResults("Select * From table1 Where id = 1");
$rawResult2 = $this->getResults("Select * From table2 Where name = 'test'");
function getResults(string $query)
{
$stmt = $this->dbAdapter->query($query);
return $stmt->execute();
}

how to convert count(*) and group by queries to yii and fetch data from it

I want to convert this query in yii
SELECT count(*) AS cnt, date(dt) FROM tbl_log where status=2 GROUP BY date(dt)
and fetch data from that. I try this command (dt is datetime field):
$criteria = new CDbCriteria();
$criteria->select = 'count(*) as cnt, date(dt)';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
but no data will fetch!
wath can I do to get data?
Probably you see no data because you need assign data to model attributes which doesn't exist.
$criteria = new CDbCriteria();
$criteria->select = 'count(*) AS cnt, date(dt) AS dateVar';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
This means that your model must have attributes cnt and dateVar in order to show your data. If you need custom query then check Hearaman's answer.
Try this below code
$logs = Yii::app()->db->createCommand()
->select('COUNT(*) as cnt')
->from('tbl_log') //Your Table name
->group('date')
->where('status=2') // Write your where condition here
->queryAll(); //Will get the all selected rows from table
Number of visitor are:
echo count($logs);
Apart from using cDbCriteria, to do the same check this link http://www.yiiframework.com/forum/index.php/topic/10662-count-on-a-findall-query/
If you use Yii2 and have a model based on table tbl_log, you can do it in model style like that:
$status = 2;
$result = Model::find()
->select('count(*) as cnt, date(dt)')
->groupBy('date(dt)')
->where('status = :status')
->params([':status' => $status ])
->all();

Parametrized query inside mysqli class

I am using Mertol Kasanan's class for running parametrized queries -
http://liveplanet.googlecode.com/svn-history/r132/trunk/db/DB.php
I am very satisfied with the script except for some issues that I don't seem to put my finger on.
As it states in the brief tutorial in the class's description the method for running the query is:
$result = $db->query('SELECT * FROM `users` WHERE id = ? AND user_type = ? LIMIT ?',$id,$user_type,$limit);
Can anybody figure out how to run a query without defining any parameter as it seems that
$result = $db->query('SELECT * FROM `users` WHERE id = 'y' ");
neither
$result = $db->query('SELECT * FROM `users` WHERE id = 'y' ", '');
do not do the trick as it returns a binding error;
A workaround would be
$result = $db->query('SELECT * FROM `users` WHERE 1 = ? AND id = 'y' ", 1);
Is there a neater way to run my query?
I don't need parameters as the query gets it's values from a safe source inside a class.
Edit:
Let's say I have this:
if($HC == 'C'){
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat != 'D' GROUP BY pic LIMIT ?";
$query = $this->dbs->query($sql,$this->user,$this->user_head,4);
$results = $this->dbs->numRows($query);
if($results < 3){
$sql = "SELECT * FROM `photo` WHERE `user` = ?i AND `pic` != ?s ORDER BY id ASC LIMIT ?";
$query = $this->dbs->query($sql, $this->user,$this->user_head,4);
}
}else{
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat = ?s ORDER BY RAND() LIMIT ?";
$query = $this->dbs->query($sql,$this->user,$this->user_head,$HC,4);
$results = $this->dbs->numRows($query);
}
Now, in order to get the data from the right query I can either define $data->getAll under each query - but that would mean repeating my code or I could try extracting the data from the last defined $query result - which I do not know how to do.
I know that there may be a better way of doing this but I am trying to improve my coding style as I think the safemysql class would need some improvements even if that would mean a bit more documentation.
I could try using $db->getAll instead of $db->query but, as far as I know, I cannot use numRows on GetAll.
As a matter of fact, this class is totally unusable. And the problem you mentioned is a least one.
It seems that someone who wrote it, never used this class in a real life project.
So, if you want a class which works and works way better, go for SafeMysql, as it will do exactly what you want:
$data = $db->getAll("SELECT * FROM `users` WHERE status = 'y'");
(note that you've got your data already, without any further code)
Nevertheless, you have to understand that the following statement of yours
I don't need parameters as the query gets it's values from a safe source inside a class.
is wrong.
It's OK to use a hard-coded value as you wrote it, but if you were intended to use a "safe" variable - it ought to be added via placeholder. Otherwise your query remains error-prone and unsafe.
So, it have to be
$id = 1; // "safe" variable
$data = $db->getRow("SELECT * FROM `users` WHERE id = ?i", $id);
To answer edited question. Not sure if it's what you need, but here is the code. It wu
if($HC == 'C')
{
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat != 'D' GROUP BY pic LIMIT ?";
$data = $this->dbs->getAll($sql,$this->user,$this->user_head,4);
if (count($data) < 3) {
$sql = "SELECT * FROM `photo` WHERE `user` = ?i AND `pic` != ?s ORDER BY id ASC LIMIT ?";
$data = $this->dbs->query($sql, $this->user,$this->user_head,4);
}
} else {
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat = ?s ORDER BY RAND() LIMIT ?";
$data = $this->dbs->query($sql,$this->user,$this->user_head,$HC,4);
}

OR clause in Zend DB update?

I'd like to do a Zend db update with an OR clause. What would be the equivalent statement to:
UPDATE mail
SET message_read = 1
WHERE id = 5
OR id = 10
When calling Zend_Db_Adapter::update(), multiple WHERE conditions will automatically be combined using AND (line 698 of Zend/Db/Adapter/Abstract.php in function _whereExpr).
You can get around this by creating your own Zend_Db_Expr which you will use as the WHERE condition and it will be left untouched.
For example:
$where[] = new Zend_Db_Expr(
$table->getAdapter()->quoteInto('id = ?', 5) . ' OR ' .
$table->getAdapter()->quoteInto('id = ?', 10)
);
// resulting expression:
// WHERE (id = 5 OR id = 10)
$table->update($data, $where);
If you had additional WHERE conditions, they would be combined with the OR condition by an AND.
Example:
$where[] = new Zend_Db_Expr(
$table->getAdapter()->quoteInto('id = ?', 5) . ' OR ' .
$table->getAdapter()->quoteInto('id = ?', 10)
);
$where[] = $table->getAdapter()->quoteInto('type = ?', 'sometype');
// resulting expression:
// WHERE (id = 5 OR id = 10) AND (type = 'sometype')
->where() will add a where clause to the query and will put an 'AND'. There is an orWhere method that exists to do that.
$select = $this->select();
$select->where('id = 5');
$select->orWhere('id = 10');
$this->fetchAll($select);