How to fix warning in php : Warning: Undefined variable $nameError in C:\xampp\htdocs\mysql\insert.php on line 84

As a beginner in PHP, I was trying to learn how PHP runs along with MySQL. So I was practicing how to insert data into a database using a form. So far this is what I did.

<?php error_reporting(E_ALL ^ E_WARNING);   define( "TITLE", "GET &amp; POST" );  if( isset( $  _POST["post_submit"] ) ) {          // build a function that validates data     function validateFormData( $  formData ) {         $  formData = trim( stripslashes( htmlspecialchars( $  formData ) ) );         return $  formData;     }          // check to see if inputs are empty     // create variables with form data     // wrap the data with our function          if( !$  _POST["post_name"] ) {         $  nameError = "Please enter your name <br>";     } else {         $  name = validateFormData( $  _POST["post_name"] );     }          if( !$  _POST["post_email"] ) {         $  emailError = "Please enter your email <br>";     } else {         $  email = validateFormData( $  _POST["post_email"] );     }      } 

?>

<head>          <meta charset="utf-8">     <meta http-equiv="X-UA-Compatible" content="IE=edge">     <meta name="viewport" content="width=device-width, initial-scale=1">      <title><?php echo TITLE; ?></title>      <!-- Bootstrap CSS -->     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">      <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->     <!--[if lt IE 9]>         <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>         <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>     <![endif]--> </head>  <body>     <div class="container">         <h1><?php echo TITLE; ?></h1>                  <h4>Submitted via $  _GET</h4>         <form action="form_get.php" method="get">             <input type="text" placeholder="Name" name="name">             <input type="text" placeholder="Email" name="email">             <input type="submit" name="form_submit">         </form>                  <hr>                  <h4>Submitted via $  _POST</h4>         <form action="form_post.php" method="post">             <input type="text" placeholder="Name" name="post_name">             <input type="text" placeholder="Email" name="post_email">             <input type="submit" name="post_submit">         </form>          <hr>          <h4>Submitted to current page</h4>                  <p class="text-danger">* Required fields</p>                  <form action="<?php echo htmlspecialchars($  _SERVER['PHP_SELF']); ?>" method="post">                          <small class="text-danger">* <?php echo $  nameError; ?></small>             <input type="text" placeholder="Name" name="post_name"><br><br>                          <small class="text-danger">* <?php echo $  emailError; ?></small>             <input type="text" placeholder="Email" name="post_email"><br><br>             <input type="submit" name="post_submit">         </form>                  <?php                          if( isset($  _POST["post_submit"]) ) {                 echo "<h4>Your info</h4>";                 echo "$  name <br> $  email <br>";             }          ?>                                </div>          <!-- jQuery -->     <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>          <!-- Bootstrap JS -->     <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </body> 

When I wasn’t using error_reporting(E_ALL ^ E_WARNING) it kept showing this warning message [ Warning: Undefined variable $ nameError in C:\xampp\htdocs\mysql\insert.php on line 84 ].

Can anyone help me why it’s showing that there is an undefined variable? Cause I think I defined this variable at the top portion of PHP code.

And is it a good practice to use the error_reporting() function to suppress the warning message from showing?

Is it possible to not differentiate through an undefined variable?

Suppose I have some $ \lambda$ that is a function of $ x$ , and I don’t know exactly what it is yet.

Then, doing the following differentiation D[lamb, x] gives zero. But what I really want is to not have Mathematica evaluate the expression, i.e., just leave it as it is until I know $ \lambda$ later.

Is there a way to achieve this? Thanks!

Fatal error and use of undefined constant in child theme unless I redefine it

Child theme functions.php:

// Init. require_once( WPBF_CHILD_THEME_DIR . '/inc/init-child.php'); 

In the parent theme functions.php, the constant is defined:

define( 'WPBF_CHILD_THEME_DIR', get_stylesheet_directory() ); 

If I include the same constant definition in the child theme like the above, then the require_once works and /inc/init-child.php file is loaded.

However I get a notice stating that the constant is already defined in the parent theme’s functions.php (correct!).

But if I remove this from the child theme’s functions.php, then I get the following:-

Warning: Use of undefined constant WPBF_CHILD_THEME_DIR - assumed 'WPBF_CHILD_THEME_DIR' (this will throw an Error in a future version of PHP) in /var/www/vhosts/xxx/subdomains/xxx/httpdocs/wp-content/themes/page-builder-framework-child/functions.php on line 42  Warning: require_once(WPBF_CHILD_THEME_DIR/inc/init-child.php): failed to open stream: No such file or directory in /var/www/vhosts/xxx/subdomains/xxx/httpdocs/wp-content/themes/page-builder-framework-child/functions.php on line 42  Fatal error: require_once(): Failed opening required 'WPBF_CHILD_THEME_DIR/inc/init-child.php' (include_path='.:/opt/plesk/php/7.3/share/pear') in /var/www/vhosts/xxx/subdomains/xxx/httpdocs/wp-content/themes/page-builder-framework-child/functions.php on line 42 

So why can I only load the file via the child theme if I redefine the constant even though it is going to show me a notice to state it is already defined…?

The same constant is already in use in the very same child theme functions.php file further up as well like:

// Textdomain. load_child_theme_textdomain( 'page-builder-framework-child', WPBF_CHILD_THEME_DIR . '/languages' ); 

I am assuming there should be a correct way to load the file needed without having to repeat constant definitions?

WP Ajax Function Always Returning undefined

What is the deal here?

JS FUNCTION ‘custom.js’

function validate() {     var email = jQuery("#billingemail").val();      if (isValidEmailAddress(email)) {         jQuery.ajax({             type: 'POST',             url: ajaxurl,             data: {"action": "custome_ajax_email_check", "guestemail": email },             success: function(data){                 data = jQuery.parseJSON(data);                 if(data.result) {                     alert('Email Exists');                     return false;                 } else {                     alert('Email Does Exists');                     return true;                 }             }         });     } else {         return false;     } } 

JS ON CLICK ‘custom.js’

 $  ('#mwb_logincoupon').on('click', '#validateguestemail', function (e) {         e.preventDefault();         validateemail = validate();          

PHP AJAX

add_action( 'wp_ajax_custome_ajax_email_check', 'custome_ajax_email_check' ); add_action('wp_ajax_nopriv_custome_ajax_email_check', 'custome_ajax_email_check');  function custome_ajax_email_check(){     $  email = $  _POST['guestemail'];      // do check     if ( email_exists($  email) ) {         $  response->result = true;     }     else {         $  response->result = false;     }      echo( json_encode( $  response));     wp_die(); } 

debugging the script the JS code goes into the success function, so far as even triggering off the alert('Email Exists').. but the return statement in the functon is never retrieved thus making validateemail always return undefined. Why?

error (Undefined index) and (Cannot modify header information – headers already)

Error:

Notice: Undefined index: link_type in /home/golchind/public_html/wp-content/themes/golchindl/functions.php on line 40

Notice: Trying to get property of non-object in /home/golchind/public_html/wp-content/themes/golchindl/functions.php on line 58

Warning: Cannot modify header information – headers already sent by (output started at /home/golchind/public_html/wp-content/themes/golchindl/functions.php:40) in /home/golchind/public_html/wp-admin/admin-header.php on line 9

help :

line 40

$ type = $ _POST[‘link_type’];

line 58

update_post_meta($ post->ID,”_oscar_data”,json_encode(array(“episodes”=>$ episodes,”links”=>$ links,”type”=>$ type), JSON_UNESCAPED_UNICODE));

function oscar_meta_box_js(){     wp_enqueue_style( 'oscar_box_style',get_bloginfo('template_url')."/css/admin_meta_box.css");     wp_enqueue_script( 'oscar_box', get_bloginfo('template_url'). '/js/meta_boxes.js', array('jquery'),'1.0',true); } add_action( 'admin_enqueue_scripts', 'oscar_meta_box_js');   function oscar_meta_save(){     global $  post,$  meta_args,$  meta_dls;     $  type = $  _POST['link_type'];     $  episodes = array();     $  links = array();     if($  type == "serial"){         for($  i=0;$  i<count($  _POST['ep_name']);$  i++){             $  episodes[] = array("name"=>$  _POST['ep_name'][$  i],"quality"=>$  _POST['ep_quality'][$  i],"medium_size"=>$  _POST['ep_med'][$  i]);         }         for($  i=0;$  i<count($  _POST['link']);$  i++){             $  links[] = array("name"=>$  _POST['name'][$  i],"link"=>$  _POST['link'][$  i],"subtitle"=>$  _POST['subtitle'][$  i],"screenshot"=>$  _POST['screenshot'][$  i],"episode"=>$  _POST['episode'][$  i]);         }     } else if($  type == "movie") {         for($  i=0;$  i<count($  _POST['movie_title']);$  i++){             $  episodes[] = array("name"=>$  _POST['movie_title'][$  i]);         }         for($  i=0;$  i<count($  _POST['mlink']);$  i++){             $  links[] = array("name"=>$  _POST['mname'][$  i],"link"=>$  _POST['mlink'][$  i],"subtitle"=>$  _POST['msubtitle'][$  i],"screenshot"=>$  _POST['mscreenshot'][$  i],"episode"=>$  _POST['mtitle'][$  i]);         }     }     update_post_meta($  post->ID,"_oscar_data",json_encode(array("episodes"=>$  episodes,"links"=>$  links,"type"=>$  type), JSON_UNESCAPED_UNICODE)); }        function oscar_download(){     global $  post;     ?> <script> var $   = jQuery; $  (function(){     var data = '<?=get_post_meta($  post->ID,"_oscar_data",true);?>';     if(data != ""){         data = JSON.parse(data);         var type = data['type'];         data['episodes'].forEach(function(e){             if(type == "serial")                 add_ep(e['name'],e['quality'],e['medium_size'])             else                 add_title(e['name']);         });         data['links'].forEach(function(e){             if(type == "serial")                 add_link(e['name'],e['link'],e['subtitle'],e['screenshot'],e['episode'])             else                 add_mlink(e['name'],e['link'],e['subtitle'],e['screenshot'],e['episode'])         });         if(data['type']){           $  ("#link_type").val(data['type']);     }     }     normalize_links()     normalize_mlinks() }); </script> <?php if ('series' == get_post_type()) { ?> <div id="serial" class="content">     <div class="side_inp_keeper">         <input id="title_serial" type="text" placeholder="عنوان فصل">         <input id="quality_serial" type="text" placeholder="کیفیت">         <input id="med_serial" type="text" placeholder="میانگین حجم هم قسمت">         <button id="add_ep" class="button">افزودن</button>     </div>     <div id="episodes">      </div>     <hr>     <div class="links" style="display:none;">             <div class="side_inp_keeper">                 <select id="ep"></select>                 <input type="text" id="name" placeholder="عنوان لینک">                 <input type="text" id="link" placeholder="لینک دانلود">                 <input type="text" id="subtitle" placeholder="زیر نویس">                 <input type="text" id="screenshot" placeholder="نمونه کیفیت">                 <button id="add_link" class="button">افزودن</button>             </div>             <div id="links">              </div>         </div> </div> <?php } else if ('movies' == get_post_type()) { ?> <div id="movie" class="content">     <div class="side_inp_keeper">         <input type="text" name="movie_title" id="movie_title" placeholder="عنوان (مثال : زبان اصلی)"><button id="add_link_title" class="button">افزودن</button>     </div>     <div id="titles">      </div>     <hr>     <div class="mlinks">         <div class="side_inp_keeper">                     <select id="titl"></select>                     <input type="text" id="mname" placeholder="عنوان لینک">                     <input type="text" id="mlink" placeholder="لینک دانلود">                     <input type="text" id="msubtitle" placeholder="زیر نویس">                     <input type="text" id="mscreenshot" placeholder="نمونه کیفیت">                     <button id="add_mlink" class="button">افزودن</button>         </div>         <div id="mlinks">          </div>     </div> </div> <?php } ?> <input type="hidden" name="link_type" id="link_type" value="serial">     <?php }    function oscar_meta_boxes() {     add_meta_box( 'oscar_download',"باکس دانلود", 'oscar_download', array('movies', 'series'), 'normal', 'high' ); } add_action("save_post","oscar_meta_save"); add_action( 'add_meta_boxes', 'oscar_meta_boxes' ); 

Conditionally returning a constant if function returns Undefined

Often times functions might return Undefined in Mathematica, e.g. when the Volume@RegionIntersection is called for 2 objects which have no overlapping volume. A simple If statement checking if the return has been indeed Undefined does not seem to work. For example, a=Undefined; If[a == Undefined, Print["yes"]] ends up printing the command itself.

  • How can we check if a variable (or a function return) such as a has been assigned as Undefined and assign a different value to it in that case?

SPServices.SPAutocomplete cannot read property ‘find’ of undefined

I have created a SharePoint page and inserted text box using content editor web part with title of FilterTextBox

<input type="text" title="FilterTextBox"/> 

and I have inserted below script using Script Editor web part

<script language="javascript" type="text/javascript">     $  (document).ready(function() {         $  ().SPServices.SPAutocomplete({              sourceList: "Country",             sourceColumn: "Title",             columnName: "FilterTextBox",             ignoreCase: true,             numChars: 3,             slideDownSpeed: 1000,             debug: true         });     }); </script> 

but I get the following error when page load

Uncaught TypeError: Cannot read property ‘find’ of undefined

what might be wrong with my code ? thanks .

Call to undefined relationship [sub_category] on model [App\Sub_Category]

Estoy intentado hacer una llamada por get para obtener todas mis “subcategorias”, me surge el error: Call to undefined relationship [sub_category] on model [App\Sub_Category].

Estoy en duda ya que no se si el error es 100% de la base de datos o de la consulta.

Por favor si alguien pudiera ayudarme lo agradecería

Clase

public function store(Request $  request) {     // Recoger los datos     $  json = $  request->input('json', null);     $  params = json_decode($  json);     $  params_array = json_decode($  json, true);     if (!empty($  params_array)) {          $  jwtAuth = new JwtAuth();         $  token = $  request->header('Authorization', null);         $  user = $  jwtAuth->checkToken($  token, true);          // Validar los datos         $  validate = \Validator::make($  params_array, [                     'name' => 'required'         ]);         //Guardar los datos         if ($  validate->fails()) {             $  data = [                 'code' => 400,                 'status' => 'error',                 'message' => 'Envia el nombre'             ];         } else {             $  sub_category = new Sub_Category();             $  sub_category->name = $  params_array['name'];             $  sub_category->category_id = $  params->category_id;             $  sub_category->save();              $  data = [                 'code' => 200,                 'status' => 'success',                 'sub_category' => $  sub_category             ];         }     } else {         $  data = [             'code' => 400,             'status' => 'error',             'mensage' => 'No has enviado ninguna sub_categoria'         ];     }      // Devolcer Sub_Categoria     return response()->json($  data, $  data['code']); } 

Modelo

class Sub_Category extends Model {     // Referencia a la base de datos     protected $  table = 'sub_categories';      // Unos a muchos     public function give_posts(){         return $  this->hasMany('App\Post');     }      // Relación Muchos a uno     public function category(){         return $  this->belongsTo('App\Category', 'category_id');     } 

Base de datos

El objetivo es poder obtener cualquier dato para poder modificar lo posteriormente, aquí dejo las 2 talabas que se tiene que relacionar.

CREATE TABLE categories( id                  int(255) auto_increment not null, name                varchar(255)  NOT NULL, created_at           datetime DEFAULT NULL, updated_at           datetime DEFAULT NULL, CONSTRAINT  pk_users PRIMARY KEY(id) )ENGINE=InnoDb;  CREATE TABLE sub_categories( id                  int(255) auto_increment not null, name                varchar(50)  NOT NULL, category_id         int(255) NOT NULL, created_at           datetime DEFAULT NULL, updated_at           datetime DEFAULT NULL, CONSTRAINT  pk_users PRIMARY KEY(id), CONSTRAINT  fk_post_category FOREIGN KEY(category_id) REFERENCES categories(id) )ENGINE=InnoDb; 

SPHttpClient undefined error: Using React JS to add item in SharePoint list

I’m trying to add an item in SharePoint Online list using SPFx solution where I’m using React JS to perform the action.

Below is the copied code, when debugging it says that:

“VM242:1 Uncaught TypeError: Cannot read property ‘spHttpClient’ of undefined”

Please have a look at the below code and let me know if I’m missing out on any thing.

I’m just trying to add an item in list called test.

function _alertClicked(): void {   alert('Clicked');   //Custom   const body: string = JSON.stringify({     'Title': `Item $  {new Date()}`   });   this.context.SPHttpClient.post(`$  {this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('test')/items`,     SPHttpClient.configurations.v1,     {       headers: {         'Accept': 'application/json;odata=nometadata',         'Content-type': 'application/json;odata=nometadata',         'odata-version': ''       },       body: body     })     .then((Response: SPHttpClientResponse): Promise<IListItem> => {       return Response.json();     })     .then((item: IListItem): void => {       this.updateStatus(`Item 'Test' Successfully Created`);     }, (error: any): void => {       this.updateStatus('Error' + error);     });  } 

Note: I’m using fabric controls on the page.

No puedo acceder a las propiedades de un Objeto da “UNDEFINED” como resultado el console.log(objeto.propiedad)

Al realizar una consulta utilizando Express y Mongoose, y utilizando console.log para revisar el resultado del siguiente codigo:

const consults = await Consult.find({ user: req.user.id }).populate('patient', 'patient_name patient_phone');      console.log(typeof(consults));     console.log(consults);     console.log(consults._id);     console.log(consults.c_motive);     console.log(consults.c_amount);     console.log(consults.c_cDate); 

Obtengo el siguiente resultado de los console.log()

console.log(typeof(consults)); Resultado//

object 

console.log(consults); Resultado//

[ { _id: 5d9f483c1cb2710408aeaf20,     c_note:      'Se presento con un dolor de estomago recurrente, y diarrea.',     c_prescription: 'Tinidazol',     c_motive: 'Dolor de estomago recurrente',     c_amount: 200,     c_recurrent: 'New',     c_cDate: 2019-10-10T15:03:24.144Z,     user: 5d9574bcc31c0e10c83fcb3b,     patient:      { _id: 5d9f47811cb2710408aeaf1f,        patient_name: 'Miguel Marroquin',        patient_phone: '40009374' },     c_status: 'PAID',     __v: 0 } ] 

console.log(consults._id); Resultado//

undefined 

console.log(consults.c_motive); Resultado//

undefined 

console.log(consults.c_amount); Resultado//

undefined 

console.log(consults.c_cDate); Resultado//

 undefined 

Como logro acceder a las propiedades del objeto para trabajar con ellas?