mysql procedure integer to string error - codeigniter

I have an INSERT query in mysql.
I use procedure and my query is this: (I use codeigniter framework)
$query = $this->db->query('call Set_Shoe_SP(1, NULL, ?)' , array($type) );
$type is an integer, but it wants to insert as a string, and this error occurs:
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 '' at line 1
call Set_Shoe_SP(1, NULL, '20',
Filename: C:\xampp\htdocs\royalshop\system\database\DB_driver.php
Line Number: 330
What should I do? Thanks

If it is a data type error then it's as simple as casting the data type to string like this
Array((string)$type)
Not sure that this is your error

Try it this way:
$query = $this->db->query('call Set_Shoe_SP(1, NULL, ' . $type . ')' , FALSE );

Related

Search users by fullname in laravel

i want to search users by fullname so i need to concat two columns which are first_name and last_name and look if it matches the given value or not, this is my try
$users = User::where(function($usersSearchQuery) use ($user,$fullName){
$usersSearchQuery
->whereNotIn('id', $user->blockerUsers->pluck('blocked_id'))
->whereNotIn('id', $user->blockedUsers->pluck('blocker_id'))
->whereRaw('CONCAT(first_name," ",last_name) LIKE \''.$fullName.'\'%'); })->get();
i have an error in this line
->whereRaw('CONCAT(first_name," ",last_name) LIKE \''.$fullName.'\'%');
message: "SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1 (SQL: select * from users where (1 = 1 and 1 = 1 and CONCAT(first_name," ",last_name) LIKE 'BertHue'%))"
Try this:
$users = User::where(function($usersSearchQuery) use ($user,$fullName){
$usersSearchQuery->whereNotIn('id', $user->blockerUsers->pluck('blocked_id'))
->whereNotIn('id', $user->blockedUsers->pluck('blocker_id'))
->whereRaw('CONCAT(first_name," ",last_name) LIKE \''.$fullName.'%\'');
})->get();
I replaced your last where with a whereRaw which allows you to use raw SQL.

Applying postgis query in laravel got ErrorException (E_NOTICE) Array to string conversion

I want to store this variable to my database, this variable is got result by doing postgis query in laravel, but everytime I tried, I always got error "array to string conversion".
What I used :
Laravel v 5.8.17
Postgis v 2.5
I have installed postgis in database, I can doing query from pgadmin, but I don't know how to doing it from laravel
$longitude = $request->input('longitude');
$latitude = $request->input('latitude');
$topoint = "SELECT ST_GeomFromText('POINT(".$longitude." ".$latitude.")', 4326)";
$res = DB::select(DB::raw($topoint));
What setting in laravel that must I do to apply the postgis query and that query resulted the geom of that point ?
Update
I have tried to adding new code
$resultfromdb = DB::select(DB::raw($topoint));
$geomresult = json_encode($resultfromdb);
$post->apill_geom = $geomresult;
but it resulted new error, it is
SQLSTATE[XX000]: Internal error: 7 ERROR: parse error - invalid geometry
HINT: "[{" <-- parse error at position 2 within geometry (SQL: insert into "e_apill" ("kode", "waktu", "desa", "kecamatan", "kondisi", "apill_geom", "jenis", "lokasi") values (a8a, 2019-05-20 04:46:03, ?, ?, ?, [{"st_geomfromtext":"0101000020E61000000000005E77965B400635AD3816DE1EC0"}], APILL, ?) returning "gid")
What must I do to get this value 0101000020E61000000000005E77965B400635AD3816DE1EC0 on the variable $geomresult
I think I can close this question, cause now I have find my answer, the code I added is
$longitude = $request->input('longitude');
$latitude = $request->input('latitude');
$topoint = "SELECT ST_GeomFromText('POINT(".$longitude." ".$latitude.")', 4326)";
$res = DB::select(DB::raw($topoint));
$finalres = $res[0]->st_geomfromtext;
$res produced json array so I cannot input it to the field of database, and I must parse it through last code, and yeah it's worked, thanks for all support

How to use IN/AND clause in Yii framework?

I have a MySQL table with 3 columns: ID, name, user.
I wish to use the following SQL with Yii framework:
$sql = "SELECT * FROM my_table WHERE idName=".$name." AND user IN .$arrayOfUsers;
// $arrayOfUsers is an array of int [0]->1, etc.
I tried in three different ways, but without success:
1)
$sql = "SELECT * FROM my_table WHERE idName=".$name." AND user IN .$arrayOfUsers;
$command = $connection->createCommand($sql);
$dataReader = $command->query();
$query = $dataReader->readAll();
The error is:
PHP Error [8]
Array to string conversion
2)
$query = Yii::app()->db->createCommand()
->select('*')
->from('my_table')
->where(array('and', array('in', 'user', $arrayOfUsers), array('idName' => $name)))
->queryAll();
The error is:
PHP Error [8]
Undefined offset: 0
3)
$query = Yii::app()->db->createCommand()
->select('*')
->from('my_table')
->where(array('and', array('in', 'user', $arrayOfUsers), 'idName='.$name)))
->queryAll();
The error is:
CDbException CDbCommand failed to execute the SQL
statement: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'idName=7)'
at line 3. The SQL statement executed was: SELECT * FROM
my_table WHERE (user IN ('1', '2', '3', '4')) AND
(idName=7)
There has many ways to do but I'd like to use Active Record to handle this thing.
However, your question was around Query Builder, I give you correct one
Edited: (As your comment, idName is big INT instead of var char)
1) You got error because you pass $arrayOfUsers which was array, not expected string on your sql. It should be
$connection=Yii::app()->db;
$sql = "SELECT * FROM my_table WHERE idName=".$name." AND (user IN(".implode(',',$arrayOfUsers)."))";
$command = $connection->createCommand($sql);
$query = $command->queryAll();
2) Using Query builder and where operator
$query = Yii::app()->db->createCommand()
->select('*')
->from('my_table')
->where(array('in', 'user', $arrayOfUsers))
->andwhere('name = :name', array('idName'=>$name))
->queryAll();
3) If you want to wrap them together, it'll be fine, but they look unsightly like this
$query = Yii::app()->db->createCommand()
->select('*')
->from('my_table')
->where(array('and', 'idName= ' . $name, array('in', 'user', $arrayOfUsers)))
->queryAll();
More references how to use where operator from official document
// WHERE id=1 or id=2
where('id=1 or id=2')
// WHERE id=:id1 or id=:id2
where('id=:id1 or id=:id2', array(':id1'=>1, ':id2'=>2))
// WHERE id=1 OR id=2
where(array('or', 'id=1', 'id=2'))
// WHERE id=1 AND (type=2 OR type=3)
where(array('and', 'id=1', array('or', 'type=2', 'type=3')))
// WHERE `id` IN (1, 2)
where(array('in', 'id', array(1, 2))
// WHERE `id` NOT IN (1, 2)
where(array('not in', 'id', array(1,2)))
// WHERE `name` LIKE '%Qiang%'
where(array('like', 'name', '%Qiang%'))
// WHERE `name` LIKE '%Qiang' AND `name` LIKE '%Xue'
where(array('like', 'name', array('%Qiang', '%Xue')))
// WHERE `name` LIKE '%Qiang' OR `name` LIKE '%Xue'
where(array('or like', 'name', array('%Qiang', '%Xue')))
// WHERE `name` NOT LIKE '%Qiang%'
where(array('not like', 'name', '%Qiang%'))
// WHERE `name` NOT LIKE '%Qiang%' OR `name` NOT LIKE '%Xue%'
where(array('or not like', 'name', array('%Qiang%', '%Xue%')))
http://www.yiiframework.com/doc/guide/1.1/en/database.query-builder
Try this
$criteria = new CDbCriteria();
$criteria->select = "*";
$criteria->condition = "idname = :name ";
$criteria->params = array (
':name' => $name,
);
$criteria->addInCondition('user', $arrayOfUsers);
my_table::model()->findAll($criteria);

CodeIgniter ActiveRecord join() method wrapping numbers with backticks

This is my active record code in CodeIgniter:
$this->db->...
$this->db->join('post_likes', 'post_likes.user_id="'.$this->db->escape($online_user).'" AND post_likes.post_id=post.id', 'left');
And this is how it is interpreted:
LEFT JOIN `post_likes` ON `post_likes`.`user_id`="`3"` AND post_likes.post_id=post.id
it gives the error:
`user_id`="`3"`
How to write a direct number in active record?
Update:
removing escape
to test it on your computer you dont need to have a database. Just trying this code shows the error:
$this->db->select('*')
->from('mytable')
->join('post_likes', 'post_likes.user_id="3" AND post_likes.post_id=post.id', 'left');
$query=$this->db->get('');
var_dump($this->db->last_query());
exit(0);
result:
A Database Error Occurred
Error Number: 1064
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 '` AND post_likes.post_id=post.id' at line 3
SELECT * FROM (`mytable`) LEFT JOIN `post_likes` ON `post_likes`.`user_id`="`3"` AND post_likes.post_id=post.id
You SHOULD not use the double quotes in SQL query:
$this->db->join('post_likes', "post_likes.user_id = $online_user AND post_likes.post_id=post.id", 'left');
Update:
This is a bug in the current CI stable version (fixed in v3.0-DEV), CI ActiveRecord methods (which doesn't implement really ActiveRecord) are prepared for simple usages.
I fixed this issue before by hacking the core files (by adding a parameter to join method to disable _protect_identifires).
There we go:
In system/database/DB_active_rec.php line #310, add $escape as 4th parameter:
public function join($table, $cond, $type = '', $escape = TRUE)
And change $match[3] = ... to:
if ($escape === TRUE)
{
$match[3] = $this->_protect_identifiers($match[3]);
}
So, you can use join($table, $cond, $type = '', $escape = FALSE) to disable escaping.
In addition, setting _protect_identifires globally to FALSE is not in a correct direction.
the only option remains is using custom query():
$sql = "SELECT * FROM some_table WHERE id = ?"
$this->db->query($sql, array(3));
Try this
$this->db->join('post_likes', "post_likes.user_id=$the_userid AND
post_likes.post_id=post.id", 'left');
or
$this->db->join('post_likes', 'post_likes.user_id="'.$the_userid.'" AND
post_likes.post_id=post.id', 'left');
Update:
Define
$db['default']['_protect_identifiers']= FALSE;
in "application/config/database.php" at the end.
Simple solution would be to temporarily set the protect_identifiers off before join query, like so:
$this->db->_protect_identifiers = false;
After making join query you could set it back to true
Works for me in CodeIgniter version 2.1.2
try this one
$this->db->join('post_likes', 'post_likes.user_id="{$online_user}" AND post_likes.post_id=post.id', 'left');
please let me know if you face any problem.
Dont use $this->db->escape
$this->db->join('post_likes', 'post_likes.user_id="'.$online_user.'" AND post_likes.post_id=post.id', 'left');

CodeIgniter query syntax error

I am facing a syntax issue with a CodeIgniter database query. Can't figure out what's wrong.
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES (".$this->db->escape($_POST['email']).", ".$this->db->escape($lang).", ".$this->input->ip_address().")");
I am also looking for a way to output what the query looks like once the placeholders are replaced, as I am little confused with CodeIgniter debugging options.
It looks as though you are not escaping the strings that you're trying to input into the database. The query you've posted would evaluate to something like:
$query = $this->db->query("
INSERT IGNORE INTO table_name (email, lang, ip_address)
VALUES (email#email.com, en, 192.168.0.1)
");
This will throw an error as the strings in VALUES are not properly escaped. Instead of the query you're running you should use something like:
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES ('".$this->db->escape($_POST['email'])."', '".$this->db->escape($lang)."', '".$this->input->ip_address()."')
");
Note the new ' characters around each string.
use
echo $this->db->last_query();
for retrieving the query runned.
so then check if the query is well formatted.
To know what query you are passing to your database. Use below statement and to insert data into the database. Please follow the below procedure.
echo $this->db->last_query();
$data = array(
'email' => $this->db->escape($_POST['email']),
'lang' = > $this->db->escape($lang),
'ip_address' => $this->input->ip_address(),
);
Call your model function $this->model->insert_function_name($data);
Your model function in your model file
public function insert_function_name($data)
{
$this->db->insert($table_name,$data);
return $this->db->insert_id();
}
Try this : your query was missing single quotes to the string type of value like email, lang and ip
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES ('".$this->db->escape($_POST['email'])."', '".$this->db->escape($lang)."', '".$this->input->ip_address()."')");

Resources