Postgres query in php with a date variable - postgresql

Can you please help me on below query?
php code://
$countdate='2017-01-03';
$countsql='SELECT rucid,"databaseType","countLoggedOn","prodCount","nprodCount","countType" FROM "ru_countLog" WHERE "countLoggedOn"=$countdate';
--> It's giving syntax error
syntax error at or near "$" LINE 1: ...untType" FROM "ru_countLog"
WHERE "countLoggedOn"=$countdate

Remove the internal double quotes from your query:
$countsql = "SELECT rucid, databaseType, countLoggedOn,
prodCount, nprodCount, countType
FROM ru_countLog
WHERE countLoggedOn = $countdate";
Note that this query is vulnerable to SQL injection. Consider parametrizing $countdate. With http://php.net/manual/en/function.pg-query-params.php, this would become
$countsql = 'SELECT rucid, databaseType, countLoggedOn,
prodCount, nprodCount, countType
FROM ru_countLog
WHERE countLoggedOn = $1';
$result = pg_query_params($dbconn, $countsql, array($countdate));
where $dbconn is your database connection

Maybe you should try like this
$countdate='2017-01-03';
$countsql='SELECT rucid,"databaseType","countLoggedOn","prodCount","nprodCount","countType" FROM "ru_countLog" WHERE "countLoggedOn"='.$countdate;
Hope this help

Related

Check if pg_prepare was already executed

Is there a way to check if pg_prepare already executed and remove it from the session?
Seems like pg_close doesn't remove prepared statement from the session. Kind of seems like a bug in php, but maybe I'm missing something or maybe there is a workaround.
public static function readSubdomains($dcName, $filter = null) {
// ...
$conn = pg_pconnect($connectionString);
// ...
$result = pg_prepare($conn, "subdomains", "SELECT subdomain
from tenants
where $where
order by 1 asc
");
$result = pg_execute($conn, "subdomains", $params);
// ...
pg_close($conn);
}
Second call to readSubdomains shows a warning like this:
Warning: pg_prepare(): Query failed: ERROR: prepared expression "subdomains" already exists in inc/TestHelper.php on line 121
Always check the official manuals for this sort of stuff.
https://www.postgresql.org/docs/current/view-pg-prepared-statements.html
Oh - if pg_close isn't dropping prepared statements then it isn't closing the connection. You might have some connection pooling involved.

appending static variable within sql query

I am trying to use the late static binding concept during insertion but I am getting a syntax error when I am writing this statement:
I am using php version 5.3.8
$resultArray = $this->connection->query("insert into " static::$table "(title,link) values('hi','hello')");
Looks like you forgot some dots to concatenate static::$table with the rest of the query string. Try this:
$resultArray = $this->connection->query("insert into " . static::$table . "(title,link) values('hi','hello')");

VB Script in Access Variable not found

So I was advised that I could create some copy replace functionality to this form.
Here is my coding attempt in VB:
First I connect to DB using DAO. Then I use a SELECT statement that has been verified to pull the last record inserted into the DB. Then I try to refill the controls with the values from the query but I am getting reference errors.
Private Sub AutoFill_Click()
Dim db As DAO.Database, rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb()
strSQL = "SELECT DISTINCTROW TOP 1 CPOrders.Cust, Customer.NAME, CPOrders.CP_Ref, CPOrders.Slsman, CPOrders.Date_opn, CPOrders.CPSmall, CPOrders.InvIssu, CPOrders.InvNo, CPOrders.InvDate, CPOrders.DueDate, CPOrders.ETADate, CPOrders.Closed, CPOrders.BuyerRef, CPOrders.ToCity, CPOrders.ToState, CPOrders.ToCtry, CPOrders.ToPort, CPOrders.Supplier, CPOrders.Origin, CPOrders.Product, CPOrders.GradeType, CPOrders.NoUnits, CPOrders.Pkg, CPOrders.Qty, CPOrders.TotSale, CPOrders.TotCost, CPOrders.GrMargin, CPOrders.[Sale$/Unit], CPOrders.[Cost$/Unit], CPOrders.OceanCost, CPOrders.OceanNotes, CPOrders.BLadingDate, CPOrders.USAPort, CPOrders.FOBCost, CPOrders.FASExportVal, CPOrders.InlandFrt, CPOrders.CommodCode, CPOrders.Notes FROM Customer INNER JOIN CPOrders ON Customer.[CUST_#] = CPOrders.Cust ORDER BY CPOrders.CP_Ref desc;"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset, dbReadOnly)
rs.MoveFirst
CP_Ref.ControlSource = rs!CP_Ref
Slsman.ControlSource = rs!Slsman
CPSmall.ControlSource = rs!CPSmall
InvIssu.ControlSource = rs!InvIssu
InvDate.ControlSource = rs!InvDate
DueDate.ControlSource = rs!DueDate
Closed.ControlSource = rs!Closed
rs.Close
db.Close
The control source reference picks up and autocompletes the word.
I would think that as it stands. although i'm not filling all the values with records from my SELECT statement that it would populate but instead i get things like #NAME? where the values should be. I also get a break in my code and it says "Invalid use of null"
Why? I appreciate your guys input and I can provider screenshots if necessary. I think this is involving the reference tie, but I'm not sure. Any help is much appreciated.
You are using the field names from the SELECT statement as if they were variables.
CP_Ref.ControlSource = rs("CP_Ref")
Slsman.ControlSource = rs("Slsman")
CPSmall.ControlSource = rs("CPSmall")
InvIssu.ControlSource = rs("InvIssu")
InvDate.ControlSource = rs("InvDate")
DueDate.ControlSource = rs("DueDate")
Closed.ControlSource = rs("Closed")
When you have that worked out, tackle the "Invalid use of null" problem by first identifying any fields that could potentially be NULL and using something like
SELECT Iif(IsNull([InvDate]), '', [InvDate]) As [InvDate], ...
in the SELECT statement to pass across a minimum of an empty string rather than a NULL value.

Cannot create parameterised query for Interbase using ADO.NET

I'm trying to issue a parameterised SELECT to an Interbase XE database using ADO.NET. The code I'm using is as follows:
using (OdbcConnection odbcConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["LawbaseTest"].ToString()))
{
odbcConnection.Open();
using (OdbcCommand odbcCommand = new OdbcCommand())
{
odbcCommand.CommandType = CommandType.Text;
odbcCommand.Connection = odbcConnection;
odbcCommand.Parameters.Add(new OdbcParameter(":CaseNumber", 1265));
odbcCommand.CommandText = "select * from cmstub where cm_recnum = :CaseNumber";
using (IDataReader rdrData = odbcCommand.ExecuteReader())
{
Output(rdrData["CM_DESC"]);
}
}
}
I'm getting the following error:
ERROR [42S22] [DataDirect][ODBC InterBase driver][InterBase]Dynamic SQL Error, SQL error code = -206, Column unknown, CASENUMBER
Which suggests to me that the query is not being sent to Interbase in a syntax it recognises as a parameterised query.
This is rather harder than I was expecting. Am I being a ficko? Can you help?
It seems to be the norm that named parameters aren't supported widely, did you try using ? instead, i.e. cm_recnum = :CaseNumber to cm_recnum = ?

Can I tell if an ado.net DbCommand is a query or not (before executing it)

I am trying to write a Powershell script to run a general SQL command against a database. The idea is that Run-SQL "select ..." will run the SQL text against the currently open database. If the SQL statement is a query, it should return a DataTable. If it is a non-query (DDL or DML) it should return nothing ($null).
In order to do this, I need to know which method (ExecuteReader or ExecuteNonQuery) to execute against the command. Is there a way to determine this? (I'm happy to prepare the command if that helps).
As an alternative, I can add a -query argument to be supplied by the user, which distinguishes the two cases, but as a potential user, I'd find this annoying (as, in my view, I have already said whether it's a query by the SQL I used, why say again?)
My key use is for Oracle databases, so an Oracle-specific answer is OK with me, although I'd prefer something generic.
I think you could just use ExecuteReader whether it's a query or not. It may be overkill but in some quick experiments with doing an UPDATE ($reader returns nothing) and a COUNT ($reader[0] outputs scalar result) - it just seems to work.
$connstr = "server=.\SQLEXPRESS;Database=AdventureWorks;" +
"Integrated Security=true;Persist Security Info=False"
$conn = new-object System.Data.SqlClient.SqlConnection $connstr
#$query = "UPDATE Production.Product SET Name = 'ACME' WHERE Name = 'Blade'"
$query = "SELECT Count(*) FROM Production.Product"
$cmd = new-object System.Data.SqlClient.SqlCommand $query,$conn
$conn.Open()
try
{
$reader = $cmd.ExecuteReader()
while ($reader.Read())
{
$reader[0]
}
}
finally
{
$conn.Dispose()
}
As an alternative to what Keith said you could try
$sql = 'Select count(1) From SomeTable;'
$sql = $sql.TrimStart(' ')
if ($sql -match "^select") { Write-Host 'ExecuteReader' }
else { Write-Host 'ExecuteNonQuery'}
The trim is there in case the SQL command has a leading space since $sql = ' select ' won't match "^select"