Меню

Get id пишет ошибку

In my wordpress website I getting below error

Fatal error: Call to a member function get_id() on boolean in /home/customer/www/ae.testing.com/public_html/wp-content/themes/movedo-child/functions.php on line 33

Previously working fine . but now what exact issue i am not getting. if any one have idea then let me know

function.php as follows:

<?php
function movedo_child_theme_setup() {
}
add_action( 'after_setup_theme', 'movedo_child_theme_setup' );


function display_price_in_variation_option_name( $term ) {
   echo  $product = wc_get_product();
    $id = $product->get_id();
    if ( empty( $term ) || empty( $id ) ) {
        return $term;
    }
    if ( $product->is_type( 'variable' ) ) {
        $product_variations = $product->get_available_variations();
    } else {
        return $term;
    }

    foreach($product_variations as $variation){
        if(count($variation['attributes']) > 1){
            return $term;
        }
        foreach($variation['attributes'] as $key => $slug){
            if("attribute_" == mb_substr( $key, 0, 10 )){
                $taxonomy = mb_substr( $key, 10 ) ;
                $attribute = get_term_by('slug', $slug, $taxonomy);
                if($attribute->name == $term){
                    $term .= " (" . wp_kses( wc_price($variation['display_price']), array()) . ")";
                }
            }
        }
    }
    
    return $term;

}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );

On line «$id = $product->get_id();» I m getting this error.

asked Jun 7, 2021 at 14:34

Praff's user avatar

The issue seems quite simple, you are hooking into ‘after_setup_theme’ which is fired for every single wordpress request. In this context you are supposing you always have a product in the main query context which is not always true.

To simply shut the error wrap $id = $product->get_id(); into an if like this:

if(!empty($product)){    
    $id = $product->get_id();
}
...

But to really make it bullet proof you should ask yourself when you really want to look into wc_get_product to get the current product. I’m assuming you may want that only on the product detail page.
Since you are hooking into ‘after_setup_theme’ conditional tags can be used.

Change your code to bail out as soon as it is not executed in the right page doing something like this:

function display_price_in_variation_option_name( $term ) {
    if (!is_product()){
        return;
    }
    echo  $product = wc_get_product();
    $id = $product->get_id();
    ...

answered Jun 7, 2021 at 15:09

Diego's user avatar

DiegoDiego

1,5761 gold badge13 silver badges26 bronze badges

Wc_get_product is returning false somehow.
Try

global $product; //

Yoda - user264474's user avatar

answered Jun 7, 2021 at 16:07

Drashti Rajpura's user avatar

Хитрый Лис

3 / 3 / 2

Регистрация: 17.04.2014

Сообщений: 37

1

09.06.2014, 13:07. Показов 3968. Ответов 7

Метки нет (Все метки)


Здравствуйте.

Тут такая ситуация.
У меня есть общий шаблон, к которому чаты из бд подсоединяются с помощью ID (чатов много, все они находятся в одной таблице, каждый со своим ID).
Он состоит из 3-ёх частей: index.php (просмотр сообщений и форма их отправки), post.php (записывает сообщение в бд), log.php (в него извлекаются и отображаются сообщения из бд. Подключается к index.php).
В index.php и post.php массив $_GET[‘id’] работает. В log.php нет, и я вообще никак не могу понять, почему. Может, вы знаете?

Вот как всё выглядит в index.php:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div id="chatbox"><?php
    if (isset($_GET['id'])) {
        $chat_id =$_GET['id'];
    } else {
        exit("<script>document.location.href='../404.php';</script>");
    }
    if (!preg_match("|^[d]+$|", $chat_id)) {
        exit("<script>document.location.href='../404.php';</script>");
    }
$result = mysql_query("SELECT * FROM role_chats WHERE id='$chat_id'");
if ($result == false) {
        exit("<script>document.location.href='../404.php';</script>");
}
    if(file_exists("log.php?id=".$chat_id) && filesize("log.php?id=".$chat_id) > 0){
        $handle = fopen("log.php?id=".$chat_id, "r");
        $contents = fread($handle, filesize("log.php?id=".$chat_id));
        fclose($handle);
        
        echo $contents;
    }
    ?>
</div>

А вот log.php:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
<?php
session_start();
include("../../bd.php");
include("../../session.php");
        $chat_id = $_GET['id'];
$result = mysql_query("SELECT * FROM role_chats WHERE id='$chat_id'");
if ($result != true) {
        exit("<script>document.location.href='../404.php';</script>");
}
$myrow = mysql_fetch_assoc($result);
echo $myrow['text'];
?>

Может, потому что log.php вставляется в index.php? По-моему, это полный бред. Но всё может быть.

Помогите, пожалуйста.
Заранее очень благодарен.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Para bellum

Эксперт PHP

5735 / 4122 / 1500

Регистрация: 06.01.2011

Сообщений: 11,251

09.06.2014, 15:52

2

Лучший ответ Сообщение было отмечено Хитрый Лис как решение

Решение

Цитата
Сообщение от Хитрый Лис
Посмотреть сообщение

В index.php и post.php массив $_GET[‘id’] работает. В log.php нет

А как Вы определили, что он не работает? Сделайте:

PHP
1
var_dump($_GET);

Может Вы просто не передаёте туда значение?
P.S. И вот это небезопасно (так как Вы значение вставляете в запрос к БД):

PHP
1
$chat_id = $_GET['id'];

Надо так:

PHP
1
$chat_id = (int) $_GET['id'];

Добавлено через 4 минуты
Хотя… Вы же там регуляркой проверяете ниже, так что оказывается вполне безопасно . Но лучше как я сказал, кода меньше .



1



Хитрый Лис

3 / 3 / 2

Регистрация: 17.04.2014

Сообщений: 37

09.06.2014, 16:33

 [ТС]

3

lyod, определил, что не работает, когда делал в log.php вот так:

PHP
1
2
3
4
5
if (isset($_GET['id'])) {
        $chat_id =$_GET['id'];
    } else {
        exit("<script>document.location.href='../404.php';</script>");
    }

Переносил на ошибку 404.

То есть. Дело не в log.php, а в index.php, т.к. когда я пишу запрос в адресной строке:

…../log.php?id=1

Открывается файл, и в нём прекрасно отображаются сообщения.
А когда я открываю:

…../index.php?id=1

log.php?id=1 внутри него не отображается, а отображается просто log.php, из-за чего и срабатывает скрипт выше. Значит, действительно, значение не передаётся. Но почему? Вроде всё прописал…

PHP
1
2
3
4
5
6
7
if(file_exists("log.php?id=".$chat_id) && filesize("log.php?id=".$chat_id) > 0){
        $handle = fopen("log.php?id=".$chat_id, "r");
        $contents = fread($handle, filesize("log.php?id=".$chat_id));
        fclose($handle);
        
        echo $contents;
    }



0



Para bellum

Эксперт PHP

5735 / 4122 / 1500

Регистрация: 06.01.2011

Сообщений: 11,251

09.06.2014, 16:53

4

Лучший ответ Сообщение было отмечено Хитрый Лис как решение

Решение

А, то есть Вы хотите передать параметр, открывая файл log.php с помощью fopen? Я только заметил… Так сделать не получится . Если только так как-то:

PHP
1
fopen("http://сайт.ру/log.php?id=".$chat_id, "r");

Или можно с помощью file_get_contents либо curl. Но вообще, зачем такое понадобилось?

Добавлено через 1 минуту

Не по теме:

И, вот это что?

PHP
1
exit("<script>document.location.href='../404.php';</script>");

Лучше так:

PHP
1
header('Location: ../404.php');



1



3 / 3 / 2

Регистрация: 17.04.2014

Сообщений: 37

09.06.2014, 17:59

 [ТС]

5

lyod, попробовал сделать полный адрес http — то же самое выходит.
Другие функции, которые вы предлагали, загуглил, смотрел мануалы, но это всё не совсем то, что мне нужно.
Я хочу, чтобы размер окна чата не менялся, сколько бы не было сообщений… Или с этими функциями тоже можно так сделать?
Я просто ещё только изучаю php, поэтому пока не силён в этом…
Извините.



0



Эксперт PHP

5735 / 4122 / 1500

Регистрация: 06.01.2011

Сообщений: 11,251

09.06.2014, 19:07

6

Цитата
Сообщение от Хитрый Лис
Посмотреть сообщение

Я хочу, чтобы размер окна чата не менялся, сколько бы не было сообщений

Я не понял . А причём тут окно чата и эти функции? Можно же просто прокрутку сделать для окна…



1



3 / 3 / 2

Регистрация: 17.04.2014

Сообщений: 37

10.06.2014, 14:38

 [ТС]

7

lyod, а… ну хорошо, допустим… Я заменил fopen на include, но он не берёт url с get-запросом. Пробовал и полный адрес http прописывать, и просто так. Всё равно выдаёт ошибку, что не нашёл файл. Видимо с fopen была та же ситуация. Может есть такая функция, которая подключает веб-страницу по url, в котором содержится get-запрос?

Добавлено через 59 минут
Попробовал с cUrl и file_get_contents. С первой та же история, а вот со вторым всё заработало, спасибо! Вот только теперь аякс не работает… буду разбираться. Ещё раз спасибо!



0



Эксперт PHP

5735 / 4122 / 1500

Регистрация: 06.01.2011

Сообщений: 11,251

11.06.2014, 08:50

8

Пожалуйста, конечно, но мне кажется использовать GET в данном случае не самый удачный вариант… Тут можно сделать по-другому, только я не знаю, почему Вам нужно передавать параметр в подключаемый файл.



0



За последние 24 часа нас посетили 8757 программистов и 850 роботов. Сейчас ищут 409 программистов …


  1. Drobotko Taras

    Drobotko Taras
    Активный пользователь

    С нами с:
    13 окт 2016
    Сообщения:
    30
    Симпатии:
    1

    Добрый день! Пишу код для edit.php (используя PDO), который дает возможность админу редактировать статьи на блоге. Админ заходит с главной страницы, например, по адресу /edit.php?id=7, делает необходимые правки статьи в полях формы и жмет кнопку «Сохранить». Но! Необходимого обновления таблицы в БД mysql не происходит. Проанализировав код, я пришёл к заключению, что ошибка св’язана с передачей $_GET[‘id’] внутрь блока if (isset($_POST[‘submit’])) { …}. $_GET[‘id’] передает id статьи, по которому идентификуется стаття в БД. Как, в моем случае, можно передать id статьи внутрь блока с кодом:

    1. if (isset($_POST[‘submit’])) {
    2.   $stmt = $conn->prepare(‘UPDATE content SET title= :title, short_desc= :short_desc,
    3.  full_desc= :full_desc, timestamp= :timestamp WHERE id = :id’);
    4.   $stmt->bindParam(‘:id’, $_GET[‘id’], PDO::PARAM_INT);
    5.   $stmt->bindParam(‘:title’, strip_tags($_POST[‘title’]));
    6.   $date = «{$_POST[‘date’]}  {$_POST[‘time’]}«;
    7.   $stmt->bindParam(‘:timestamp’, strtotime($date));
    8.   $status= $stmt->execute();
    9. } catch(PDOException $e) {
    10.   print «ERROR: {$e->getMessage()}»;
    11.   require(‘base/footer.php’);
    12. <form action=»<?php print $_SERVER[«PHP_SELF»]; ?>» method=»POST»>’

    Помогите, пожалуста, разобраться!


  2. ADSoft


  3. Drobotko Taras

    Drobotko Taras
    Активный пользователь

    С нами с:
    13 окт 2016
    Сообщения:
    30
    Симпатии:
    1

    1. <form action=»<?php print $_SERVER[«PHP_SELF»]; ?>» method=»POST»>
    2.   <label for=»title»>Заголовок</label>
    3.   <input type=»text» name=»title» id=»title» required maxlength=»255″ value=»<?php echo $article[‘title’]; ?>«>
    4.   <label for=»short_desc»>Короткий зміст</label>
    5.   <textarea name=»short_desc» id=»short_desc» required maxlength=»600″><?php echo $article[‘short_desc’]; ?></textarea>
    6.   <label for=»full_desc»>Повний зміст</label>
    7.   <textarea name=»full_desc» id=»full_desc»
    8.   required><?php echo $article[‘full_desc’]; ?></textarea>
    9.   <label for=»date»>День створення</label>
    10.   <input type=»date» name=»date» id=»date» required
    11.   value=»<?php print date(‘Y-m-d’, $article[‘timestamp’]); ?>«>
    12.   <label for=»time»>Час створення</label>
    13.   <input type=»time» name=»time» id=»time» required
    14.   value=»<?php print date(‘G:i’, $article[‘timestamp’]); ?>«>
    15. <input type=»submit» name=»submit» value=»Зберегти»>


  4. ADSoft

    1.     <form action=»<?php print $_SERVER[«PHP_SELF»].’?id=7′; ?>

    так надо гет то оптравлять


  5. Maputo

    Maputo
    Активный пользователь

    С нами с:
    30 июл 2015
    Сообщения:
    1.136
    Симпатии:
    173

    1. <?php print $_SERVER[«REQUEST_URI»]; ?>

@fiveriddle

Describe the Bug
When i want use the get_id of CameraRecognitionObject when using Python, it occurs the error that the get_id are not in the list, i wonder how could i take the id or the position out?
屏幕快照 2020-05-22 上午10 02 15

Screenshots
If applicable, add screenshots to help explain your problem.

System

  • Operating System: macOS Mojave

@omichel

You should write:

    if data.get_id() == 1813:

@fiveriddle

You should write:

    if data.get_id() == 1813:

it still occur the error
[recog] Traceback (most recent call last):
[recog] File «recog.py», line 43, in
[recog] if data.get_id() == 1803:
[recog] AttributeError: ‘list’ object has no attribute ‘get_id’

@omichel

Can you please post your complete controller source code?

@fiveriddle

Can you please post your complete controller source code?

from so far it is like
from controller import Robot
from controller import Camera
from controller import CameraRecognitionObject


TIME_STEP = 64

robot = Robot()
camera1=Camera('camera1')
camera1.enable(TIME_STEP)
camera1.recognitionEnable(TIME_STEP)
wheels = []
data=[]
wheelsNames = ['wheel1', 'wheel2', 'wheel3', 'wheel4']
for i in range(4):
    wheels.append(robot.getMotor(wheelsNames[i]))
    wheels[i].setPosition(float('inf'))
    wheels[i].setVelocity(0.0)

while robot.step(timestep) != -1:
    leftSpeed = 0.0
    rightSpeed = 0.0
    cameraData = camera1.getImage()
    number = camera1.getRecognitionNumberOfObjects() 
    data = camera1.getRecognitionObjects()   
    for i in range(number):
        if data.get_id() == 1803:
            leftSpeed = 6.0
            rightSpeed = 6.0
            if((data.get_position())> -3):
                leftSpeed = 0.0
                rightSpeed = 0.0

@omichel

Can you try this:

[...]
    data = camera1.getRecognitionObjects()   
    for d in data:
        if d.get_id() == 1803:
[...]

@fiveriddle

Can you try this:

[...]
    data = camera1.getRecognitionObjects()   
    for d in data:
        if d.get_id() == 1803:
[...]

My aim is to scan all the objects in the image to check whether there exist the ideal id(which we have test and record before). Once confirmed, I want to get the z, x or y position of the object. ( for the next step). However, when I take use of python, I do not understand how to call database.

  1. Do I need to use the CameraRecognitionObject API?
    Such as directly use
    CameraRecognitionObject.get_id()
    or use
    data = camera1.getRecognitionObjects()
    and use data.get_id()
  2. how to call the position, do i need to built another 3 length array like
    position =[3]
    position=data[i].get_position()
    and take use of position[2] to use the z-position?
    and how could i know the objects’ id
    is the class more like
    data[i].get_position[k](in C language)?
    how to write it in python?
    Thanks a lot.

@omichel

Yes, getRecognitionObjects() returns an array of CameraRecognitionObject which you can access using either the []operator or the for object in objects construct which I originally suggested.

@fiveriddle

Describe the Bug
When i want use the get_id of CameraRecognitionObject when using Python, it occurs the error that the get_id are not in the list, i wonder how could i take the id or the position out?
屏幕快照 2020-05-22 上午10 02 15

Screenshots
If applicable, add screenshots to help explain your problem.

System

  • Operating System: macOS Mojave

@omichel

You should write:

    if data.get_id() == 1813:

@fiveriddle

You should write:

    if data.get_id() == 1813:

it still occur the error
[recog] Traceback (most recent call last):
[recog] File «recog.py», line 43, in
[recog] if data.get_id() == 1803:
[recog] AttributeError: ‘list’ object has no attribute ‘get_id’

@omichel

Can you please post your complete controller source code?

@fiveriddle

Can you please post your complete controller source code?

from so far it is like
from controller import Robot
from controller import Camera
from controller import CameraRecognitionObject


TIME_STEP = 64

robot = Robot()
camera1=Camera('camera1')
camera1.enable(TIME_STEP)
camera1.recognitionEnable(TIME_STEP)
wheels = []
data=[]
wheelsNames = ['wheel1', 'wheel2', 'wheel3', 'wheel4']
for i in range(4):
    wheels.append(robot.getMotor(wheelsNames[i]))
    wheels[i].setPosition(float('inf'))
    wheels[i].setVelocity(0.0)

while robot.step(timestep) != -1:
    leftSpeed = 0.0
    rightSpeed = 0.0
    cameraData = camera1.getImage()
    number = camera1.getRecognitionNumberOfObjects() 
    data = camera1.getRecognitionObjects()   
    for i in range(number):
        if data.get_id() == 1803:
            leftSpeed = 6.0
            rightSpeed = 6.0
            if((data.get_position())> -3):
                leftSpeed = 0.0
                rightSpeed = 0.0

@omichel

Can you try this:

[...]
    data = camera1.getRecognitionObjects()   
    for d in data:
        if d.get_id() == 1803:
[...]

@fiveriddle

Can you try this:

[...]
    data = camera1.getRecognitionObjects()   
    for d in data:
        if d.get_id() == 1803:
[...]

My aim is to scan all the objects in the image to check whether there exist the ideal id(which we have test and record before). Once confirmed, I want to get the z, x or y position of the object. ( for the next step). However, when I take use of python, I do not understand how to call database.

  1. Do I need to use the CameraRecognitionObject API?
    Such as directly use
    CameraRecognitionObject.get_id()
    or use
    data = camera1.getRecognitionObjects()
    and use data.get_id()
  2. how to call the position, do i need to built another 3 length array like
    position =[3]
    position=data[i].get_position()
    and take use of position[2] to use the z-position?
    and how could i know the objects’ id
    is the class more like
    data[i].get_position[k](in C language)?
    how to write it in python?
    Thanks a lot.

@omichel

Yes, getRecognitionObjects() returns an array of CameraRecognitionObject which you can access using either the []operator or the for object in objects construct which I originally suggested.

Хорошо, это меня серьезно поставило в тупик, после нескольких часов попыток с блоком javascript ниже я все еще получаю ту же ошибку в отладчике javascript IE.

Я получаю сообщение об ошибке SCRIPT5007: невозможно получить значение свойства «get_id»: объект имеет значение null или не определен.

И ниже мой код:

AS.SP.ClientActions.ClientProgramEdit_Status = new AS.SP.ClientActions.ButtonStatus();
AS.SP.ClientActions.Can_ClientProgramEdit = function (groupID) {

var OnError = function (sender, args) {
    AS.SP.ClientActions.ClientProgramEdit_Status.enabled = false;
    RefreshCommandUI();
};

var items = AS.SP.ClientActions.GetSelectedItems();
var count = CountDictionary(items);
if (count === 1) {
    var itemID = items[0].id;
    if (AS.SP.ClientActions.ClientProgramEdit_Status.itemID != itemID) {
        AS.SP.ClientActions.ClientProgramEdit_Status.itemID = itemID;
        AS.SP.ClientActions.ClientProgramEdit_Status.enabled = false;

        AS.SP.ClientActions.GetUrl(function (rootUrl) {
            var fragments = AS.SP.Navigation.ParseUri(rootUrl);

            var ctx = new SP.ClientContext(fragments.path); 
            var web = ctx.get_web();
            var props = web.get_allProperties();

            ctx.load(web);
            ctx.load(props);
            ctx.executeQueryAsync(function () {

                var listId = 'Client Programs';
                var sdlist = web.get_lists().getByTitle(listId);

                var locationID = props.get_item('WL_ITEM_ID');
                var query = new SP.CamlQuery();
                query.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name="len_cp_Location" /><Value Type="Text">' + locationID + '</Value></Eq><Eq><FieldRef Name="len_cp_Client_Status" /><Value Type="Text">Inactive</Value></Eq></And></Where></Query><ViewFields><FieldRef Name="Title" /></ViewFields></View>');
                var items = sdlist.getItems(query);
                ctx.load(items);
                ctx.executeQueryAsync(function () {
                    var item = items.itemAt(0);
                    var itemID = item.get_id();

                    if (itemID == "WL_ITEM_ID") {
                        AS.SP.ClientActions.ClientProgramEdit_Status.enabled = true;
                        RefreshCommandUI();
                    }
                }, OnError);
            }, OnError);
        });
    }
}

return AS.SP.ClientActions.ClientProgramEdit_Status.enabled;
}

Моя теория заключается в том, что я сделал что-то не так с моим CAML-запросом, но на данный момент я действительно не знаю, любая помощь в этом будет очень признательна, спасибо!

1 ответы

Вы используете items переменная дважды, один раз в строке 9:

var items = AS.SP.ClientActions.GetSelectedItems();

И снова внутри GetUrl:

var items = sdlist.getItems(query);

В замыкании executeQueryAsync возник конфликт имен. Я бы начал с решения этой проблемы. На какую коллекцию элементов вы хотите сослаться? Вы имеете в виду загрузить исходную переменную элементов:

 ctx.load(items); 
 var items = sdlist.getItems(query);

Создан 03 июля ’12, 19:07

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

javascript
sharepoint-2010
caml

or задайте свой вопрос.

На моем веб-сайте wordpress я получаю ошибку ниже

Fatal error: Call to a member function get_id() on boolean in /home/customer/www/ae.testing.com/public_html/wp-content/themes/movedo-child/functions.php on line 33

Раньше работал нормально. но теперь, какой именно вопрос я не понимаю. если у кого-то есть идеи, дайте мне знать

Function.php следующим образом:

<?php
function movedo_child_theme_setup() {
}
add_action( 'after_setup_theme', 'movedo_child_theme_setup' );


function display_price_in_variation_option_name( $term ) {
   echo  $product = wc_get_product();
    $id = $product->get_id();
    if ( empty( $term ) || empty( $id ) ) {
        return $term;
    }
    if ( $product->is_type( 'variable' ) ) {
        $product_variations = $product->get_available_variations();
    } else {
        return $term;
    }

    foreach($product_variations as $variation){
        if(count($variation['attributes']) > 1){
            return $term;
        }
        foreach($variation['attributes'] as $key => $slug){
            if("attribute_" == mb_substr( $key, 0, 10 )){
                $taxonomy = mb_substr( $key, 10 ) ;
                $attribute = get_term_by('slug', $slug, $taxonomy);
                if($attribute->name == $term){
                    $term .= " (" . wp_kses( wc_price($variation['display_price']), array()) . ")";
                }
            }
        }
    }
    
    return $term;

}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );

В строке « $ id = $ product-> get_id (); » я получаю эту ошибку.

2 ответа

Лучший ответ

Проблема кажется довольно простой, вы подключаетесь к after_setup_theme, которая запускается для каждого отдельного запроса wordpress. В этом контексте вы предполагаете, что у вас всегда есть продукт в контексте основного запроса, что не всегда верно.

Чтобы просто закрыть ошибку, оберните $ id = $ product-> get_id (); в такое, если так:

if(!empty($product)){    
    $id = $product->get_id();
}
...

Но чтобы сделать это действительно пуленепробиваемым, вы должны спросить себя, когда вы действительно хотите изучить wc_get_product, чтобы получить текущий продукт. Я предполагаю, что вы можете захотеть это только на странице сведений о продукте. Поскольку вы подключаетесь к ‘after_setup_theme’, можно использовать условные теги.

Измените свой код, чтобы вывести его из строя, как только он не выполняется на нужной странице, сделав что-то вроде этого:

function display_price_in_variation_option_name( $term ) {
    if (!is_product()){
        return;
    }
    echo  $product = wc_get_product();
    $id = $product->get_id();
    ...


1

Diego
7 Июн 2021 в 18:09

Wc_get_product каким-то образом возвращает false. Пытаться

global $product; //


0

Yoda — user264474
3 Фев 2022 в 13:25

вот php код

if(isset($_GET['id'])) {
    //do something
} else {
    redirect('index.php'); //redirect is a function
}

теперь, если id установлен (например: index.РНР?id=12), то действие выполняется, но если id не установлен (например, индекс.РНР?id=) это показывает ошибку, как ее преодолеть…??

Как определить id-это целое число, и оно не пустое, а затем выполнить определенное действие….

редактировать

спасибо всем за ваши ответы, но я все еще получаю эту ошибку…

if(isset($_GET['id'])) { // I implemented all these codes but still....
    $user= User::find_by_id($_GET['id']);
   // Database Classes Fetches user info from database
}
else {
    redirect('index.php'); //redirect function
}

Если id равен 1 или больше 1, то скрипт выполняется отлично. ( индекс.РНР?id=1)

но id я установил id, отметив, что получаю ошибку i..индекс Е.РНР?id=

код должен автоматически перенаправлять пользователя на индекс.страница php вместо отображения ошибки…..

ошибка: запрос базы данных не удался: у вас есть ошибка в синтаксисе SQL; проверьте руководство, которое соответствует вашей версии сервера MySQL для правильного синтаксиса для использования рядом с «пределом 1» в строке 1

8 ответов


вы должны проверить и set-status и содержание:

if ( isset( $_GET['id'] ) && !empty( $_GET['id'] ) )
    // ....

обратите внимание, что вы должны не используйте значение просто как есть и работайте с ним. Вы должны убедиться, что он содержит только ожидаемые значения. Чтобы проверить целое число и даже лучше работать с целым числом, сделайте что-то вроде этого:

$id = ( isset( $_GET['id'] ) && is_numeric( $_GET['id'] ) ) ? intval( $_GET['id'] ) : 0;

if ( $id != 0 )
    // id is an int != 0
else
    redirect('index.php');

что говорит вам ошибка?

но это проверит, установлен ли он, и если это целое число

if(isset($_GET['id']) && ctype_digit($_GET['id']) && intval($_GET['id']) > 0)

is_numeric @ php.net

или проверить ctype_digit


if (!empty($_GET['id']) && filter_var($_GET['id'], FILTER_VALIDATE_INT))

или

if (!empty($_GET['id']) && ctype_digit($_GET['id']))

хорошо… Если вы настраиваете его как переменную целочисленного типа, вы также можете сделать следующее:

if($_GET['id'] && gettype($_GET['id']) == 'integer'){
    #do something
}else{
    #do something else
}

Как определить id — это целое число и он не пуст а затем выполните определенное действие….

if (!empty($_GET['id']) && (intval($_GET['id']) == $_GET['id'])) {
    //do something
} else {
    redirect('index.php'); //redirect is a function
}

вышеуказанное не может быть лучшим решением, но оно должно работать для того, что вам нужно. Он не позволит идентификатору быть 0 и потребует, чтобы он был целым числом.


 if(isset($_GET['id']) && ctype_digit($_GET['id']) && is_numeric($_GET['id']) && $_GET['id']>0) {
  $user= User::find_by_id($_GET['id']);
  }
else {
  redirect('index.php'); //redirect function
  }

попробуйте это и этот код полный таблетки ваше требование.


похоже, у вас просто проблема с?id бросает true, когда вы хотите проверить, установлен ли его. Это потому, что он установлен, но не установлен на значение, которое вы хотели бы использовать.

Я предполагаю, что userids должны быть > 0, поэтому просто сделайте это

if (isset($_GET['id']) && $_GET['id'] > 0) {
    $user= User::find_by_id($_GET['id']);
} else {
    redirect('index.php'); 
}

Также вы, вероятно, лучше всего очищаете идентификатор перед обработкой его так

$userID = isset($_GET['id']) && $_GET['id'] > 0 ? (int) $_GET['id'] : 0;

if ($userID) {
    $user= User::find_by_id($userID);
} else {
    redirect('index.php'); 
}

есть много способов сделать это, лично я предпочитаю этот. Это делает ваш код немного чище.


вам придется проверять несколько раз для каждого возможного случая: что делать, если id не установлен или пуст? что делать, если id установлен, но это не цифра? что делать, если ключ » id » вообще не существует в запросе GET?

У меня была похожая ситуация. Я отправлял два вара с GET, одна цифра: «id», а другая-строка, которая была именем: «state»… Я решил проверить все возможные условия.


0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Get contact ошибка 5003 как исправить
  • Get contact ошибка 5001 как избавиться