Mysql query option param - php

There is my query string, are there any problems about the bindParam?
$str = "select A.option_id,count(*) as sum
from tb_feedback A,tb_question B,tb_group C
where (A.question_id=B.id)
and (:question is null or B.id=:question)
and (B.group_num=C.id)
and (:group is null or C.name=:group)
and (:fromdate is null or A.date >= CAST(:fromdate AS DATE))
and (:todate is null or A.date <= CAST(:todate AS DATE))
group by A.option_id";
$sql = $this->conn->prepare($str);
$sql->bindParam(':question', $obj['question']);
$sql->bindParam(':group', $obj['group']);
$sql->bindParam(':fromdate', $obj['fromdate']);
$sql->bindParam(':todate', $obj['todate']);

I have found the reason that parameter's type not NULL, it is string, so it is not succeed when execute the next statement
(:question is null or B.id=:question)

Related

SQL Server query on php

I'm begginner in this field so I need help.
I want to get integer value from this select. When I run this query in sql server - it returns correct value (so that part is okay)
My idea is to get integer value of $select -> put it in $value variable and use it after that.
Here is working sql expression:
$select = "SELECT COUNT (*) broj (SELECT a.CaseNo as CaseNo,
b.Naruc as Naruc,
b.Opis as Opis,
b.Vrijednost as cijena,
CONVERT(VARCHAR(50),b.Datumpn, 127) as datum_predaje,
(case when b.Kn IS NULL then 0 when b.Kn IS not null then b.Kn end) as kat1,
(case when b.Kn2 IS NULL then 0 when b.Kn2 IS not null then b.Kn2 end) as kat2,
(case when b.Kn3 IS NULL then 0 when b.Kn3 IS not null then b.Kn3 end) as kat3,
a.DateInserted as datum_unosa
FROM [Therefore].[dbo].[za_slanje_maila] a, [Therefore].[dbo].[TheCase1] b
WHERE CONVERT(date,a.DateInserted) = '".$today."'
AND a.DateInserted < '".$today3."'
AND a.CaseNo = b.CaseNo
AND b.Naruc is not null
AND b.Opis is not null
AND b.Vrijednost is not null
AND b.Datum_predaje is not null) broj";
After that, I tryed this
$data_api = sqlsrv_query($conn, $select, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
And then I try to call
$value = $data_api['broj']
- but that is empty.
How can I assign that value to the variable $value?
Thanks.
sqlsrv_query() doesn't return an array yet, but statement resource (or false on error). You can then use this resource to get the data array with sqlsrv_fetch_array() function.

Simple DateTime sql query with php object

This is my Query . It does not give result.If i place a quote the query runs. How to place that quote.
Select sum(r.views) as sum_views ,r.revenue_date ,
l.lot_id ,l.lot_name,r.type_name
FROM tbl_revenue_upload r , tbl_lot_details as l
WHERE AND l.lot_id ='.$search['lot'].'
And revenue_date >= '.$search['from_date'].'
And revenue_date <= '.$search['to_date'].'
group by r.type_id ,month(revenue_date)
'Select sum(r.revenue) as sum_revenue ,sum(r.views) as sum_views ,r.revenue_date ,l.lot_id ,l.lot_name,r.type_name
FROM tbl_revenue_upload r , tbl_lot_details as l
WHERE r.video_id = l.video_id AND l.lot_id ='.$search['lot'].'
And revenue_date >= "'.$search['from_date'].'"
And revenue_date <= "'.$search['to_date'].'"
group by r.type_id ,month(revenue_date)

Codeigniter return 0 result when I use Union All in query

$sql = 'SELECT bind_id, Title, category, image_url, keyword, style_Binder_id, end_user_id, NULL AS cphoto_id, NULL AS cphoto, NULL AS title, NULL AS company_id, DATE FROM styleBinds
UNION ALL
SELECT NULL , NULL , NULL , NULL , keyword, style_Binder_id, end_user_id, cphoto_id, cphoto, title, company_id, date_time FROM company_photo
ORDER BY DATE ASC';
$sql =$this->db->query($query);
if($sql->num_rows > 0){
$result=$sql->result();
return $result;
}else{
echo "0 records";
}
When I run this query in phpmyadmin it return 150 results
but In codeignitor It returns 0 results...
Simple typo problem. You have reversed the argument and the assignment.
code should be
$query=$this->db->query($sql);
if($query->num_rows() > 0){
return $query->result();
}else{
return NULL; //controller should decide what to do with no model results
}
Try this one :Assuming that you have date_time filed in your table and I suggest to use isnull instead of null.
SELECT bind_id, Title, category, image_url, keyword, style_Binder_id, end_user_id, NULL AS cphoto_id, NULL AS cphoto, NULL AS title, NULL AS company_id,date_time FROM styleBinds
UNION ALL
SELECT NULL as bind_id , NULL as Title , NULL as category , NULL as image_url,keyword, style_Binder_id, end_user_id, cphoto_id, cphoto, title, company_id, date_time FROM company_photo
ORDER BY date_time ASC;

Error passing an array to PL/pgSQL stored procedure

I have this procedure:
CREATE OR REPLACE FUNCTION get_saldo_conto(idUtente integer, idConto integer, categories int[], end_date date) RETURNS numeric(8,2) AS $$
DECLARE
row_transazione transazione%ROWTYPE;
saldoIniziale numeric(8,2);
totale numeric(8,2);
BEGIN
saldoIniziale = (SELECT saldo_iniziale FROM conto WHERE id = idConto AND id_utente = idUtente);
totale = 0;
FOR row_transazione IN SELECT *
FROM transazione
LEFT JOIN categoria ON id_categoria = categoria.id
WHERE id_conto = idConto
AND transazione.id_utente = idUtente
AND id_categoria = ANY (categories)
AND data <= end_date
LOOP
IF(row_transazione.tipo = 'entrata') THEN
totale = totale + row_transazione.importo;
ELSE
totale = totale - row_transazione.importo;
END IF;
END LOOP;
RETURN (saldoIniziale + totale) AS saldo_corrente;
END;
$$ LANGUAGE 'plpgsql';
When I call it with for example with
SELECT get_saldo_conto('1','19','{1,2,4,5,6}', '20/01/2015');
gives me an error
ERROR: op ANY/ALL (array) requires array on right side
Am I doing something wrong passing the array?
I tried also passing like '{1,2,4,5,6}'::int[] with no success.
CREATE TABLE transazione(
id SERIAL PRIMARY KEY,
tipo VARCHAR(7) NOT NULL CHECK(tipo IN('spesa', 'entrata')),
importo NUMERIC(8,2) NOT NULL,
descrizione VARCHAR(40),
data DATE DEFAULT CURRENT_TIMESTAMP,
id_conto INTEGER NOT NULL REFERENCES conto(id) ON UPDATE CASCADE ON DELETE CASCADE,
id_utente INTEGER NOT NULL REFERENCES utente(id) ON UPDATE CASCADE ON DELETE CASCADE,
id_categoria INTEGER REFERENCES categoria(id) ON UPDATE CASCADE ON DELETE SET NULL
);
Debug
You defined the row variable
row_transazione transazione%ROWTYPE;
But then you assign SELECT * FROM transazione LEFT JOIN categoriato it, which obviously does not fit the type.
The error message you display, however, does not make sense. The only case of ANY/ALL in your code looks correct. Are you sure you are calling the function you think you are calling? Investigate with:
SELECT n.nspname, p.proname
, pg_get_function_identity_arguments(p.oid) AS params
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE p.proname = 'get_saldo_conto';
.. to find all functions with the given name. And
SHOW search_path;
.. to check if the search_path leads to the right one.
Audited function
Your function would work like this:
CREATE OR REPLACE FUNCTION get_saldo_conto(_id_utente integer
, _id_conto integer
, _categories int[]
, _end_date date)
RETURNS numeric(8,2) AS
$func$
DECLARE
row_trans transazione;
saldoIniziale numeric(8,2) := (SELECT saldo_iniziale
FROM conto
WHERE id_utente = _id_utente
AND id = _id_conto);
totale numeric(8,2) := 0;
BEGIN
FOR row_trans IN
SELECT t.*
FROM transazione t
-- LEFT JOIN categoria ON id_categoria = categoria.id -- useless anyway
WHERE t.id_utente = _id_utente
AND t.id_conto = _id_conto
AND t.id_categoria = ANY (_categories)
AND data <= _end_date
LOOP
IF row_trans.tipo = 'entrata' THEN
totale := totale + row_trans.importo;
ELSE
totale := totale - row_trans.importo;
END IF;
END LOOP;
RETURN (saldoIniziale + totale); -- AS saldo_corrente -- no alias here!
END
$func$ LANGUAGE plpgsql;
But that's just to showcase the syntax. The function is expensive nonsense.
Superior simple query
Replace with a simple SELECT:
SELECT COALESCE((
SELECT saldo_iniziale
FROM conto
WHERE id_utente = _id_utente
AND id = _id_conto), 0)
+ COALESCE((
SELECT sum(CASE WHEN tipo = 'entrata' THEN importo ELSE 0 END)
- sum(CASE WHEN tipo = 'spesa' THEN importo ELSE 0 END)
FROM transazione
WHERE id_conto = _id_conto
AND id_utente = _id_utente
AND id_categoria = ANY (_categories)
AND data <= _end_date), 0) AS saldo;
Assuming rows in conto are unique on (id_utente,id).
Depending on implementation details the best query can vary. I chose a variant that is safe against missing rows and NULL values. Either way, a plain query should be much faster than a loop over all rows.
You can wrap this into a function (SQL or plpgsql) if you want.
Aside:
transazione.tipo should rather be an enum type - or even just "char" or boolean. varchar(7) is a waste for tag with two possible values.
And data DATE DEFAULT CURRENT_TIMESTAMP should really be data DATE DEFAULT CURRENT_DATE.

PHP vs Phpmyadmin

I've got this code which i execute on phpmyadmin which works 100%
Create Temporary Table Searches ( id int, dt datetime);
Create Temporary Table Searches1 ( id int, dt datetime, count int);
insert into Searches(id, dt) select a.id, now() from tblSavedSearches a;
insert into Searches1(id, dt, count)
select
b.savedSearchesId,
(select c.dt from tblSavedSearchesDetails c where b.savedSearchesId = c.savedSearchesId order by c.dt desc limit 1) as 'dt',
count(b.savedSearchesId) as 'cnt'
from tblSavedSearchesDetails b
group by b.savedSearchesId;
insert into tblSavedSearchResults(savedSearchId,DtSearched,isEnabled)
select id,now(),0 from Searches where not id in (select savedSearchId from tblSavedSearchResults);
update tblSavedSearchResults
inner join Searches1 on tblSavedSearchResults.savedSearchId = Searches1.id
Set tblSavedSearchResults.DtSearched = Searches1.dt, tblSavedSearchResults.isEnabled = 1;
However when i put the same code in php as below it generates an error
$dba = DbConnect::CreateDbaInstance();
$query = "";
$query.="Create Temporary Table Searches ( id int, dt datetime); ";
$query.="Create Temporary Table Searches1 ( id int, dt datetime, count int); ";
$query.="insert into Searches(id, dt) select a.id, now() from tblSavedSearches a; ";
$query.="insert into Searches1(id, dt, count) ";
$query.="select ";
$query.=" b.savedSearchesId, ";
$query.=" (select c.dt from tblSavedSearchesDetails c where b.savedSearchesId = c.savedSearchesId order by c.dt desc limit 1) as 'dt', ";
$query.=" count(b.savedSearchesId) as 'cnt' ";
$query.="from tblSavedSearchesDetails b ";
$query.="group by b.savedSearchesId; ";
$query.="insert into tblSavedSearchResults(savedSearchId,DtSearched,isEnabled) ";
$query.="select id,now(),0 from Searches where not id in (select savedSearchId from tblSavedSearchResults); ";
$query.="update tblSavedSearchResults ";
$query.="inner join Searches1 on tblSavedSearchResults.savedSearchId = Searches1.id ";
$query.="Set tblSavedSearchResults.DtSearched = Searches1.dt, tblSavedSearchResults.isEnabled = 1; ";
$dba->DbQuery($query) or die(mysql_error());
I get the following error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Create Temporary Table Searches1 ( id int, dt datetime, count int) insert into S' at line 1
Please if someone could assist me with this ...
Thanks
If your $dba->DbQuery($query) method is actually using mysql_query (Which I suppose it does, as you are using mysql_error), then, you cannot execute more than one query per call (quoting) :
mysql_query() sends a unique query (multiple queries are not supported) to the currently active
database on the server that's
associated with the specified
link_identifier.
You'll have to either :
separate your queries, and call mysql_query once for each query
should be quite easy, here : instead of concatening all queries into $query, just execute them one by one.
or stop using mysql_*, and start working with MySQLi, which provides a mysqli_multi_query function
You can only execute queries one at a time via PHP. Call $dba->DbQuery() once per new query instead.

Categories