How to give single quotes in SQL Query using yii frameowrk? - mysql

I'm trying to execute following SQL query using YII frameowrk
Query= select * from table where name='Bachelor''s degree'
By executing the above query I'm getting empty results. But I have content in tables.
From my perspective I think Yii framework not accepts query with single quotes in its contents.
So could you please suggest some other idea to resolve this issue ?
Thanks in advance.

Try query with parameter.
$name = "Bachelor's degree";
Yii::app()->db->createCommand()
->select()
->from('table_name')
->where('name = :name', array(':name' => "{$name}"))
->queryAll();

In YII way, bind your value to the statement.
$name = "Bachelor's degree";
$command=Yii::app()->db->createCommand();
$command->select('table_column1,table_column2,table_column3');
$command->from('table');
$command->where('name=:name', array(':name'=>$name));
echo $command->queryAll();

Related

Laravel Sum column database Eloquent

Trying to get the sum of a int field in one of my table should be pretty easy, unfortunately it is not as I'm getting different result whether I use Laravel, MySQL or Excel.
Laravel 5.4 gives me 20506:
Table::sum('field_name');
MySQL gives me 1830:
Select sum(field_name) from table;
And the data from the Excel sheet before importing it into the database:
Sum gives me 145689
Any idea? I tried to cast to integer before doing the sum but it doesn't work.
All the numbers are pretty big but don't contain comma or dot.
Examples of values I have to sum: (contain sometimes empty cells)
17906774
99630157
28581131
159551532
20312892
668928885
$query = YourModel::query();
$query->withCount([
'activity AS yoursum' => function ($query) {
$query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
}
]);
You can use laravel aggregate function SUM as :
$result = DB::table('table_name')
->select(DB::raw('SUM(field_name) as total_field_name'))
->get();
For more details you can follow:
https://laravel.com/docs/5.4/queries
Thanks
Try with
$result = DB::table(tablename)
->selectRaw('sum(column)')
->get();
If it still gives you wrong result, maybe wait for someone to give you a better answer. This is all I could think of.

PDO Sql query not working

I am using the following code to insert in MYSQL table:
try{
$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES(':t_id',':t_name',':mem_id')";
$stmt=db::con()->prepare($sql);
$stmt->bindParam(':t_id',$tid,PDO::PARAM_INT);
$stmt->bindParam(':t_name',$tNm,PDO::PARAM_STR);
$stmt->bindParam(':mem_id',$mId,PDO::PARAM_INT);
$stmt->execute();
}catch(PDOException $ex){
die("Error occured:".$ex->getMessage());
}
$tid variable has value=1;
$tNm variable has value='CBSE';
$mId variable has value=9
when this piece of code is run then no error is generated but in MYSQL table i observe the field values as 't_id'=0, 't_name'=t_name, 'mem_id'=0.I just don't understand what is wrong with my code.However, one funny thing is that when i try to acomplish the same task using the below mentioned code, proper data is inserted into the table.The code is
$db= new Database();
$db->open();
$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES('$tid','$tNm','$mId')";
$db->query($sql);
When using PDO to bind parameters, keep in mind that it appropriately quotes and escapes for you automatically. This means you need to remove the quotes from your VALUES statement, as follows:
$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES(:t_id,:t_name,:mem_id)";

Multiple PHP variables in MYSQL query with AND condition

This is my first code-question! I'm a beginner at both MySQL and PHP, so this might be really simple! Here is my code:
This is a file included in my Index.php...:
<?php
$query="SELECT * FROM wines WHERE Type='$type' AND Country='$country'";
$products=mysql_query($query);
?>
And these are the variables set with the $_GET function:
<?php
$type=$_GET['type'];
$fruit=$_GET['fruit'];
$country=$_GET['country'];
?>
And then later I'll fetch the array and work with it.
The problem is that my $query works fine with just the '$type'-variable, but not with the $country -variable - - - - or any other variable I've tried.
I use Microsoft Webmatrix and it tells me that the issue arises the very moment I type in the $-sign in the second variable...
So confused! Hope you can help a newcomer :)
EDIT: I found out the problem was with the "ticks" around my variables. The correct way to do it is with backticks ( `` ). Also, I started using PDO and MySQLi instead of mysql. For beginners, MySQLi is probably the easiest. Started sanitizing too.
Just a couple of (important) points to note...
You should probably be using the mysqli_* functions in the place of the mysql_ functions, as they are going to be deprecated in a following release.
start sanitizing your input before making DB queries. It's a good habit to get into early, and will save you a lot of headaches in the long run!
a good habit it to use sprintf and mysqli_real_escape_string to build your SQL before executing it on the db:
$sql = sprintf("SELECT * FROM wines WHERE Type='%s' AND Country='%s'" ,
mysqli_real_escape_string($db_object, $type),
mysqli_real_escape_string($db_object, $country));
$results = mysqli_query($db_object, $sql);
ps. in my example $db_object is coming from the call to mysqli_connect()
EDIT:
Using the (soon-to-be-defunct) mysql_ functions would be something like the following for the above example:
$sql = sprintf("SELECT * FROM wines WHERE Type='%s' AND Country='%s'" ,
mysql_real_escape_string($type),
mysql_real_escape_string($country));
$results = mysql_query($sql);
If you don't send a $type in your query string, the query is
SELECT * FROM wines WHERE Type='' AND [other stuff];
which will give back only wines with type = '';
Try:
<?php
$wheres=array();
if (isset($type)){$wheres['Type']=$type;}
if (isset($type)){$wheres['Country']=$country;}
// and so forth for each parameter
$query="SELECT * FROM wines";
if (count($wheres) != 0){
$query.=" WHERE ";
foreach ($wheres as $k => $v){$query.="$k='$v' AND ";}
$query.=" 1=1;"
}
$products=mysql_query($query);
?>

How to create a NOT IN where clause Doctrine_Query?

I am developing in symfony 1.4 using Doctrine ORM. I can't create a NOT IN where clause using an array with ids. This is my code:
$results = Doctrine_Query::create()
->from('Asset a')
->where('a.id NOT IN (?)', implode(',', $ids))
->execute();
The sql for this query that is generated is this one:
WHERE (a.id NOT IN ('1,5,6,7,8,9,10,11,12,13,14,15,17,18,20,24,25,26,29,30,28'))
As you can see is treating the array filled with ids like an string. I tried also without the implode of the array but I get this error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
The array $ids containing the excluded ids is a plain numeric one.
I can't find out what is the correct syntax for this clause. Thanks
You have to use whereNotIn (old doc but still ok).
$results = Doctrine_Query::create()
->from('Asset a')
->whereNotIn('a.id', $ids)
->execute();

CodeIgniter Active Record, basic update give error

I'm new to CodeIgniter and I get an error I cannot understand.
This is the code that give the error:
$data = array('adr' => $address);
$this->db->where('id', $id);
$this->db->update('domains', $data);
The error is:
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 '://www.example.com WHERE id = '10'' at line 1
This is the query:
UPDATE `domains` SET `adr` = http://www.example.com WHERE `id` = '10'
If I change this to
UPDATE `domains` SET `adr` = 'http://www.example.com' WHERE `id` = '10'
it works. Why is CodeIgniter creating this erroneous query?
Try escaping the single quotes in the $address variable before you call the update method.
Generally the CodeIgniter will automatically surround the value of $address with a single quote. I do not know why did you get this error message?
Curious, see if it works when you escape the string use $this->db->escape()
$data = array('adr' => $this->db->escape($address));
$this->db->where('id', $id);
$this->db->update('domains', $data);
I have the same problem and codeigniter do not add single qoutes to where clause.
When you enter integer value, sql do not give error but when you put string value (as a variable) to where clause, it gives error. But when you add single quotes to query and run it on phpmyadmin, it works.
So the solution is adding (string) statement to your variable: as in this (string)$id
I wrote before to add single quotes to variable as '$id', but this will not going to work (I'm new to codeigniter&php, thanks to commenter Mitchell McKenna, I checked out what I wrote before)