PHP script error Notice: Undefined variable - php

I am writing a PHP script for advanced searching but an error occurred. Please help
Code:
$key = $_GET['key'];
$auth = $_GET['auth'];
$lang = $_GET['lang'];
$pub = $_GET['pub'];
if(isset($key) OR isset($auth) OR isset($lang) OR isset($pub))
{
if ($key != NULL){$keyword = "AND (native_name LIKE '%".$key."%' OR unique_name LIKE '%".$key."%')";}
if ($auth != 0) {$auther = "AND auth_id=".$auth."";}
if ($lang != 0) {$language = "AND lang_id=".$lang."";}
if ($pub != 0) {$publisher = "AND pub_id=".$pub."";}
$search_query = "SELECT native_name from books WHERE status=1 ".$keyword." ".$auther." ".$language." ".$publisher."";
print $search_query;
}
Error:
Notice: Undefined variable: keyword in FILE_PATH on line 90
Notice: Undefined variable: auther in FILE_PATH on line 90
Notice: Undefined variable: language in FILE_PATH on line 90
Notice: Undefined variable: publisher in FILE_PATH on line 90

If you are creating variables through if statements then there is a likelihood that these variables won't be created.
There are a couple of different options in your case.
1, Use Ternary syntax
$keyword = $key != NULL ? "AND (native_name LIKE '%".$key."%' OR unique_name LIKE '%".$key."%')" : "";
$author = $auth !=0 ? "AND auth_id=".$auth : "";
$language = $lang !=0 ? "AND lang_id=".$lang : "";
$publisher = $pub !=0 ? "AND pub_id=".$pub : "";
2, Predefine your variables
$keyword = "";
$author = "";
$language = "";
$publisher = "";
if ($key != NULL){$keyword = "AND (native_name LIKE '%".$key."%' OR unique_name LIKE '%".$key."%')";}
if ($auth != 0) {$auther = "AND auth_id=".$auth."";}
if ($lang != 0) {$language = "AND lang_id=".$lang."";}
if ($pub != 0) {$publisher = "AND pub_id=".$pub."";}

$keyword/$auther/etc.. only get assigned if the corresponding value in _POST is set. If no data is passed in, $key/$auth/etc... will be empty strings or null, which will be equal to 0/null. Try:
if ($key != null) {
$keyword = ...;
} else {
$keyword = some default value;
}
and similarly for the other ones.

Related

How to split query builder in laravel 5.2?

I have three variables and I only want to add certain where clause if those variables are not null or blank.
$brand = $request->brand == 0 ? "" : $request->brand ;
$category = $request->category == 0 ? "" : $request->category ;
$subcategory = $request->subcategory == 0 ? "" : $request->subcategory;
$items = Item::select('items.*','brands.brand_name','category.category_name','subcategory.subcategory_name')
->leftJoin('brands','items.brand_id','=','brands.id')
->leftJoin('category','items.category_id','=','category.id')
->leftJoin('subcategory','items.subcategory_id','=','subcategory.id');
if($brand != ""){
$items->where('items.brand_id',$brand);
}
if($category != ""){
$items->where('items.category_id',$category);
}
if($subcategory != ""){
$items->where('items.subcategory_id',$subcategory);
}
$items->get();
Now I am getting below error
'Illuminate\Database\Eloquent\Builder could not be converted to
string'
$items is an Eloquent Builder instance so take output in other variable:
$items = Item::select('items.*','brands.brand_name','category.category_name','subcategory.subcategory_name')
->leftJoin('brands','items.brand_id','=','brands.id')
->leftJoin('category','items.category_id','=','category.id')
->leftJoin('subcategory','items.subcategory_id','=','subcategory.id');
if($brand != ""){
$items->where('items.brand_id',$brand);
}
if($category != ""){
$items->where('items.category_id',$category);
}
if($subcategory != ""){
$items->where('items.subcategory_id',$subcategory);
}
$data = $items->get();
Try to use this part as like this. assign your $items variable every condition.
$items = Item::select('items.*','brands.brand_name','category.category_name','subcategory.subcategory_name')
->leftJoin('brands','items.brand_id','=','brands.id')
->leftJoin('category','items.category_id','=','category.id')
->leftJoin('subcategory','items.subcategory_id','=','subcategory.id');
if($brand != ""){
$items = $items->where('items.brand_id',$brand);
}
if($category != ""){
$items = $items->where('items.category_id',$category);
}
if($subcategory != ""){
$items = $items->where('items.subcategory_id',$subcategory);
}
$items = $items->get();
$Items = DB::table('Item')
->join('brands','items.brand_id','=','brands.id')
->Join('category','items.category_id','=','category.id')
->Join('subcategory','items.subcategory_id','=','subcategory.id');
->select('items.*','brands.brand_name','category.category_name',
'subcategory.subcategory_name')
->get();
dd($Items);

MySQL:Query with multiple conditions

Im creating detailed product search.I verified that ,my variables are posted correctly, but the query don't finding anything. My question is:
What could be wrong in this query and what could be the best solution for detailed search in SQL?
<?php
if (
isset($_POST["productName"]) || isset($_POST["searchCategory"]) ||
isset($_POST["searchManufacturer"]) || isset($_POST["costFrom"]) ||
isset($_POST["costTo"])
){
$stmt=$user_home->runQuery("SELECT* FROM Products
WHERE (productTitle='$_POST[productName]' OR '$_POST[productName]' IS NULL)
AND (category='$_POST[searchCategory]' OR '$_POST[searchCategory]' IS NULL)
AND (manufacturer='$_POST[searchManufacturer]' OR '$_POST[searchManufacturer]' IS NULL)
");
echo $stmt->rowCount();
}
Try to proper forming WHERE statement. You should add conditions for productTitle, category, manufacturer fields only then isset proper POST fields.
Try this code:
<?php
if (
isset($_POST["productName"]) || isset($_POST["searchCategory"]) ||
isset($_POST["searchManufacturer"]) || isset($_POST["costFrom"]) ||
isset($_POST["costTo"])
){
$conditions = array();
if (isset($_POST['productName'])) {
$conditions[] = "(productTitle='".$_POST['productName']."')";
}
if (isset($_POST['category'])) {
$conditions[] = "(category='".$_POST['searchCategory']."')";
}
if (isset($_POST['searchManufacturer'])) {
$conditions[] = "(manufacturer='".$_POST['searchManufacturer']."')";
}
$where = implode(' AND ', $conditions);
if ($where) {
$where = 'WHERE '.$where;
} else {
$where = "";
}
$stmt=$user_home->runQuery("SELECT * FROM Products ". $where);
echo $stmt->rowCount();
}

how to escape empty and/or black field on PDO update?

i have a tabe with many fields and i want to change one or many fields with the same update method , the problem is when i try to update it affect the others fields that i have not updated too .
this is my sql function :
<?php
if ($_REQUEST['fct']=="ModelUpdate")
{
if ( isset( $_REQUEST['day'] ) && isset( $_REQUEST['month'] ) && isset( $_REQUEST['year'] ) ) {
$D_DATE_NAISSANCE = "".$_REQUEST['year']."/".$_REQUEST['month']."/".$_REQUEST['day']."";
}else{
$D_DATE_NAISSANCE = $_REQUEST['model_bidthday'];
}
$PK_MODEL = isset($_REQUEST['PK_MODEL']) ? $_REQUEST['PK_MODEL'] : $_SESSION['PK_MODEL'];
$K_KEY_MODEL = isset($_REQUEST['K_KEY_MODEL']) ? $_REQUEST['K_KEY_MODEL'] : $_SESSION['K_KEY_MODEL'];
$FK_STUDIO = $_REQUEST['model_studio'];
//$S_LOGIN = $_REQUEST['model_username'];
//$S_EMAIL = $_REQUEST['model_adressmail'];
//$S_PASSWORD = $_REQUEST['S_PASSWORD'];
$S_FIRSTNAME = $_REQUEST['model_firstname'];
$S_LASTNAME = $_REQUEST['model_lastname'];
//$D_DATE_NAISSANCE = $_REQUEST['model_bidthday'];
$S_GENRE = $_REQUEST['model_gender'];
$S_COUNTRY_CODE = $_REQUEST['model_coutryCode'];
$S_CITY = $_REQUEST['model_city'];
$S_ZIP = $_REQUEST['model_zipcode'];
$S_ADRESS = $_REQUEST['adress'];
$S_NATIONALITY = $_REQUEST['model_nationality'];
$S_ETHNIE = $_REQUEST['model_ethnie'];
$S_CARD_ID_FRONT = $_REQUEST['S_CARD_ID_FRONT'];
$S_CARD_ID_BACK = $_REQUEST['S_CARD_ID_BACK'];
$S_IMAGE_CAM = $_POST['S_IMAGE_CAM'];
$sql = $sqlserver->prepare("UPDATE t_model SET FK_STUDIO=? , S_FIRSTNAME=? , S_LASTNAME=? , D_DATE_NAISSANCE=?, S_GENRE=? ,S_COUNTRY_CODE=?, S_CITY=? , S_ZIP=? , S_ADRESS=? , S_NATIONALITY=? , S_ETHNIE=? , S_CARD_ID_FRONT=?, S_CARD_ID_BACK=? , S_IMAGE_CAM=? where PK_MODEL=? and K_KEY_MODEL=?");
$r = $sql->execute(array($FK_STUDIO,$S_FIRSTNAME,$S_LASTNAME,$D_DATE_NAISSANCE,$S_GENRE,$S_COUNTRY_CODE,$S_CITY,$S_ZIP,$S_ADRESS, $S_NATIONALITY, $S_ETHNIE, $S_CARD_ID_FRONT, $S_CARD_ID_BACK,$S_IMAGE_CAM, $PK_MODEL,$K_KEY_MODEL)) or die(print_r($sql->errorInfo()));
$sql->closeCursor();
echo 1;
}
?>
In case you're using an sql server (as the name of the variable suggests) you can use ISNULL(expr1,expr2). In case the parameter in the query is null (expr1) then use the current value of that row (expr2).
// using php7's Null coalescing operator
// for php < 7 use: isset($_REQUEST['key']) ? $_REQUEST['key'] : replacement
$PK_MODEL = $_REQUEST['PK_MODEL'] ?? $_SESSION['PK_MODEL'];
$K_KEY_MODEL = $_REQUEST['K_KEY_MODEL'] ?? $_SESSION['K_KEY_MODEL'];
$FK_STUDIO = $_REQUEST['model_studio'] ?? NULL;
$S_FIRSTNAME = $_REQUEST['model_firstname'] ?? NULL;
$S_LASTNAME = $_REQUEST['model_lastname'] ?? NULL;
$S_GENRE = $_REQUEST['model_gender'] ?? NULL;
$S_COUNTRY_CODE = $_REQUEST['model_coutryCode'] ?? NULL;
$S_CITY = $_REQUEST['model_city'] ?? NULL;
$S_ZIP = $_REQUEST['model_zipcode'] ?? NULL;
$S_ADRESS = $_REQUEST['adress'] ?? NULL;
$S_NATIONALITY = $_REQUEST['model_nationality'] ?? NULL;
$S_ETHNIE = $_REQUEST['model_ethnie'] ?? NULL;
$S_CARD_ID_FRONT = $_REQUEST['S_CARD_ID_FRONT'] ?? NULL;
$S_CARD_ID_BACK = $_REQUEST['S_CARD_ID_BACK'] ?? NULL;
$S_IMAGE_CAM = $_POST['S_IMAGE_CAM'] ?? NULL;
$sql = $sqlserver->prepare("
UPDATE
t_model
SET
FK_STUDIO=IsNull(?,FK_STUDIO),
S_FIRSTNAME=IsNull(?,S_FIRSTNAME),
S_LASTNAME=IsNull(?,S_LASTNAME),
D_DATE_NAISSANCE=IsNull(?,D_DATE_NAISSANCE),
S_GENRE=IsNull(?,S_GENRE),
S_COUNTRY_CODE=IsNull(?,S_COUNTRY_CODE),
S_CITY=IsNull(?,S_CITY),
S_ZIP=IsNull(?,S_ZIP),
S_ADRESS=IsNull(?,S_ADRESS),
S_NATIONALITY=IsNull(?,S_NATIONALITY),
S_ETHNIE=IsNull(?,S_ETHNIE),
S_CARD_ID_FRONT=IsNull(?,S_CARD_ID_FRONT),
S_CARD_ID_BACK=IsNull(?,S_CARD_ID_BACK),
S_IMAGE_CAM=IsNull(?,S_IMAGE_CAM)
WHERE
PK_MODEL=?
AND K_KEY_MODEL=?
");
In case you're using MySQL, the same can be done via IFNULL.
Either way it's cruical that the server really gets a NULL-value (not only an empty string but NULL).
You could try to use dynamically created queries.
You'll have to have the input fields' names the same as your columns in the table that you're going to update.
Then pass all the variables to the superglobal $_POST this way you won't update anything that is empty.
In your update function loop through $_POST like this:
$sql = 'UPDATE t_model SET ';
foreach($_POST as $key=>$value){
if($value !== '' && !empty($value)) //checking if you don't have an empty value and you can add more exceptions here by doing '&& $key !== 'exception' or '&& $value !== "exception"'
$sql .= $key.' = :'.$key.', ';
}
$sql = rtrim($sql, ",")." where PK_MODEL=:PK_MODEL and K_KEY_MODEL=:K_KEY_MODEL ";
$query = $sqlserver->prepare($sql);
foreach($_POST as $key=>$value){
if($value !== '' && !empty($value)){
$query->bindValue(':'.$key, $value);
}
}
$query->execute();
$query->closeCursor();
echo 1;
This should work, I've been using the same structure for my dynamic admin panel and it works like a charm.
NOTE: I've changed some variable names to make it a little bit easier to read for potential other users
IMPORTANT EDIT: As suggested by #SZenC this could be vulnerable to SQL injection. This would be by adding input fields manually in the source code of the form.
This can all be prevented by adding an additional check in the loops like this:
$allowed_cols = array('col1', 'col2', 'col3');
if($value !== '' && !empty($value) && in_array($key, $allowed_cols)){
So the fix for this potential SQL injection is to edit the checks in the for loops

PHP Pagination values errors

I get errors:
Notice: Undefined index: p, page, srt and where
// set default pagenation values
if(!$_GET['p']) $_GET['p'] = $conf['perpage']; // default number of entries per page
if(!$_GET['page']) $_GET['page'] = 1; // current page
if(!$_GET['srt']) $_GET['srt'] = $conf['srt']; // default sort order
$start = ($_GET['page'] - 1) * $_GET['p']; // start row for query
// get total number of entries for pagenation
$result = mysql_query("SELECT COUNT(*) FROM articals $where", $link);
$total = mysql_fetch_array($result); $total = $total[0]; // total number of listings
$pages = ceil($total / $_GET['p']); // number of pages
And also on:
Notice: Undefined index: category, description,model,cond,location,photos,featured and where
$_GET = safe_data($_GET, 'query');
if($_GET['category']) $where .= "AND (category='$_GET[category]' OR category2='$_GET[category]') ";
if($_GET['description']) $where .= "AND description LIKE '%$_GET[description]%' ";
if($_GET['model']) $where .= "AND model LIKE '%$_GET[model]%' ";
if($_GET['cond']) $where .= "AND cond='$_GET[cond]' ";
if($_GET['location']) $where .= "AND location='$_GET[location]' ";
if($_GET['photos']) $where .= "AND images>'0' ";
if($_GET['featured']) $where .= "AND featured='1' ";
// finialize query string if necessary
if(substr($where, 0, 3) == 'AND') {
$where = ltrim($where, 'AND');
$where = 'WHERE'.$where;
}
// do not show hidden and expired listings
$display = "hide!='1' AND (expire>'".time()."' OR expire='' OR expire='0') AND (user_expire>'".time()."' OR user_expire='' OR user_expire='0')";
$display = "hide!='1'";
if(!$where) $where = "WHERE ".$display;
else $where .= "AND ".$display;
Any Help please?
You have to wrap isset() Around every get request to get rid of the notice.
The Notice is shown because their is no value.
You can use it like this: if(isset($_GET['p']))
This code might help you, it wraps the http php response:
class Input {
public static function Post($item,$default=null){
//If the value was posted, then return that value, else return the $default value.
return isset($_POST[$item]) ? $_POST[$item] : $default;
}
public static function Get($item,$default=null){
return isset($_GET[$item]) ? $_GET[$item] : $default;
}
public static function Cookie($item,$default=null){
return isset($_COOKIE[$item]) ? $_COOKIE[$item] : $default;
}
public static function Param($item,$default=null){
return self::Post($item) ?: self::Get($item) ?: self::Cookie($item) ?: $default;
}
}
usage:
Input::Get('p',$conf['perpage']); // First argument is the index, second is default if not set.
in your example:
$p = Input::Get('p',$conf['perpage']);
$page = Input::Get('page',1);
$srt= Input::Get('page',$conf['srt']);
$start = ($page - 1) *$p; // start row for query
In your URL, do you have parameters such as http://www.yoursite.com/yourpage.php?p=XXX&page=YYYY&srt=ZZZZ ?
If those parameters are optionnal, use:
if (!isset($_GET["p"])) $_GET["p"] = $conf["perpage"];
But actually, a better practice is to not assign $_GET by yourself. Instead, set a variable and use it later instead of using $_GET content:
$p = (isset($_GET["p"])?$_GET["p"]:$conf["perpage"]);
If you are doing a redirection in your htaccess, make sure to forward the GET parameters using [QSA].

Troubleshooting "Undefined offset" error

It's show following error:
Notice: Undefined offset: 1 in C:\xampp\htdocs\evantechbd\secure\content\feature_link_process.php on line 28.
Why it's show the error...? Can anyone tell me... Here is the code:
$row = explode("|", $_POST['coun_name']);
$coun_id = $row[1]; // cat_id
$coun_name = $row[0];
if(isset($coun)){
$errors = array();
if(empty($coun))
$errors[] = 'Country Name require<br>';
}
$row = explode("|", $_POST['coun_name']);
$coun_id = $row[1]; // cat_id
$coun_name = $row[0];
if $_POST['coun_name] has no | than $row[1] is not defined.
You will probably want to do something like this, instead:
$errors = array();
if( empty($_POST['coun_name']) )
{
$errors[] = 'Country Name required.';
}
elseif( strpos($_POST['coun_name'], '|') === false )
{
$errors[] = 'Country Name invalid.';
}
else
{
list($coun_name, $coun_id) = explode("|", $_POST['coun_name'], 2);
}
The first condition checks to make sure the user submitted a value for $_POST['coun_name']. The second condition checks to make sure that the value contains a '|' character.
If both conditions are met, $coun_name and $coun_id are populated by explode()'ing $_POST['coun_name'] as normal (I dropped in a call to list() for brevity).

Categories