Updating via query builder in is not working - sql

I tried updating a column value using sql command, but it show general failure. Below is my code for update:
$name = 'ABC';
$id = 2;
$command = Yii::$app->db->createCommand()
->update('companies', ['company_name' => $name], 'company_id ='.$id.'');
$result = $command->queryAll();
When I execute this code below message is shown to me.
SQLSTATE[HY000]: General error
The SQL being executed was: UPDATE companies SET company_name='ABC' WHERE company_id =2
Error Info: Array
(
[0] => HY000
)
I cant find out why. Does anybody have any idea, what am I doing wrong here?
UPD
$command = Yii::$app->db->createCommand()
->update('companies', ['company_name' => $name], 'company_id ='.$id.'')->execute();
Can not use $command->queryAll() with update command.

There are couple of errors in your code.
First of all, why you are using queryAll() with UPDATE operation? Remove this line:
$result = $command->queryAll();
Second error - missing call of execute() command. Should be:
$command = Yii::$app->db
->createCommand()
->update('companies', ['company_name' => $name], 'company_id ='.$id.'')
->execute();
Check out documentation for yii\db\Command, especially execute() and queryAll() methods.

Related

Perl user input into SQL Like statement

Im trying to get user input and send it through to the SQL Like statement. But Im getting error: Can't call method "bind_param" on an undefined.
My Original code :
#!/usr/bin/perl
use DBI;
#use DBD::Oracle;
use strict;
use warnings;
use CGI;
print "Enter INCD number : ";
my $input = <>;
chomp $input;
my $DSN = 'driver={SQL Server};Server=ddsfs1; database=sdfds;TrustedConnection=Yes';
my $dbh = DBI->connect("dbi:ODBC:$DSN")
#print "connected.."
or die "$DBI::errstr\n";
my $query = $dbh->prepare("SELECT TOP 20 Id
,Created
,Updated
,Message
FROM FrameworkDEV3.Log.Entry
where Message like ?
and Created >= DATEADD(day, -10, GETDATE())
order by Created desc");
$sth->bind_param(1, '%$input%');
print $sth;
$sth->execute;
#DBI::dump_results($sth);
while( my #data = $query->fetchrow_array())
{
foreach(#data) {
print "[$_]";
}
print "\n\n";
}
$sth->finish;
$dbh->disconnect;
#print "Connected..";
print "\n";
Following code is fixed as per comments from Dave and Jim :
my $sth = $dbh->prepare("SELECT TOP 20 Id
,Created
,Updated
,Message
FROM FrDEVsd.Log.Entry
where Message like ?
and Created >= DATEADD(day, -10, GETDATE())
order by Created desc");
$sth->bind_param(1, "%$input%");
print $sth;
$sth->execute;
#DBI::dump_results($sth);
while( my #data = $sth->fetchrow_array())
{
foreach(#data) {
print "[$_]";
}
print "\n\n";
}
$sth->finish;
$dbh->disconnect;
print "\n";
The error im getting now is
DBI::st=HASH(0x2a9a480)
In your code:
my $query = $dbh->prepare("SELECT TOP 20 Id
,Created
,Updated
,Message
FROM sdada.ada.asd
where Message like ?
and Created >= DATEADD(day, -10, GETDATE())
order by Created desc");
my $sth->bind_param(1, "%$input%");
Notice the prepared statement is stored in a variable named $query, but you attempt to bind using $sth which was never set and is undefined. That is what the error message was telling you.
Use the same variable name both places (and later when you execute the statement) to fix the problem.
You've already been given a fish. Perhaps we can show you how to catch your own in the future.
This is your error:
Can't call method "bind_param" on an undefined
You call bind_param() on this line:
my $sth->bind_param(1, "%$input%");
So you're defining a variable (called $sth) and immediately expecting that variable to be an object that you can call a method on. When you define a variable with my the variable is initialised to undef unless you assign something to it like this:
my $var = 'something';
Your code is the equivalent of this.
my $sth = undef;
$sth->my $sth->bind_param(1, "%$input%");
Do you see the problem now?
In DBI code you'll often see the the variable $sth used to store the statement handle that we use to execute a statement. I suspect you've copied this from some example DBI code and taken the variable name from there. If $sth was a statement handle then you could certainly call the bind_param() method on it.
So $sth needs to be a statement handle. And we create one of those by calling the prepare() method on a database handle.
my $sth = $dbh->prepare($some_sql);
Oh, but wait.... you already have a line that looks a lot like that:
my $query = $dbh->prepare("SELECT ...");
So it looks to me like you started writing your own code, using $query as the variable to hold the statement handle. You then copied the bind_param() line from some sample code. That didn't compile, because it used $sth, which you hadn't declared, so you just stuck a my in front of it to get around that problem? Does that sound at all accurate?
What you really wanted was to call bind_param() on the statement handle that you had already created.
$query->bind_param(1, "%$input%");
But, to be honest, I think it's a good idea to stick with the "standard" names for DBi-related variables. It's what your maintenance programmer (which might well be you in six months time!) will expect to see.
So I'd change the prepare() line to:
my $sth = $dbh->prepare("SELECT ...");
And leave the bind_param() call as it is. You'll need to change the fetchrow_array() to be called on $sth as well.

Xquery ERROR err:XPDY0002: undefined value for variable $skill

I am trying to use xquery for a project and I cannot see why this query is not working. It gives me the following error:
err:XPDY0002: undefined value for variable $skill
I am new to xquery and I am using EXIST DB as a database and I have tried using base x db and this works there perfectly. Is there anything i am missing in existdb? Any help would be appeciated.
for $endorsement in doc('/db/users.xml')/LOUser/Endorsements
for $endorsed_skill in $endorsement/Skills
let $skill := $endorsed_skill/text()
for $user in doc('/db/users.xml')/LOUser/User[#URL = $endorsement/URL2/text()]
let $Name := $user/Name/text()
where not($user/Skills/text() = $skill)/* I am getting the error here*/
group by
$Name, $skill
return {$Name}

CActiveRecord::findall throws exception

I'm trying to perform a search in one of my tables based on a given criteria like so:
$id = 1;
$criteria = new CDbCriteria();
$criteria->addCondition("usr_currency=:currency");
$currencies = User::model()->findAll($criteria, array(':currency' => $id,));
I get a CDbException:
CDbCommand failed to execute the SQL statement:
SQLSTATE[HY093]: Invalid parameter number: no parameters were bound.
The SQL statement executed was:
SELECT * FROM `user` `t`
WHERE usr_currency=:currency
Where as, this works:
$id = 1;
$criteria = new CDbCriteria();
$criteria->addCondition("usr_currency=:currency");
$criteria->params = array(':currency' => $id,);
$comments = User::model()->findAll($criteria);
What is wrong with the first code fragment?
From CActiveRecord::find()
This is only used when the first parameter is a string (query condition). In other cases, please use CDbCriteria::params to set parameters.

Switching from mysql_ to PDO

After a lot of recommendation from others I have decided to make the switch from mysql_ to PDO. I started looking at PDO literally around 15 minutes ago and I'm stuck trying to convert this line of code into PDO format.
function verify_user($username, $recover_password) {
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password_recovery` = '$recover_password'"), 0) == 1) ? true : false;
}
I have looked at a couple of tutorials and as far as I can work out I can do the actual query with this code:
$verify_user = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password_recovery` = '$recover_password'";
$result = $con->prepare($verify_user);
$result->execute();
The problem I am having is the second part of the line of code - the mysql_result. Now that the query has run I have no idea how to return true or false using PDO. I'd appreciate any help. Thanks!
Updated:
$result = $con->prepare("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = :username AND `password_recovery` = :recover_password");
$result->bindParam(':username', $username, PDO::PARAM_STR);
$result->bindParam(':password_recovery', $recover_password, PDO::PARAM_STR);
$result->execute();
From reading that page you provided it would be:
$result = $con->prepare("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = :username AND `password_recovery` = :recover_password");
$result->bindParam(':username', $username, PDO::PARAM_STR);
$result->bindParam(':password_recovery', $recover_password, PDO::PARAM_STR);
$result->execute();
return ($con->fetch($result) == 1) ? true : false;
I'm probably miles out but I appreciate the help you've given me :) I'll do a couple more searches.
I would write the function this way:
function verify_user($username, $recover_password) {
$sql = "SELECT COUNT(`user_id`) AS count FROM `users`
WHERE `username` = ? AND `password_recovery` = ?";
$stmt = $con->prepare($sql);
$stmt->execute(array($username, $recover_password));
while ($row = $stmt->fetch()) { } /* should be exactly one row anyway */
return $row["count"] == 1;
}
There's no need to use bind_param(), since you can just pass values in an array argument to execute(). And there's no need to specify the parameter type (that's actually ignored, at least in the MySQL PDO driver).
Also be careful to do error-checking. The prepare() and execute() functions return false on error. Many things can cause an error. You could misspell a column name. Your database connection may lack the right database privileges. Someone could drop the table.
FWIW, proper error-checking is important when using the mysql_* and mysqli_* API's too, but it seems that few people do it right.
In the above code, I don't show checking the return values because I've made an assumption that we've enabled exceptions when we created the PDO connection.
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
That relieves us of having to write code to check the return values every time, but it means that an error will cause our application to go "white-screen". It's best practice to handle the exceptions in the caller function, and display some friendly error screen.

Codeigniter ActiveRecord update SQL error

I am working on CI 2.1.3 and encountering the following problem. What am I doing wrong here? Is there any reading or knowledge I need to do or know.
Codeigniter ActiveReocrd Update syntax
$data['spun'] = TRUE;
$this->db->update('registered', $data,
"registered_id = $registration['registered_id']");
what I expected
UPDATE `registered` SET `spun` = 1 WHERE `registered_id` = 1
what CI generated
UPDATE `registered` SET `spun` = 1 WHERE `id` = 1
DB table (in bracketing notation)
registered(registered_id, registered_name, ..., spun);
Edit 1
I also tried the following, but CI give the same SQL.
$this->db->update('registered', $data,
array('registered_id' => $registration['registered_id']));
I think the solution is very easy. You can simply do this:
$data['spun'] = TRUE;
$this->db->update('registered', $data,
array('registered_id' => $registration['registered_id']);
Based on Code Igniter documentation:
http://codeigniter.com/user_guide/database/active_record.html#update
you should use:
$data['spun'] = TRUE;
$this->db->where('registered_id', $registration['registered_id']);
$this->db->update('registered', $data);