Fatal error uncaught error call to a member function setpageproperty

Fatal error: Call to a member function query() on null PHP БД Решение и ответ на вопрос 2399258

Just_art

0 / 0 / 0

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

Сообщений: 1

1

05.02.2019, 01:56. Показов 16581. Ответов 2

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


доброго времени суток всем!

проблема: есть класс базы данных и есть метод query который выполняет запрос в бд. с этим методом связана следующая ошибка которую выдает php: Fatal error: Uncaught Error: Call to a member function Query() on null in /testovaya/reg.php:12 Stack trace: #0 {main} thrown in testovaya/reg.php on line 12

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
require_once("connection.php");
 
$name =$_POST['login'];
$pass1 =$_POST['password'];
$pass2 =$_POST['password2'];
 
if($name != null){
if($pass1 == $pass2){
    
    $db->Query("INSERT INTO `user` (`id`, `name`, `count`, `chests`, `pass`) VALUES (NULL, '.$name.', '0', '0','.$pass2')");
    $db->Query("$sql");
 
}else{
    echo "<div id='error'>Пароли не совпадают</div>";
}
}else{
    echo "<div id='error'>не Указан логин</div>";
}
?>

Если удалять 12 строку он пишет что 13 строка выдаёт ошибку.
помогите пожалуйста решить эту ошибку. перерыл весь интернет но не нашел ничего полезного что могло бы решить конкретно эту проблему. всем заранее спасибо!

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



0



svtslv

307 / 159 / 66

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

Сообщений: 449

05.02.2019, 03:57

2

Данные от пользователя всегда нужно проверять. Есть подозрения что ТС хотел написать…

PHP
1
"VALUES (NULL, '".$name."', '0', '0','".$pass2."')";

Добавлено через 2 минуты
Или скорее всего так хотел… хотя кто знает…

PHP
1
2
$sql = "INSERT INTO `user` (`id`, `name`, `count`, `chests`, `pass`) VALUES (NULL, '".$name."', '0', '0','".$pass2."')";
$db->Query($sql);

Добавлено через 2 минуты
А можно было и так…

PHP
1
2
$sql = "INSERT INTO `user` (`id`, `name`, `count`, `chests`, `pass`) VALUES (NULL, '$name', '0', '0', '$pass2')";
$db->Query($sql);



0



Эксперт PHP

3802 / 3160 / 1326

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

Сообщений: 10,717

05.02.2019, 07:35

3

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

Call to a member function Query() on null

Вызов метода Query() у несуществующей переменной. Т.е. в $db ничего нет.

Либо надо создать подключение (как именно — надо смотреть файл connection.php), либо переменная с соединением называется как-то иначе.

И $sql тоже не определена.



0



Bug report

just ran into a «random» error, which phpstan told me to open a issue with this stack trace:

phpstan analyse -c phpstan.neon.dist
 252/252 [============================] 100% ------ --------------------------------------------------------------
  Line   libDebug.php
 ------ --------------------------------------------------------------
         Internal error: Call to a member function getType() on null
         Run PHPStan with --debug option and post the stack trace to:
         https://github.com/phpstan/phpstan/issues/new
 ------ --------------------------------------------------------------

so, running with --debug gets me:

PHP Fatal error:  Uncaught Error: Call to a member function getType() on null in phar://C:/Users/mstaab/Documents/GitHub/php-rocket/vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan/src/Rules/Functions/IncompatibleDefaultParameterTypeRule.php:51
Stack trace:
#0 phar://C:/Users/mstaab/Documents/GitHub/php-rocket/vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan/src/Analyser/FileAnalyser.php(69): PHPStanRulesFunctionsIncompatibleDefaultParameterTypeRule->processNode(Object(PhpParserNodeStmtFunction_), Object(PHPStanAnalyserMutatingScope))
#1 phar://C:/Users/mstaab/Documents/GitHub/php-rocket/vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan/src/Analyser/NodeScopeResolver.php(243): PHPStanAnalyserFileAnalyser->PHPStanAnalyser{closure}(Object(PhpParserNodeStmtFunction_), Object(PHPStanAnalyserMutatingScope))
#2 phar://C:/Users/mstaab/Documents/GitHub/php-rocket/vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan/src/Analyser/NodeScopeResolver.php(203): PHPStanAnalyserNodeScopeResolver->processStmtNode(Object(PhpPa in phar://C:/Users/mstaab/Documents/GitHub/php-rocket/vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan/src/Rules/Functions/IncompatibleDefaultParameterTypeRule.php on line 51
Fatal error: Uncaught Error: Call to a member function getType() on null in phar://C:/Users/mstaab/Documents/GitHub/php-rocket/vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan/src/Rules/Functions/IncompatibleDefaultParameterTypeRule.php:51
Stack trace:
#0 phar://C:/Users/mstaab/Documents/GitHub/php-rocket/vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan/src/Analyser/FileAnalyser.php(69): PHPStanRulesFunctionsIncompatibleDefaultParameterTypeRule->processNode(Object(PhpParserNodeStmtFunction_), Object(PHPStanAnalyserMutatingScope))
#1 phar://C:/Users/mstaab/Documents/GitHub/php-rocket/vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan/src/Analyser/NodeScopeResolver.php(243): PHPStanAnalyserFileAnalyser->PHPStanAnalyser{closure}(Object(PhpParserNodeStmtFunction_), Object(PHPStanAnalyserMutatingScope))
#2 phar://C:/Users/mstaab/Documents/GitHub/php-rocket/vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan/src/Analyser/NodeScopeResolver.php(203): PHPStanAnalyserNodeScopeResolver->processStmtNode(Object(PhpPa in phar://C:/Users/mstaab/Documents/GitHub/php-rocket/vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan/src/Rules/Functions/IncompatibleDefaultParameterTypeRule.php on line 51
Script phpstan analyse -c phpstan.neon.dist --debug handling the phpstan event returned with error code 255

do you need more to reproduce or similar?

env:

$ php -v
PHP 7.4.5 (cli) (built: Apr 14 2020 16:17:19) ( NTS Visual C++ 2017 x64 )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies

mstaab@NB-COMPLEX-15 MINGW64 ~/Documents/GitHub/php-rocket (rm-pear)
$ vendor/bin/phpstan -v
PHPStan - PHP Static Analysis Tool 0.12.25

  John Mwaniki /   18 Jan 2022

A prepared statement is a very useful feature in database management that increases efficiency and protects the database against SQL injections. It is also referred to as a parameterized statement.

It works by separating the SQL code from the data.

In the prepared statement, an SQL statement template is created and sent to the database with values unspecified (labeled with «?»). These question marks (?) are referred to as parameters.

The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it.

The application later binds the values to the parameters, then executes the SQL statement. The application can execute the statement many times with different values without having to do the parsing and thus increasing the efficiency.

Since the parameter values are transmitted later, separately from the SQL statement using a different protocol, SQL injection cannot occur.

Below is an example code of inserting data in a table with a prepared statement in MySQLi.

<?php
$fname = "John"
$lname = "Doe";
$email = "johndoe@gmail.com";
$con = new mysqli("servername", "db_username", "db_password", "db_name");
$stmt = $con->prepare("INSERT INTO users(first_name, last_name, email) VALUES(?,?,?)");
$stmt->bind_param("sss", $fname, $lname, $email);
$stmt->execute();

The example below shows a code for updating a record in the database table using a prepared statement.

<?php
$fname = "John"
$lname = "Doe";
$email = "johndoe@gmail.com";
$userid = 5;
$con = new mysqli("servername", "db_username", "db_password", "db_name");
$stmt = $con->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ? WHERE id = ?");
$stmt->bind_param("sssi", $fname, $lname, $email, $userid);
$stmt->execute();

When working with prepared statements in MySQLi, it’s common to encounter the error below from time to time.

PHP Fatal error: Uncaught Error: Call to a member function bind_param() on bool in /path/to/file/filename.php:x

This happens when prepare returns a bool false instead of a MySQLi statement object. That is then causing the fatal error you see here. This is due to an error in the SQL statement.

How to Fix the Error

Below are possible ways to fix the error:

  • Countercheck to make sure that the name of the table and its columns which are specified in the SQL statement is exactly the same as in the database with no misspellings.
  • If you specify the table columns you are working with, ensure that the number of column names matches that of the parameters (?). For instance in example 1 above, we have 3 columns (first_name, last_name, email) we are inserting into. We must include exactly 3 «?» and not more or less. Ensure that they are separated with commas (,) and no extra comma is there.
  • If you don’t specify the column names that you’re inserting values into, then you have to give values for every column. For instance, if your table has 5 columns and you don’t specify columns in the statement, you have to supply 5 values or else you get the error.
  • In the bind_param() function, make sure that the number of values is equal to the number of parameters (?) passed in the prepare() function. For instance, in example 1 we have 3 parameters (?,?,?) in the prepare() function and 3 values ($fname, $lname, $email) in the bind_param().
  • Make sure to specify the types of data of the parameters as the first argument in the bind_param() function, eg «sss» in example 1 and «sssi» in example 2. The «s» character tells mysql that the parameter is a string. Other types include «i» for integer, «d» for double and «b» for BLOB.
    The number of types in the argument should be equal to the number of values. Their order should also be the same as that of the respective values.

By fixing any of the above possible causes, your code should definitely work with no errors.

2 hours ago, dunno said:

But your solution makes total sense: the global scope within the class must be inside the class but outside any function, and the call to that property within a function must be accessed using the «$this» keyword. A simple error which I will not forget. Thank you for pointing it out.

That is not quite an accurate description.

PHP has exactly two variable scopes: one for inside of functions (each function gets its own and it isn’t shared with other functions) and one for outside of functions (normally referred to as the global scope, which is the same everywhere and even shared across files).

<?php

$a = 1; // global scope
echo $a; // 1

function one() {
  echo $a; // empty: $a from the global scope is not available inside this function scope so this "$a" is different
  $a = 2; // a new variable in the function scope
  echo $a; // 2
}
one();

function two() {
  echo $a; // $a from the global scope or one's scope is not available inside here either
  $a = 3; // a new variable
  echo $a; // 3
}
two();

one(); // will output the same thing as before: first echo shows nothing, second echo shows 2

echo $a; // still 1

Code in functions can use the «global» keyword to access the global scope, but this is very strongly discouraged.

With classes, their functions («methods») have a function scope just like every other regular function has. What PHP does differently is give you a «$this» variable corresponding to the instance of the class. $this->db is using the $this variable (scoped only to the method) to access its «db» property (which has nothing to do with scope).

<?php

class Example {
  public $a;
  
  public function one() {
    echo $this->a;
    $this->a = 1;
    echo $this->a;
  }
  
  public function two() {
    echo $this->a;
  }
}

$example = new Example();
$example->one(); // first echo shows nothing because $a is undefined, second shows 1
$example->two(); // also 1

// echo $this->a; // "$this" is only available inside class methods

$example->a = 2;
$example->two(); // 2

Variable scope only matters for variables, as in things that use dollar signs, and besides the «public $a» (whose dollar sign is really more about the syntax for defining «a» in the Example class), there are only two ways that dollar signs are used in the above code: with $this and with $example.

  • Posts

  • I just installed a new woocommerce plugin “Woo Terms & Conditions Text” and once intalled I got this message Fatal error: Uncaught Error: Call to a member function get_page_permastruct() on null in /home1/whatthev/public_html/new2/wp-includes/link-template.php:357 Stack trace: #0 /home1/whatthev/public_html/new2/wp-includes/link-template.php(320): _get_page_link(Object(WP_Post), false, false) #1 /home1/whatthev/public_html/new2/wp-includes/link-template.php(144): get_page_link(Object(WP_Post), false, false) #2 /home1/whatthev/public_html/new2/wp-content/plugins/woocommerce/includes/wc-page-functions.php(72): get_permalink(Object(WP_Post)) #3 /home1/whatthev/public_html/new2/wp-content/plugins/woo-terms-conditions-text/woo-terms-text.php(85): wc_get_page_permalink(‘terms’) #4 /home1/whatthev/public_html/new2/wp-includes/class-wp-hook.php(298): wtc_text_strings(‘Overview’, ‘Overview’, ‘google-analytic…’) #5 /home1/whatthev/public_html/new2/wp-includes/plugin.php(203): WP_Hook->apply_filters(‘Overview’, Array) #6 /home1/whatthev/public_html/new2/wp-includes/l10n.php(134): apply_filters(‘gettext’, ‘Overview’, ‘Overview’, ‘google-a in /home1/whatthev/public_html/new2/wp-includes/link-template.php on line 357

    The blog I need help with is: (visible only to logged in users)

    Hi @whatthevintage,

    The site we have whatthevintage.wordpress.com does not seem to have WooCommerce installed. And your error seems to be Self-Hosted WordPress issue.

    Could you confirm the URL of the site you are referring? Ones I have the information would be happy to help you further.

    Thanks!

    Hi again,

    Thank you for the correct link. Your site is hosted on Bluehost and using WordPress software only. It is not a WordPress.com hosted site. You can learn more about the differences in the two platforms here:

    WordPress Com vs WordPress ORG

    Your best way to get help would be to contact the Woocommerce directly.

    Also for future reference, your best way to get help for the Self-Hosted WordPress site would at the WordPress.org Support:

    WordPress org Support

    Also just check if this search result could be useful for you:

    Search

    Best wishes for getting your error resolved soon.

    Thanks!

  • The topic ‘Fatal error: Uncaught Error: Call to a member function get_page_permastruct()’ is closed to new replies.

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


  1. Daryaa049

    С нами с:
    5 окт 2020
    Сообщения:
    28
    Симпатии:
    0

    Добрый день, у меня появляется сообщение:Fatal error: Uncaught Error: Call to a member function prepare() on null in C:OSPaneldomainsregustratandvhodindex.php:70 Stack trace: #0 {main} thrown in C:OSPaneldomainsregustratandvhodindex.php on line 70
    Код:

    1. $sql = $conn->prepare(«SELECT COUNT(*) as `total` FROM registrasia WHERE email = :email»);
    2. $sql->execute(array(‘:email’ => $email));
    3. $result = $sql->fetchObject();
    4. echo ‘The email: ‘ . $email. ‘ is already in the database<br />’;
    5. echo ‘No rows matched the query.’;

    Подлкючение:

    1.     $conn = new PDO(«mysql:host=localhost;dbname=registra», ‘root’, »);
    2.     // set the PDO error mode to exception
    3.     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    4.     $sql = «INSERT INTO registrasia (firstname, lastname, email, number,password)
    5.    VALUES (‘firstname’, ‘lastname’, ’email’, ‘number’,’password’)»;
    6.     // use exec() because no results are returned
    7.     echo «Новая запись успешно создана!»;
    8.     echo $sql . «<br>» . $e->getMessage();


  2. ADSoft

    А потом чето пытаетесь сделать???


  3. Daryaa049

    С нами с:
    5 окт 2020
    Сообщения:
    28
    Симпатии:
    0

    Я пытаюсь создать регистрацию) Мне нужно проверить на занятость данной строки, т. е существует ли точно такая же строка


  4. ADSoft

    я не зря процитировал вас! вы пытаетесь что-то вызвать от $conn который — null !!!


  5. Daryaa049

    С нами с:
    5 окт 2020
    Сообщения:
    28
    Симпатии:
    0

    То есть я как то не так подключила, или сами строки в базе не видет?)


  6. ADSoft

    Ты обнуляешь результат соединения

    а потом пытаешься использовать

    это то же самое что пытаться NULL->а вызови ка мне функцию, или дай данных

    попробуй закоменнтироватьэтоу фигню


  7. Daryaa049

    С нами с:
    5 окт 2020
    Сообщения:
    28
    Симпатии:
    0

    Да, действительно, спасибо большое)

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error uncaught error call to a member function fetch on boolean in
  • Fatal error uncaught error array callback has to contain indices 0 and 1
  • Fatal error викед вимс
  • Fatal error арт
  • Fatal error uncaught error access to undeclared static property

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

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