I have a query that works in psql, but when I insert it into my REST service it doesnt work. Here is my code:
exports.getProjects = function(req, res) {
'use strict';
var query = client.query('select projects.project_id, array_to_string(array_agg(distinct project_subservices.subservice_id), ',') as subservices, array_to_string(array_agg(distinct project_certifications.certification_id), ',') as certifications from projects left outer join project_subservices on projects.project_id = project_subservices.project_id left outer join project_certifications on projects.project_id = project_certifications.project_id group by projects.project_id');
query.on('row', function(row, result) {
result.addRow(row);
});
query.on('end', function(result) {
var finalResult = {};
finalResult.meta = {};
finalResult.meta.count = result.rows.length;
finalResult.projects = result.rows;
res.json(finalResult);
});
};
Here is the error I get:
/home/jason/Projects/Node/isx_server/node_modules/pg/lib/native/index.js:141
this._sendQueryWithParams(query.text, query.values, query.singleRowMode);
^
Error: Values must be an array
at Connection._pulseQueryQueue (/home/jason/Projects/Node/isx_server/node_modules/pg/lib/native/index.js:141:10)
at Connection.connection.on.clientBuilder.port (/home/jason/Projects/Node/isx_server/node_modules/pg/lib/native/index.js:241:18)
at Connection.EventEmitter.emit (events.js:93:17)
I can cut and paste this code into psql and it works find. What is the difference in the 2 environments that will cause the query not to work? How do I make this work? Thanks for the help.
You're not escaping those single quotes, so your js function things you're passing three variables instead of a single one…
If memory serves, js allows to use double quotes as string delimiters, so use that instead of single quotes seeing that you're not using double quotes in the query.
Else, add backslashes where needed to escape the single quotes.
Related
I want to Execute a line of SQL which looks like this:
conn.Open();
var db = new PetaPoco.Database(conn);
var sql = "INSERT INTO FOO (name) VALUES ( 'foo#bar.com')";
var response = db.Execute(sql);
The problem is that PetaPoco thinks #bar is a parameter. Is there a way to tell it not to treat any #'s specially? My super lame work around was to replace "#" with "at". I live with this shame.
"You are doing it wrong"™
To avoid SQL Injection attacks, and other minuances concatenting strings, you should use parameters:
var response = db.Execute("INSERT INTO FOO (name) VALUES (#0)", "foo#bar.com");
Wrong way, but works at least:
var response = db.Execute("INSERT INTO FOO (name) VALUES ('foo##bar.com')",
You need to use two # characters to escape it. I think this should work:
var sql = "INSERT INTO FOO (name) VALUES ( 'foo##bar.com')"
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
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.
<?php
$link = mysqli_connect('localhost','root','root');
$link->query('CREATE DATABASE IF NOT EXISTS users');
$link->Select_db('users');
$sql='SELECT id FROM users WHERE email = '.$useremail.' AND username = '.$username;
$results = $link->query($sql);
$numrows = $results->num_rows;
if ($numrows == 1) {
#update user information
} else {
#failed to update
}
?>
It only works part of the time, and i'm not able to nail down an error from it one way or the other. I can confirm that the error pops up on the $numrows=$results->num_rows; line, but as for why, i'm lost. Occasionally it will work as intended, so any and all advice on what i can do to fix it, or at least helping me understand it better is greatly appreciated. Thanks!
Use Double Quotation for query and varchar/string pass with single quotation
$sql="SELECT id FROM users WHERE email = '".$useremail."' AND username = '".$username."'";
$results = $link->query($sql);
$numrows = $results->num_rows();
The reason that your call to num_rows generated an error is that your query had an error, and query() returned false instead of a valid result resource. Because it's a fatal error to try to call a method on a false value, you should always check the return value of query() before using it. Example:
if (!($result = $link->query($sql))) {
die($link->error);
}
Problems with your query:
You create a database named users and make that the default database, then you run a SELECT query from a table named users. There would be no tables in a database you have just created. In SQL, we use SELECT against tables, not databases (these are two different things, analogous to files contained in a directory on a filesystem).
You don't quote the string arguments in your SQL statement. For example, this SQL would be an error:
SELECT id FROM users WHERE email = bill#example.com AND username = bill
It should be this instead:
SELECT id FROM users WHERE email = 'bill#example.com' AND username = 'bill'
I know the quotes get confusing, because you have PHP string quotes and then SQL string quotes, but here are several ways of accomplishing it:
$sql='SELECT id FROM users WHERE email = \''.$useremail.'\' AND username = \''.$username.'\'';
$sql="SELECT id FROM users WHERE email = '".$useremail."' AND username = '".$username."'";
$sql="SELECT id FROM users WHERE email = '{$useremail}' AND username = '{$username}'";
I'm not sure if you have protected your PHP variables appropriately. You must never interpolate PHP variables into SQL strings unless you have escaped the content of the variables.
$useremail_esc = $link->real_escape_string($useremail);
$username_esc = $link->real_escape_string($username);
$sql="SELECT id FROM users WHERE email = '{$useremail_esc}' AND username = '{$username_esc}'";
But it would be better to use prepared statements with parameter placeholders. This is easier to use than escaping variables, and it's more reliable. Here's an example:
$sql="SELECT id FROM users WHERE email = ? AND username = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $useremail, $username);
$stmt->execute();
$result = $stmt->get_result();
Notice that you don't use escaping when you use parameters, and you don't put SQL quotes around the ? placeholders.
I am working with mongo client. Sometimes the output of some commands I execute involve an enormous output, which mongo prints on screen. How can I avoid this?
There is a way to suppress output.
Using "var x = ...;" allows to hide output of expressions.
But there are other commands that harder to suppress like
Array.prototype.distinct = function() {
return [];
}
This produces printing of new defined function.
To suppress it you will need to write it in this way:
var suppressOutput = (
Array.prototype.distinct = function() {
return [];
}
);
Per the comment by #WiredPrairie, this solution worked for me:
Just set the return value to a local variable: var x=db.so.find(); and inspect it as needed.