Doctrine setParameter always produces "?" - symfony

I would like to compare a datetime value (from a database) with the current time and check whether the current time is before or after the value in the database. This is done in a Symfony project. I tried to follow the instructions on the Symfony website.
So I wrote the following Doctrine query in a Repository Class which checks for a user lockout time and checks if it still lies in the future:
$user_id = 1; // Just giving $user_id a value for this example
$qb = $this->createQueryBuilder('user')
->andWhere('user.lockout_time > :time')
->setParameter('time', date("Y-m-d H:i:s"))
->andWhere('user.user_id = :user_id')
->setParameter('user_id', $user_id);
$query = $qb->getQuery();
echo $query->getSQL();
die;
When running this, both Where clauses contain "?" in the comparative value (e.g. WHERE user.lockout_time > ?). Obviously I want the actual values to be used in the query.
Initially I thought the date() function might be the issue, but even if I just use the :user_id I get the above error.
If I write ->andWhere('user.user_id = 1') I get the desired result.
If I replace :time with some date in the format 'Y-m-d H:i:s', I get the message "Error: Expected end of string..." (with the ... being the value for the Hour).
So both my setParameter() lines are not passing the values set in them. What am I overlooking?
Edit:
The suggested question here is not a duplicate. That just helps me see the query that is sent off. It was helpful in preparation of this question.

So here my own answer after some (= way too much) time of digging around.
The "?" are escaped values and do not represent what is actually in the query (which is another reason the above link doesn't help). To resolve this I resorted to monitoring the MySQL general log.
Here how to get to it, if someone has the same question. This log shows the actual SQL query.

Related

Firebase + DialogFlow - Realtime database- Cloud function return query result only after second request

I'm writing a simple Google Action which will read the Firebase Realtime Database, and return result in the response. My problem is, the query result is being passed back in response to DialogFlow only after at least 2 attempts.
Below the screenshots showing the end result in the Simulator
First query screenshot
The first line of the response is returned from the Cloud Function, and contains values passed with the "Context". There is no second line in this response.
below is the screen showing the result after sending exactly the same request second time.
Second query screenshot
First line is the same as previously, but this time I also get the second line which contains the query result data.
It looks like my code is "working" (I get the correct data from the database), but for some reason it only works if I trigger it at least 2 times in quick succession.
Below is the code snipped which handle this request:
function googleAssistantHandler(agent) {
let conv = agent.conv();
let outCommandContext = agent.getContext('outcommand');
let outCharacterContext = agent.getContext('outcharacter');
let character = outCharacterContext.parameters.character;
let command = outCommandContext.parameters.command;
agent.add('<prosody rate="140%" pitch="0.4">' + character +' '+ command +'</prosody>');
var movesRef = admin.database().ref('characters/'+character.toLowerCase()+'/moves/');
movesRef.limitToFirst(1).orderByChild("notation")
.equalTo(command.toString()).on("child_added",function(snapshot){
agent.add(`record number is ` + snapshot.key);
});
}
I've tried using once() instead of on() (as it would make more sense in my case... i don't need to listen to changes on the database, i just want to retrieve data once)- but, I couldn't get it to work.
Can you guys help me out understanding why my query returns result only after the second trigger?
Thanks!
you are using a callback method to get the data from database so there is no guaranty that it will be called before your function is returned. to solve the issue, you need to use a Promise and return that Promise in your function so the last few lines of your function will look like this
return movesRef.limitToFirst(1).orderByChild("notation")
.equalTo(command.toString()).on("child_added").then(snapshot= > {
agent.add(`record number is ` + snapshot.key);
});
You need to always use promises when working with databases. Moreover, the first response that you see might be because of the failed function which timed out. If you see your console logs in firebase, you might see the errors. Also check your default response, if it has the text that User said $name or something similar, then that is what causes the issue in the first attempt.
If you still don't get it to work, try logging the returned data and post your logs here.

Perl dancer error execute method undefined

I was trying to make a website using perl dancer, below is my code. It seems to be correct but the page keeps loading and never enters the values in the database. When I cancel the page I get an error stating "request to POST /appform crashed: Can't call method "execute" on an undefined value". I can't figured out whats wrong in the code. If you have any other code please mention.
I am using SQLite for database.
There is a database campus.dband I am inserting the value in student table.
post '/appform' => sub {
my $q = CGI ->new;
my $name = $q->param ("firstname");
my $password = $q->param("password");
my $mobile_no = $q->param("mobile");
my $gender = $q->param("gender");
my $email = $q->param("email");
my $address = $q->param("address");
my $sslc = $q->param("SSLC");
my $hsc = $q->param("HSC");
my $cgpa = $q->param("cgpa");
my $languages = $q->param("lang");
my $internships = $q->param("intern");
my $preferred_loc = $q->param("country");
my $sql = "insert into student(name,mobile_no,gender,email,address,sslc,hsc,cgpa,languages,internships,preferred_loc,password,applied_job,company_applied) values ('?','?','?','?','?','?','?','?','?','?','?','?','?','?');";
my $sth = database->prepare($sql);
$sth->execute($name,$mobile_no,$gender,$email,$address,$sslc,$hsc,$cgpa,$languages,$internships,$preferred_loc,$password) or die $sth->errstr;
#$sth->execute();
$sth-> finish;
set_flash('New entry posted!');
redirect '/';
};
You're using the database keyword to get a database handle. I'm guessing that's coming from Dancer2::Plugin::Database (it would be useful if you could include information like this in your question).
The error says that you're calling execute() on an undefined value. You're calling execute() on the variable $sth. So $sth is undefined. You get $sth by calling prepare() on the database handle returned from database(). So it looks like the prepare() call is failing. You should check the return value from that call and throw an error if it fails.
The most common reason for prepare() to fail is that you're trying to compile an SQL statement that contains an error. I can't see any obvious error in your SQL, but it's worth checking it by running it manually against your database.
I see you're using bind params in your SQL statement. That's a great idea, but please note that you don't need to quote the question marks in your SQL - the database driver will handle that for you. I don't think that's what is causing your problem though.
I also see that you're using CGI.pm inside your Dancer app to get the request parameters. To be honest, I'm slightly surprised that it works - but it's a terrible idea. Dancer has its own keywords that will give you this information. Look at query_parameters(), body_parameters() and route_parameters() in the Dancer documentation.
In addition to the points made already, that your DBI prepare() call is probably failing (add error-checking to see why, e.g. my $sth = database->prepare('...') or die "DB error: " . database->errstr) and that you're using CGI.pm within a Dancer app (... don't do that, I'm surprised it would work at all - look at the Dancer documentation for how to access the params your app was sent), look also at the quick_insert convenience method provided by Dancer::Plugin::Database / Dancer2::Plugin::Database so that you don't have to write that SQL INSERT statement at all.

Drupal db_update not working, unless intentional error through batch API

I'm submitting a form from a view through the Drupal batch API to update a row in my DB. The statement I use for that is:
db_update('scores')
->fields(['status' => 0])
->condition('sid', $score->sid)
->execute();
The batch returns successfully and gives me the feedback of
Performed undo publishing on 1 item.
However, the row in the DB is not updated.
When using the following code:
$result = db_update('scores')
->fields(['status' => 0])
->condition('sid', $score->sid)
->execute();
drq($result);
The batch API returns an error due to unexpected output, and after refreshing the page manually, the row in question is updated!
I can't for the life of me figure out what's going on nor how to get the query from the batch API to log somewhere so I can see what's going on.
Any help is much appreciated.
It seems that there's two queries being executed. One by the db_update statement described earlier, and one by entity.controller.inc::save() in the entity module. The latter started a transaction which negated the db_update action.
I now changed the code to the following
db_update('scores')
->fields(['status' => 0])
->condition('sid', $score->sid)
->execute();
$score->status = 0;
$score->save();
And it works as intended. The status of the item gets changed in DB and all seems well. I know this is an ugly workaround for the actual problem, but at this moment it's the only solution I can find.

Using sqlite database with qt

Here is my code, there doesn't seem to be anything wrong:
QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("thedata.sqlite");
db.open();
QSqlQuery query;
query.prepare("SELECT lastname FROM people where firstname='?' ");
query.bindValue(0, lineEdit->text());
bool x = query.exec();
if(x){
lineEdit_2->setText(query.value(0).toString());
}
else {
QSqlError err;
err = query.lastError();
QMessageBox::about(this,"error",err.text() );
}
When the program is working always it gives the error parameter count mismatch I'm using qt 4.8 and its own headers for using sqlite.
I would be very thankful for any advice, though I searched in google i see many posts in this issue but nothing helped me.
Thank you.
You're prepared statement is wrong, it should be:
quary.prepare("SELECT lastname FROM people where firstname=?");
Notice that there are no single quotes (') around the placeholder. If you put the quotes, it gets passed as a literal to the database, leaving you with a parameter-less query and code that passes too many parameters.
(Changing that variable name to query would be a nice touch too.)
Also you need to check the return value if QSqlQuery::prepare, and print out/display the error message you're getting from that if it fails – otherwise QSqlQuery::exec resets the current error and you'll get a pretty meaningless error message if there was a problem parsing the prepared statement.
if(x){
lineEdit_2->setText(quary.value(0).toString());
}
This is incorrect too. The you need to call (and check the return value of) query.next() to position the result set to the first row returned (if there is one). You can't use .value(X) before you've called .next().

Linq returning wrong value from DB

I have a super simple select in a wcf service like
BusinessModel.Candidate candidateObject
= dcMUPView.Candidates.SingleOrDefault(dev => dev.Username == username);
But when I hit this code, and then check the candidateObject, it's candidateid value is incorrect. In the DB candidateid is the identity column and primary key. In this case it is 2572884 in the DB but when I look in the candidateObject is says the value returned is something like 0x00274254. Anyone know what might cause something like this?
I think your query is returning the correct record, since 0x00274254 (base 16) = 2572884 (base 10).
If you are checking the value using the debugger, make sure you have the Hexadecimal Display option turned off (see here for more info: Visual Studio debugger - Displaying integer values in Hex).

Resources