Here my code :
$context = new Context;
$context->name = 'blabla';
if($original_lang === 'en') {
$context->en = $sentence;
} else if($original_lang === 'fr') {
$context->fr = $sentence;
} else if($original_lang === 'ja') {
$context->ja = $sentence;
}
$context->save;
I think the part with original lang is redundant, anyone know a best way to write this ? thanks !
You can write as below
$context->{$original_lang} = $sentence;
Related
I have a problem code beneath this line does not work! How can I let this work? where ... orWhere orWhere does filter but cumulates the queries. where ... where does not provide any result. Can someone help me?
$artworks = Artwork::where('category_id', $category)
->where('style_id', $style)
->where('technic_id', $technic)
->where('orientation', $orientation)
->get();
Here is the full code:
if (request()->category_id) {
$category = request()->category_id;
} else {
$category = 0;
}
if (request()->style_id) {
$style = request()->style_id;
} else {
$style = 0;
}
if (request()->technic_id) {
$technic = request()->technic_id;
} else {
$technic = 0;
}
if (request()->orientation_id == 'vertical') {
$orientation = 'vertical';
} else if (request()->orientation_id == 'horizontal') {
$orientation = 'horizontal';
} else {
$orientation = 0;
}
$artists = Artist::get();
$artworks = Artwork::where('category_id', $category)
->where('style_id', $style)
->where('technic_id', $technic)
->where('orientation', $orientation)
->get();
return view('frontend.index', compact('artworks', 'artists'));
I think you want to use OR Condition and you are mistaking it with double where. Please look below to understand properly
If you want AND condition in your query then the double where are used but if you want OR condition then you have to use orWhere
Examples:
AND condition
Query::where(condition)->where(condition)->get();
OR Conditon
Query::where(condition)->orWhere(condition)->get();
If you expect all of your variables to be set
Your query variables category_id, style_id, orientation_id & technic_id are being defaulted to 0 if they are not true.
Your query is fine, but you may not have the data you think you do.
Run the following at the top of this function:
print_r($request->all());
exit;
If all of your variables are optional
very procedural, basic way to achieve this:
$artists = Artist::get();
$artworks = Artwork::where('id', '>', 0);
$category_id = request()->input('category_id');
if ($category_id != '') {
$artworks->where('category_id', request()->category_id);
}
$style_id = request()->input('style_id');
if ($style_id != '') {
$artworks->where('style_id', request()->style_id);
}
$technic_id = request()->input('technic_id');
if ($technic_id != '') {
$artworks->where('technic_id', request()->technic_id);
}
$orientation_id = request()->input('orientation_id');
if ($orientation_id != '') {
$artworks->where('orientation_id', request()->orientation_id);
}
$artworks->get();
return view('frontend.index', compact('artworks', 'artists'));
I have 4 parameter in my URL. I retrieve the url parameter from my url that is given. With every parameter I'm changing the path to a directory and get different images.
My sample url look like this:
www.sample.com?cat=section1&language=de&prices=pl
The code is working but it's a spagheti code.
Is there a solution to make is less DRY ? How do I retrieve multiple url parameter ?
if(isset($_GET["cat"])) {
switch ($cat) {
case 'section1':
if(isset($_GET["language"])) {
$language = htmlspecialchars($_GET["language"]);
if($language == "de") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/dp/low/*.jpg');
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
}
elseif ($language == "en") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/ep/low/*.jpg');
}
else {
$files=glob('pages/section1/en/low/*.jpg');
}
}
else {
$files=glob('pages/section1/en/low/*.jpg');
}
}
elseif ($language == "cz") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/cp/low/*.jpg');
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
break;
case 'section2':
//the same like in section 1, path is .../section2/...
break;
case section3:
//the same like in section 1, path is .../section3/...
break;
default:
//the same like in section 1
break;
}
else {
//the same like in section 1
}
The path d=german, e=english, c=czech, p=prices, n=noprices
You could shorten/remove many if else statements with just doing the checks:
$lang_code = $language[0];
There you have your first letter, you can do the same with every GET parameter.
So you can use that as in:
$files=glob('pages/section1/'.$lang_code.'p/low/*.jpg');
You can do the same for everything else.
P.s.: don't forget to sanitze any user input i.e.:
$language=mysqli_real_escape_string($conn, $_GET['language']);
I'd probably do something like this:
<?php
$allowedCat = ['section1', 'section2'];
$allowedLanguage = ['pl', 'en', 'cz'];
$allowedPrice = ['pl', '??'];
$cat = (isset($_GET["cat"])) ? $_GET["cat"] : null;
$language = (isset($_GET["language"])) ? $_GET["language"] : null;
$prices = (isset($_GET["prices"])) ? $_GET["prices"] : null;
if (!in_array($cat, $allowedCat)) throw new \Exception('Invalid `cat`');
if (!in_array($language, $allowedLanguage)) throw new \Exception('Invalid `language` option.');
if (!in_array($prices, $allowedPrice)) throw new \Exception('Invalid `price` option.');
$someVar1 = ($prices === 'pl') ? 'p' : 'n';
$someVar2 = $language[0];
$files = glob("pages/{$cat}/{$someVar1}{$someVar2}/low/*.jpg");
Think that should be self explanatory. Translates one to one really. Was not certain on how the other price option was specified...
I'm not so sure whether it is smart to post both problems in one question, but lets try:
So, I was checking my server's error log and it still has two notices, both about "Array to string conversion in [...]".
The first line should be this:
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
Context:
// Build an url which match a route
if ($this->use_routes || $force_routes) {
$url = $route['rule'];
$add_param = array();
foreach ($params as $key => $value) {
if (!isset($route['keywords'][$key])) {
if (!isset($this->default_routes[$route_id]['keywords'][$key])) {
$add_param[$key] = $value;
}
} else {
if ($params[$key]) {
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
} else {
$replace = '';
}
$url = preg_replace('#\{([^{}]*:)?'.$key.'(:[^{}]*)?\}#', $replace, $url);
}
}
$url = preg_replace('#\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\}#', '', $url);
if (count($add_param)) {
$url .= '?'.http_build_query($add_param, '', '&');
}
}
The second one is this line:
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
as part of this:
// legacy mode or default image
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ((Configuration::get('PS_LEGACY_IMAGES')
&& (file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg')))
|| ($not_default = strpos($ids, 'default') !== false)) {
if ($this->allow == 1 && !$not_default) {
$uri_path = __PS_BASE_URI__.$ids.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg';
}
} else {
// if ids if of the form id_product-id_image, we want to extract the id_image part
$split_ids = explode('-', $ids);
$id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]);
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ($this->allow == 1) {
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').$theme.'.jpg';
}
}
return $this->protocol_content.Tools::getMediaServer($uri_path).$uri_path;
}
public function getMediaLink($filepath)
{
return $this->protocol_content.Tools::getMediaServer($filepath).$filepath;
}
PHP is not my strength, so I have no idea what to do :/
Also I found some other questions about Array to string notices, but it seemed to me like you can't solve them the same way...
Thanks in advance for any help!
This error is appearing because some of the variables in these two lines are supposed to be String but they are actually array.
You need to print all the variables used in these 2 lines using the var_dump() function of PHP, this will tell you which of the variables are actually an Array, but they are supposed to be a String as per your code.
On the basis of the output, you need to modify your code to fix the issue.
I just wrote this and was thinking there must be an easier/more clean way to do this as it looks terrible doing it this way:
if(isset($_GET['m']) && isset($_GET['v'])) {
Router::Get($_GET['m'], $_GET['v']);
} elseif(isset($_GET['m'])) {
Router::Get($_GET['m'], "");
} else {
Router::Get("", "");
}
I'm looking for a cleaner way, like:
Router::Get(is('m'), is('v'));
Any suggestions to shorten/clean this kind of if-statements?
Can do,
$m = isset($_GET['m']) ? $_GET['m'] : "";
$v = isset($_GET['v']) ? $_GET['v'] : "";
Router::Get($m, $v);
You can encapsulate the logic:
Router::$query = $_GET;
Router::Get('m', Router::Get('v'))
class Router {
static public $query;
static function Get($name, $default = '') {
return isset(self::$query[$name]) ? self::$query[$name] : $default;
}
}
I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}