I am updating the db table using below code but it does not seem to working fine.
$model = new Admin_Model_DbTable_SmsTemplate();
$where = $model->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
$model->getDbTable()->update(array('content'=>$content), $where);
what is the error in this code as it is giving affected rows zero.
Thanks.
When using Zend_Db_table IN ZF1.
You can achieve it like this:-
$db=Zend_Db_Table::getDefaultAdapter();
$model = new Admin_Model_DbTable_SmsTemplate($db);
$where = 'id = ' . $id;
$model->update(array('content'=>$content), $where);
OR
$db=Zend_Db_Table::getDefaultAdapter();
$where = 'id = ' . $id;
$db->update('YourTableName', array('content = ?' => $content,),
$where
);
And the adapter will do quote work for you.
Related
Is it possible to query a firestore collection to get all document that starts with a specific string?
I have gone through the documentation but do not find any suitable query for this.
You can but it's tricky. You need to search for documents greater than or equal to the string you want and less than a successor key.
For example, to find documents containing a field 'foo' staring with 'bar' you would query:
db.collection(c)
.where('foo', '>=', 'bar')
.where('foo', '<', 'bas');
This is actually a technique we use in the client implementation for scanning collections of documents matching a path. Our successor key computation is called by a scanner which is looking for all keys starting with the current user id.
same as answered by Gil Gilbert.
Just an enhancement and some sample code.
use String.fromCharCode and String.charCodeAt
var strSearch = "start with text here";
var strlength = strSearch.length;
var strFrontCode = strSearch.slice(0, strlength-1);
var strEndCode = strSearch.slice(strlength-1, strSearch.length);
var startcode = strSearch;
var endcode= strFrontCode + String.fromCharCode(strEndCode.charCodeAt(0) + 1);
then filter code like below.
db.collection(c)
.where('foo', '>=', startcode)
.where('foo', '<', endcode);
Works on any Language and any Unicode.
Warning: all search criteria in firestore is CASE SENSITIVE.
Extending the previous answers with a shorter version:
const text = 'start with text here';
const end = text.replace(/.$/, c => String.fromCharCode(c.charCodeAt(0) + 1));
query
.where('stringField', '>=', text)
.where('stringField', '<', end);
IRL example
async function search(startsWith = '') {
let query = firestore.collection(COLLECTION.CLIENTS);
if (startsWith) {
const end = startsWith.replace(
/.$/, c => String.fromCharCode(c.charCodeAt(0) + 1),
);
query = query
.where('firstName', '>=', startsWith)
.where('firstName', '<', end);
}
const result = await query
.orderBy('firstName')
.get();
return result;
}
If you got here looking for a Dart/Flutter version
Credit to the java answer by Kyo
final strFrontCode = term.substring(0, term.length - 1);
final strEndCode = term.characters.last;
final limit =
strFrontCode + String.fromCharCode(strEndCode.codeUnitAt(0) + 1);
final snap = await FirebaseFirestore.instance
.collection('someCollection')
.where('someField', isGreaterThanOrEqualTo: term)
.where('someField', isLessThan: limit)
.get();
I found this, which works perfectly for startsWith
const q = query(
collection(firebaseApp.db, 'capturedPhotos'),
where('name', '>=', name),
where('name', '<=', name + '\uf8ff')
)
The above are correct! Just wanted to give an updated answer!
var end = s[s.length-1]
val newEnding = ++end
var newString = s
newString.dropLast(1)
newString += newEnding
query
.whereGreaterThanOrEqualTo(key, s)
.whereLessThan(key, newString)
.get()
I am writing code using nestjs and typeorm.
However, the way I write is vulnerable to SQL injection, so I am changing the code.
//Before
.where(`userId = ${userId}`)
//After
.where(`userId = :userId` , {userId:userId})
I am writing a question because I was changing the code and couldn't find a way to change it for a few cases.
//CASE1
const query1 = `select id, 'normal' as type from user where id = ${userId}`;
const query2 = `select id, 'doctor' as type from doctor where id = ${userId}`;
const finalQuery = await getConnection().query(`select id, type from (${query1} union ${query2}) as f limit ${limit} offset ${offset};`);
//CASE2
...
.addSelect(`CASE WHEN userRole = '${userRole}' THEN ...`, 'userType')
...
//CASE3 -> to find search results in order of accuracy
...
.orderBy(`((LENGTH(user.name) - LENGTH((REPLACE(user.name, '${keyword.replace( / /g, '', )}', '')))) / LENGTH('${keyword.replace(/ /g, '')}'))`,
'ASC')
...
//CASE4
let query = 'xxxx';
let whereQuery = '';
for(const i=0;i<5;i++)
whereQuery += ' or ' + `user.name like '%${keyword}%'`
query.where(whereQuery)
I cannot use parameter in the select function.
In the above case, I am wondering how to change it.
Is it ok to not have to modify the select code?
I have a search query that its parameters changes depending on the client input.
await prisma.$queryRaw(`SELECT column FROM table ${condition ? `WHERE column = '${condition}'` :' ' } `)
how can I write this query using prepared statement and avoiding duplicate queries. The only solution I came up with is the following:
const result = condition ? await prisma.$queryRaw(`SELECT column FROM table WHERE column = $1`,condition) : await prisma.$queryRaw(`SELECT column FROM table`)
The goal from this is to avoid sql injections from the first query.
EDIT
after trying the solution suggested by #Ryan I got the following error:
Raw query failed. Code: `22P03`. Message: `db error: ERROR: incorrect binary data format in bind parameter 1`
here's my implementation:
const where = Prisma.sql`WHERE ${searchConditions.join(' AND ')}`;
const fetchCount = await prisma.$queryRaw`
SELECT
COUNT(id)
FROM
table
${searchConditions.length > 0 ? where : Prisma.empty}
`;
that will translate to the following in the prisma logs:
Query:
SELECT
COUNT(id)
FROM
table
WHERE $1
["column = something"]
SOLUTION
I had to do a lot of rework to achieve what I want. Here's the idea behind it:
for every search condition you need to do the following:
let queryCondition = Prisma.empty;
if (searchFilter) {
const searchFilterCondition = Prisma.sql`column = ${searchFilter}`;
queryCondition.sql.length > 0
? (queryCondition = Prisma.sql`${queryCondition} AND ${streamingUnitCondition}`)
: (queryCondition = searchFilterCondition);
}
afterwards in the final search query you can do something of this sort:
SELECT COUNT(*) FROM table ${queryCondition.sql.length > 0 ? Prisma.sql`WHERE ${queryCondition}` : Prisma.empty}
You can do it like this:
import { Prisma } from '#prisma/client'
const where = Prisma.sql`where column = ${condition}`
const result = await prisma.$queryRaw`SELECT column FROM table ${condition ? where : Prisma.empty}`
Here is my working version, using Prima.join :
import { Prisma } from '#prisma/client'
const searchConditions: Prisma.Sql[] = []
if (q) {
searchConditions.push(Prisma.sql`column = ${q}`)
}
const where = searchConditions.length ?
Prisma.sql`where ${Prisma.join(searchConditions, ' and ')}` :
Prisma.empty
await prisma.$queryRaw(
Prisma.sql`
select *
from table
${where}
`
)
I have the following code in PHP:
$IDs = implode(",", array_keys($result["matches"]));
$sql = "SELECT * FROM table WHERE id IN ($IDs)";
I am "translating" it into Node.js, and I suppose that implode becomes array.join, so I tried this:
var ids = Object.keys(answer['matches']).join(",");
var sql = "SELECT * FROM xml_it WHERE id IN (" + ids + ")";
now, if I echo the PHP $sql variable, I get the expected result:
SELECT * FROM table WHERE id IN (3187,3220,3233,3245,3246,3251,3253,3256, ...
BUT, with node.js, I am getting this:
SELECT * FROM xml_it WHERE id_xml IN ([0,1,2,3,4, ...
The answer['matches'] obviously is the same result (it's basically a Sphinx search result)
Any idea why I am not getting it as a string but the keys?
the data of $result and var answer looks like this:
[{"doc":3187,"weight":1,"attrs":{}},{"doc":3220,"weight":1,"attrs":{}},{"doc":3233,"weight":1,"attrs":{}},
This should work:
var matches = answer['matches'].map( function( o ) {
return o.doc;
});
var ids = matches.join(",");
var sql = "SELECT * FROM xml_it WHERE id IN (" + ids + ")";
gotta map out the doc field since the structure is different
I am getting my feet wet with Kohana but having trouble with pagination. i get the following error :
ErrorException [ Fatal Error ]: Class
'Pagination' not found
following the unoffical wiki I amended the bootstrap file to include this:
Kohana::modules(array( 'database' => MODPATH.'database', 'userguide' => MODPATH.'userguide', 'pagination' => MODPATH.'pagination', ))
but that didn't seem to help.
my second question is with regards to query count.... I am surprised there is no function like $query-count() unless i opt for ORM instead i find this solution a bit clunky given that a query count is a must for every pagination request:
$result['count'] = $pagination_query->select('COUNT("*") AS result_count')->execute()->get('result_count');
Any suggestions?
thank you very much
Kohana 3.1 does not come with the pagination module...
it must be downloaded from
https://github.com/kohana/pagination
then go to the class/kohana edit line 199 from ->uri to ->uri()
that does it
as to the query count....still searching.
hope this helps someone
There used to be a count_last_query() function in the Database class which provided the total results of the last query run as it would be without any limit or offset, but they pulled it from version 3.0.9. You can find the documentation of it here:
http://kohanaframework.org/3.0/guide/api/Database#count_last_query
I've actually built upon the code from that function to make my own count query function if you want to use that.
protected static function _pagedQuery($query) {
$sql = (string)$query;
if (stripos($sql, 'LIMIT') !== FALSE) {
// Remove LIMIT from the SQL
$sql = preg_replace('/\sLIMIT\s+[^a-z]+/i', ' ', $sql);
}
if (stripos($sql, 'OFFSET') !== FALSE) {
// Remove OFFSET from the SQL
$sql = preg_replace('/\sOFFSET\s+\d+/i', '', $sql);
}
if (stripos($sql, 'ORDER BY') !== FALSE) {
// Remove ORDER BY from the SQL
$sql = preg_replace('/\sORDER BY\s+`\w+`(\.`\w+`)?(\s+DESC|\s+ASC)?/i', '', $sql);
}
$db = Database::instance();
$result = $db->query(Database::SELECT, '
SELECT COUNT(*) AS ' . $db->quote_identifier('total_rows') . '
FROM (' . $sql . ') AS ' . $db->quote_table('counted_results'),
TRUE
);
return (int)$result->current()->total_rows;
}