Php object undefined index

Notice: Undefined index: mail in \var\www\object\ on line 38

С помощью этого метода я вытаскиваю mail для сравнения с тем что передал клиент.
Со стороны клиента я прописываю user@mail.ru в таблице user есть такой mail user@mail.ru.

Но PHP мне выдает и делает замечание что нету такого массива.


Notice: Undefined index: mail in \var\www\object\ on line 38

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Он ругается на $result['mail']. public function vivod() { if($this->passVal() == true) { if(!empty($this->error) && is_array($this->error)) { foreach($this->error as $key => $value) { $error_user = [$key => $value]; } echo json_encode($error_user); } else { require_once 'connect.php'; $connect = new Connect(); $result = $connect->select("SELECT mail FROM user"); if($result['mail'] == $this->mail) { echo '+'; } else { echo '-'; } } } else { $error_pass = ["errorpass" => '1']; echo json_encode($errorpass); } }

Notice: Undefined index: token in /var/www/data/www/au3d.ru/admin/controller/extension/module/buyoneclick.php
Прошу помощи! При переходе в админке Опенкарта 3.0.2 в Модулях при нажатии Редактировать всплывает.

Читайте также:  Php операции со строки

Notice: Undefined index: buttonstyle in C:\wamp\www\steamauth\steamauth.php on line 19
Помогите пожалуйста решить данную ошибку Notice: Undefined index: buttonstyle in.

Notice: Undefined index: code in Y:\home\ocStore\www\catalog\view\theme\default\template\chec kout\payment_data.tpl on line 6
Вылезает вот такая ошибка в форме оформления заказа. не могу понять что не так с синтаксисом. .

Эксперт PHP

ЦитатаСообщение от maxoun Посмотреть сообщение

Всё правильно, метод select ведь возвращает Вам массив с числовыми индексами. Вы же на 5 строке сами формируете такой массив, а потом, на 7, возвращаете.

ЦитатаСообщение от Para bellum Посмотреть сообщение

$arr = ["id" => $row['id'],"mail"=>$row['mail'],"name"=>$row['name'],"pass"=>$row['pass']];

Эксперт PHP

SELECT 1 FROM USER WHERE mail = :mail

Вы же проводите проверку на существование?

А далее смотреть, пришли данные или нет (хотя бы через то же num_rows ). Если пришли — email есть в таблице.

ЦитатаСообщение от Para bellum Посмотреть сообщение

А далее смотреть, пришли данные или нет (хотя бы через то же num_rows). Если пришли — email есть в таблице.

Я вас понял, и сейчас исправлю ошибку, вместо 1 , но я не понял одно.
Вы указали выбрать 1 с user где mail = :mail

Объясните пожалуйста, синтаксис :mail .

И еще если не сложно объясните как вытаскивать ассоциативный массив для других скриптов

Эксперт PHP

ЦитатаСообщение от maxoun Посмотреть сообщение

Это placeholder для PDO, для примера написал. У Вас mysqli-расширение используется.

ЦитатаСообщение от maxoun Посмотреть сообщение

ЦитатаСообщение от maxoun Посмотреть сообщение

Вопрос не понял. Как это, для других?

И, кстати, та while в методе select не нужна. Есть fetch_all.

ЦитатаСообщение от Para bellum Посмотреть сообщение

Все ровно пишет что ключ в массиве не найден.

На счет вывода и сравнения mail я уже решил спасибо.
Простыми словами проблема остается именно в массиве.

Я как бы все сделал правильно, при true хотел в session присвоить идентификатор пользователя, но не могу потому что пишет что нет такого ключа.
когда вывожу через print_r fetch_all показывает числовой идентификатор странно.

вот скрипт P.S посмотрите пожалуйста, правильно ли я построил ООП для этого метода

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
public function vivod() { if($this->passVal() == true) { if(!empty($this->error) && is_array($this->error)) { foreach($this->error as $key => $value) { $error_user = [$key => $value]; } echo json_encode($error_user); } else { return true; } } else { $error_pass = ["errorpass" => '1']; echo json_encode($errorpass); } } public function vivod_user() { if($this->vivod() == true) { require_once 'connect.php'; $connect = new Connect(); $sql = "SELECT id FROM user WHERE mail = '".$this->mail."' "; $result = $connect->select($sql); if($result == true) { $error_mail = ["errormail" => "1"]; echo json_encode($error_mail); } else { $insert_user = $connect->query("INSERT INTO user (name, mail, pass) VALUES (. )", $this->name, $this->mail, $this->pass); if($insert_user == true) { $res_id = $connect->select($sql); if($res_id == true) { require 'session.php'; $session = new Session(); $session->startSession("user", $res_id['id']); echo (isset($session->get("user")) ? header('location, mypage.php?id='.$session->get("user")) : " "; } } } //else } //true }
public function select($sql) { $res = $this->link->query($sql); if($res->num_rows > 0) { return $res->fetch_all(); } }

Источник

What is an Undefined Index PHP Error? How to Fix It?

Undefined Index PHP Error

PHP is a widely used scripting language that is mainly used for web development purposes. It is a scripting language and finds application in automating tasks that would otherwise be impossible to implement with just human intervention. Being a server-side language, it primarily takes care of things at the server’s end. Launched in 1995 for public use, it has remained a popular choice among web developers since then.

Programming is a tricky business. It is pretty normal to stumble upon errors and warnings while making a program. The same happens a lot to PHP developers, like when they face an Undefined index in PHP. However, such errors are not hard to deal with with a little bit of knowledge and guidance.

Basics to Advanced — Learn It All!

What Is an Undefined Index PHP Error?

Websites often use forms to collect data from visitors. PHP uses $GET and $POST methods for such data collection. This data is collected and saved in variables that are used by the website to work and serve the visitor further. Many a time, some fields are left blank by the user. But the website tries to refer to these fields for proceeding further. That means the PHP code tries to get the value of the field that no one has defined and thus does not exist. Quite expectedly, it does not work and raises a notice called Undefined Index in PHP.

Code:

Result:

Undefined_Index_Php_1

You can fix it using the isset() function, which we will discuss further in the upcoming sections.

Undefined Index is a notice in PHP, and it is a choice of the developer to either ignore it or fix it.

How to Ignore PHP Notice: Undefined Index?

Undefined Index in PHP is a Notice generated by the language. The simplest way to ignore such a notice is to ask PHP to stop generating such notices. You can either add a small line of code at the top of the PHP page or edit the field error_reporting in the php.ini file.

1. Adding Code at the Top of the Page

A simple way to ask PHP to disable reporting of notices is to put a line of code at the beginning of the PHP page.

Code:

Or you can add the following code which stops all the error reporting,

2. Changes in php.ini

Php.ini is a configuration file and is essential for all the programs running on PHP. Open this file and find the field error_reporting. The easiest way is to use the ctrl + F shortcut key. By default, error reporting is set to E_ALL. That means all errors are reported. Change this to E_ALL & ~E_NOTICE. It means all errors except for the notices will now be reported.

Learn 15+ In-Demand Tools and Skills!

How to Fix the PHP Notice: Undefined Index?

We know the cause of the error. It occurs when we use $_GET and $_POST methods to get input, but we reference it even when it has not been set. The solution simply is to check if it has been set before referencing.

We can use the isset() function, which checks if the variable ‘is set’ or not before referencing to them. Isset() function returns True or False depending on it.

Undefined Index in PHP $_GET

When using the $_GET method, the following code might show the notice Undefined index in PHP:

Code:

As we have not set any of these variables, this code shows the Undefined Index notice.

Change it to the following code to fix this issue:

Code:

$name = » John — This is our default name»;

$age = «10 — This is our default age. Let’s leave the grade blank.»;

Result:

undefined_Index_Php_2.

Here’s How to Land a Top Software Developer Job

We can use a single line of code like this instead.

Code:

$name = isset($_GET[‘name’]) ? $_GET[‘name’]: “John- This is our default name”;

This approach also achieves the intended goal.

Result:

undefined_Index_Php_3.

Notice: Undefined Variable

PHP shows this notice when we try to use a variable even before defining it.

Code:

Result:

undefined_Index_Php_4

It can be solved either by declaring a variable global and then using isset() to see if it is set or not. It can be echoed only if it has been set. Alternatively, we can use isset(X) ? Y to set a default.

Code:

Result:

undefined_Index_Php_5.

We can set it after the isset() check like this.

Code:

$name= isset($name) ? $name:»Default»;

undefined_Index_Php_6.

Designing a Social Media App Like Instagram

It shows Undefined Offset Notice in PHP when we are referring to a key in an array that has not been set for the array.

Code:

$nameArray = array(1=>’one’, 2=>’two’, 4=>’four’);

Result:

It might show an undefined array key warning for some. It means the same thing that you are trying to access an undefined array key.

undefined_Index_Php_7.

It can be solved similarly like the last two cases by using isset(), arrayexists() or empty() function.

Code:

$nameArray = array(1=>’one’, 2=>’two’, 4=>’four’);

echo ‘
using array_key_exists
‘;

echo array_key_exists(3, $nameArray);

echo array_key_exists(2, $nameArray);

Result:

undefined_Index_Php_8.

Learn right from the basics of JavaScript to advanced concepts of Angular, Spring Boot, Hibernate, JSPs, MVC, etc. Enroll in our PGP in Full Stack Web Development today!

Conclusion

In this article, we learned about the undefined index in PHP. However, it is just one of the many errors, warnings, and notices that a PHP developer has to deal with. If you are looking to make a career out of developing web applications and handling such errors, Simplilearn is offering a Post Graduate Program in Full stack Web Development, in partnership with Caltech CTME. Simplilearn is the world’s #1 online Bootcamp that has helped advance 2,000,000 careers through collaboration with World’s top-ranking universities.

Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:

Name Date Place
Post Graduate Program in Full Stack Web Development Cohort starts on 15th Aug 2023,
Weekend batch
Your City View Details
Post Graduate Program in Full Stack Web Development Cohort starts on 12th Sep 2023,
Weekend batch
Your City View Details
Post Graduate Program in Full Stack Web Development Cohort starts on 10th Oct 2023,
Weekend batch
Your City View Details

About the Author

Ravikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

Post Graduate Program in Full Stack Web Development

Full Stack Web Developer — MEAN Stack

Automation Testing Masters Program

*Lifetime access to high-quality, self-paced e-learning content.

Источник

Оцените статью