Laravel SQL parameter bindings when using raw sql - mysql

I have the following query:
$venues = Venue::select(['id', 'name'])
->where('name', 'LIKE', "%{$query}%")
->orderByRaw("CASE " .
"WHEN name like '{$query}%' THEN 0 " . // start with
"WHEN name like '% {$query}%' THEN 1 " . // start of a later word
"ELSE 3 " .
"END"
)
->limit(5)
->get();
The issue is the above query is vulnerable to SQL injection.
How can I fix this?
Parameter bindings is explained here:
https://laravel.com/docs/5.6/queries#raw-expressions
But if I do:
$venues = Venue::select(['id', 'name'])
->where('name', 'LIKE', "%{$query}%")
->orderByRaw("CASE " .
"WHEN name like '?%' THEN 0 " . // start with
"WHEN name like '% ?%' THEN 1 " . // start of a later word
"ELSE 3 " .
"END",
[
$query,
$query,
]
)
->limit(5)
->get();
I get different results.

Try adding the percent to the query param, like this:
...
->orderByRaw("CASE " .
"WHEN name like ? THEN 0 " . // start with
"WHEN name like ? THEN 1 " . // start of a later word
"ELSE 3 " .
"END",
[
"{$query}%",
"% {$query}%",
]
)
...

Related

Laravel Error : Function name must be a string

$files = $request->file('attachment');
$attachmentDataPush = NULL;
if ($request->hasfile('attachment')) {
foreach ($files as $file) {
$message->attach($file->getRealPath(), [
'as' => $file->getClientOriginalName(),
'mime' => $file->getMimeType()
]);
$filename = 'AttachmentsBox/' . $message->getId() . '/' . $file->getClientOriginalName();
Storage::put($filename, $file->get());
$attachmentDataPush = $attachmentDataPush . "<" . $file()->getClientOriginalName() . ">";
}
}
I want to add the code I wrote in $ attachmentDataPush side by side in <> but it gives an error. "Function name must be a string" What do you think may be the problem. ?
$attachmentDataPush = $attachmentDataPush . "<" . $file()->getClientOriginalName() . ">";
Line gives an error.I will insert the transaction into the database.
$attachmentDataPush = $attachmentDataPush . "<" . $file->getClientOriginalName() . ">";
I functioned as file (). I accidentally put brackets. The top one is correct.

Trying to get a Property of Non Object in Yii2

I get this above mentioned error when i was trying to write a search and filter query for gridview,here is code:
Store Model: Relation
public function getStoreNamesCombo(){
return $this->storeName->classId . ' ' . $this->storeName->platformId . ' ' . $this->storeName->familyId . ' ' . $this->storeName->subFamilyName . ' ' . $this->storeName->variantName;
}
}
StoreSearch Model:
$query->joinWith(['author',
'storeNamesCombo']);
if(!empty($this->storeNamesCombo)){
$query->andWhere('storeNames.classId LIKE "%' . $this->storeNamesCombo . '%" ' .
'OR storeNames.platformId LIKE "%' . $this->storeNamesCombo . '%" ' .
'OR storeNames.familyId LIKE "%' . $this->storeNamesCombo . '%" ' .
'OR storeNames.subFamilyName LIKE "%' . $this->storeNamesCombo . '%" ' .
'OR storeNames.variantName LIKE "%' . $this->storeNamesCombo . '%" ' .
'OR CONCAT(storeNames.classId, " ", storeNames.platformId, " ", storeNames.familyId, " ", storeNames.subFamilyName, " ", storeNames.variantName) LIKE "%' . $this->storeNamesCombo . '%"'
);
Gridview
'value' => function($q) use ($storeFamilies, $storeClasses, $storePlatforms){
return implode('.', array_filter([
$storeClasses[$q->storeName->classId] ?? null,
$storePlatforms[$q->storeName->platformId] ?? null,
$storeFamilies[$q->storeName->familyId] ?? null,
$q->storeName->subFamilyName,
$q->storeName->variantName,
]));
Error
Trying to get property of non-object
Error Line: Store Model Relation.
UPDATE:
public function getStoreName()
{
return $this->hasOne(StoreNames::className(), ['id' => 'storeNameId'])->via('transaction');
}
thanks in advance,
Make sure relation is fetched first to be safe.
public function getStoreNamesCombo()
{
if ($this->storeName) {
return $this->storeName->classId . ' ' . $this->storeName->platformId . ' ' . $this->storeName->familyId . ' ' . $this->storeName->subFamilyName . ' ' . $this->storeName->variantName;
}
return null;
}
EDIT:
BUT in your code one thing does not make sense. You are using value of getStoreNamesCombo() as the condition for query searching through storeNames table which is something like an inception idea.
I guess what you want to do is:
Set field in form model that will be filled with search term for the query condition.
public $storeNameSearch;
User fills that through the form for example. Now you can use it for the query.
if (!empty($this->storeNameSearch)){
$query->andWhere([
'or',
['like', 'storeNames.classId', $this->storeNameSearch],
['like', 'storeNames.platformId', $this->storeNameSearch],
['like', 'storeNames.familyId', $this->storeNameSearch],
['like', 'storeNames.subFamilyName', $this->storeNameSearch],
['like', 'storeNames.variantName', $this->storeNameSearch],
]);
}
BTW checking concatenated fields here seems redundant.
You can use getStoreNamesCombo() (->storeNamesCombo) on the prepared model in the gridview.
Edit 2:
If some of the columns are integers it sounds more reasonable to build conditions differently. If you can filter each column separately and there are filter fields user can fill it would be something like:
$query
->andFilterWhere(['storeNames.classId' => $this->storeClassId])
->andFilterWhere(['storeNames.platformId' => $this->storePlatformId])
->andFilterWhere(['storeNames.familyId' => $this->storeFamilyId])
->andFilterWhere(['like', 'storeNames.subFamilyName', $this->storeFamilyName])
->andFilterWhere(['like', 'storeNames.variantName', $this->storeVariantName]);
where first 3 columns are integers and last two are strings.

If where and or clause in Sql searching

I have build a query to search on text using n_make and n_month using if, where and or clause
However - unsure why is n_month not getting executed, search only happening for text if its in n_make and not in n_month
I want a search to display output if its shown in either n_make or n_month
// Filter by search in title
$search = $this->getState('filter.search');
if (!empty($search))
{
if (stripos($search, 'id:') === 0)
{
$query->where('a.id = ' . (int) substr($search, 3));
}
else
{
$search = $db->Quote('%' . $db->escape($search, true) . '%');
$query->where('( a.n_make LIKE ' . $search . ' )')
or
$query->where('( a.n_month LIKE ' . $search . ' )')
;
}
}
else
{
$search = $db->Quote('%' . $db->escape($search, true) . '%');
$query->where('( a.n_make LIKE' . $search . ') OR ( a.n_month LIKE' . $search . ')');
}

Joomla Jdatabase query code with join does not work

I run the php code below within the 'Eval' section of a Fabrik form element. The code is supposed to return/put a number in a form field, but nothing appears in the form field.
When I used another query (refer to '$query-> ' lines) the code does work, so I get the impression that the query contains errors; however, when executing the related webpage with the form fields no sql error appears.
I have no idea what is wrong with the query(?)
Code:
$form_productname = 'testproduct';
$form_username = 'myname';
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
//$query->select($db->quoteName(array('a.id', 'b.productid')));
$query->select($db->quoteName('b.productid'));
$query->from($db->quoteName('#__products', 'b'));
$query->join('INNER', $db->quoteName('#__extendedreg_users', 'a') . ' ON (' . $db->quoteName('a.user_id') . ' = ' . $db->quoteName('b.owner') . ')
AND (' . $db->quoteName('a.cf_collectivename') . ' = ' . $db->quote($form_username) . ')
AND (' . $db->quoteName('b.productname') . ' = ' . $db->quote($form_productname)).')'.;
//echo $query;exit;
$db->setQuery($query);
$db->execute();
$results = $db->loadObjectList();
return count($results);
UPDATE: cause was syntax php error in where statement:
. $db->quote($form_productname)).
must be:
. $db->quote($form_productname).
You are not getting any errors because you are not catching any errors. Have a look at How to do SQL exception / error handling.
Do at least a $query->dump() and run your query in a console if you can't figure out what is wrong.
I don't understand why are you quoting the value you are comparing $form_username and $form_productname. But maybe it's late and I am tired.

Fatal error: Call to a member function Show_LastRec_Pack() on a non-object

It has been already 5 days and still can't figure out where's the problem! so here i post the error and the whole code. Hopefully someone can help! I'll appreciate it very much.
Fatal error: Call to a member function Show_LastRec_Pack() on a non-object in packgames.php on line 69
here's "packgames.php":
<?
/**
* Block Last Rec Pack
**/
define ('PACK_GAMES_TO_SHOW', 3);
require_once ('recmod/constants.php');
$query = "SELECT r.*, pp.topic_id, p.Nick, b.*, p.Rating
FROM " . TABLE_RECGAMES . " r, " . $this->db->obj['sql_tbl_prefix'] . "attachments a, " . $this->db->obj['sql_tbl_prefix'] . "posts pp,
" . TABLE_PLAYERS." p, recs_aoc_flags b
WHERE a.attach_id = r.attach_id
AND a.attach_rel_id = pp.pid
AND r.Id_Player > 0
AND p.Id_Player = r.Id_Player
AND b.flag_id = p.flag_id
ORDER BY r.Id_RecordedGame DESC
LIMIT " . PACK_GAMES_TO_SHOW;
$this->DB->query($query);
$packs = array ();
while ($player = $this->DB->fetch ())
{
$flag = '<img src="' . PATH_FLAGS . $player['flag_image'] . '" alt="'.$player['flag_country'].'" title="' . $player['flag_country'] . '" align="absmiddle" border="0">';
$packs[] = array (
'GAMES' => $player['Players'],
'PLAYER' => $player['Nick'],
'FLAG' => $flag,
'RATING' => $player['Rating'],
'ID_POST' => $player['topic_id']
);
}
$tmp = $this->registry->getClass('output')->getTemplate('recgames')->Show_LastRec_Pack ($packs);
echo $tmp;
?>
Whatever that object call template is returning, it's not an object. Do some var_dumps() on the call chain and figure out where a null or other non-object is being returned. Most likely on getTemplate().