0 Пользователей и 1 Гость просматривают эту тему.
  • 3 Ответов
  • 547 Просмотров
*

ShopES

  • Захожу иногда
  • 426
  • 11 / 0
Определить ошибку
« : 06.09.2021, 10:22:46 »
При импорте вылетает ошибка
Код
Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in /import-excel/DataSource.php on line 147

Fatal error: Uncaught Error: Call to a member function execute() on bool in /import-excel/DataSource.php:109 Stack trace: #0 /import-excel/index.php(73): Phppot\DataSource->insert('insert into tbl...', 'ss', Array) #1 {main} thrown in /import-excel/DataSource.php on line 109

Datasource
Код
<?php
/**
 * Copyright (C) 2019 Phppot
 *
 * Distributed under MIT license with an exception that,
 * you don’t have to include the full MIT License in your code.
 * In essense, you can use it on commercial software, modify and distribute free.
 * Though not mandatory, you are requested to attribute this URL in your code or website.
 */
namespace Phppot;

/**
 * Generic datasource class for handling DB operations.
 * Uses MySqli and PreparedStatements.
 *
 * @version 2.5 - recordCount function added
 */
class DataSource
{

    // PHP 7.1.0 visibility modifiers are allowed for class constants.
    // when using above 7.1.0, declare the below constants as private
    const HOST = 'localhost';

    const USERNAME = '111';

    const PASSWORD = '111';

    const DATABASENAME = '111';

    private $conn;

    /**
     * PHP implicitly takes care of cleanup for default connection types.
     * So no need to worry about closing the connection.
     *
     * Singletons not required in PHP as there is no
     * concept of shared memory.
     * Every object lives only for a request.
     *
     * Keeping things simple and that works!
     */
    function __construct()
    {
        $this->conn = $this->getConnection();
    }

    /**
     * If connection object is needed use this method and get access to it.
     * Otherwise, use the below methods for insert / update / etc.
     *
     * @return \mysqli
     */
    public function getConnection()
    {
        $conn = new \mysqli(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASENAME);

        if (mysqli_connect_errno()) {
            trigger_error("Problem with connecting to database.");
        }

        $conn->set_charset("utf8");
        return $conn;
    }

    /**
     * To get database results
     *
     * @param string $query
     * @param string $paramType
     * @param array $paramArray
     * @return array
     */
    public function select($query, $paramType = "", $paramArray = array())
    {
        $stmt = $this->conn->prepare($query);

        if (! empty($paramType) && ! empty($paramArray)) {

            $this->bindQueryParams($stmt, $paramType, $paramArray);
        }
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $resultset[] = $row;
            }
        }

        if (! empty($resultset)) {
            return $resultset;
        }
    }

    /**
     * To insert
     *
     * @param string $query
     * @param string $paramType
     * @param array $paramArray
     * @return int
     */
    public function insert($query, $paramType, $paramArray)
    {
        $stmt = $this->conn->prepare($query);
        $this->bindQueryParams($stmt, $paramType, $paramArray);

        $stmt->execute();
        $insertId = $stmt->insert_id;
        return $insertId;
    }

    /**
     * To execute query
     *
     * @param string $query
     * @param string $paramType
     * @param array $paramArray
     */
    public function execute($query, $paramType = "", $paramArray = array())
    {
        $stmt = $this->conn->prepare($query);

        if (! empty($paramType) && ! empty($paramArray)) {
            $this->bindQueryParams($stmt, $paramType, $paramArray);
        }
        $stmt->execute();
    }

    /**
     * 1.
     * Prepares parameter binding
     * 2. Bind prameters to the sql statement
     *
     * @param string $stmt
     * @param string $paramType
     * @param array $paramArray
     */
    public function bindQueryParams($stmt, $paramType, $paramArray = array())
    {
        $paramValueReference[] = & $paramType;
        for ($i = 0; $i < count($paramArray); $i ++) {
            $paramValueReference[] = & $paramArray[$i];
        }
        call_user_func_array(array(
            $stmt,
            'bind_param'
        ), $paramValueReference);
    }

    /**
     * To get database results
     *
     * @param string $query
     * @param string $paramType
     * @param array $paramArray
     * @return array
     */
    public function getRecordCount($query, $paramType = "", $paramArray = array())
    {
        $stmt = $this->conn->prepare($query);
        if (! empty($paramType) && ! empty($paramArray)) {

            $this->bindQueryParams($stmt, $paramType, $paramArray);
        }
        $stmt->execute();
        $stmt->store_result();
        $recordCount = $stmt->num_rows;

        return $recordCount;
    }
}

61-75 index
Код
           if (! empty($dateup) || ! empty($filial) || ! empty($tarif) || ! empty($numbsim) || ! empty($phonenumb) || ! empty($dateout) || ! empty($agents)) {
                $query = "insert into tbl_info(dateup,filial,tarif,numbsim,phonenumb,dateout,agents) values(?,?)";
                $paramType = "ss";
                $paramArray = array(
                    $dateup,
                    $filial,
                    $tarif,
                    $numbsim,
                    $phonenumb,
                    $dateout,
                    $agents
                );
                $insertId = $db->insert($query, $paramType, $paramArray);
                // $query = "insert into tbl_info(dateup,filial,tarif,numbsim,phonenumb,dateout,agents) values('" . $dateup . "','" . $filial . "','" . $tarif . "','" . $numbsim . "','" . $phonenumb . "','" . $dateout . "','" . $agents . "')";
                // $result = mysqli_query($conn, $query);
73 index
Код
$insertId = $db->insert($query, $paramType, $paramArray);
*

NewUsers

  • Живу я здесь
  • 2307
  • 215 / 0
  • +375 (25) 627-16-99 (WhatsApp, Telegram)
Re: Определить ошибку
« Ответ #1 : 06.09.2021, 10:58:48 »
Функция prepare класса mysqli возвращает false в случае ошибки.

Fatal error: Uncaught Error: Call to a member function execute() on bool in /import-excel/DataSource.php:109 Stack trace: #0 /import-excel/index.php(73): Phppot\DataSource->insert('insert into tbl...', 'ss', Array) #1 {main} thrown in /import-excel/DataSource.php on line 109

Согласно Fatal error: функция execute не может быть вызвана из значения bool, а это значит что в вашем запросе ошибка!
Занимаюсь создание расширений для Joomla 3.10.x и 4.2.x | Доработка и настройка сайтов. Занимаюсь создание Интернет магазинов с нуля на собственном компоненте + оптимизация загрузки страницы (после предоставляю техподдержку).
Работа с DOM деревом на PHP
*

ShopES

  • Захожу иногда
  • 426
  • 11 / 0
Re: Определить ошибку
« Ответ #2 : 06.09.2021, 11:28:00 »
фишка в том что на дефолте(типа демо) все работает
Код
            if (! empty($name) || ! empty($description)) {
                $query = "insert into tbl_info(name,description) values(?,?)";
                $paramType = "ss";
                $paramArray = array(
                    $name,
                    $description
                );
                $insertId = $db->insert($query, $paramType, $paramArray);
                // $query = "insert into tbl_info(name,description) values('" . $name . "','" . $description . "')";
                // $result = mysqli_query($conn, $query);
заменено только на данные своих столбцов в таблице
вот и не могу вкурить в чем косяк
при этом DataSource.php один и тот же
*

ShopES

  • Захожу иногда
  • 426
  • 11 / 0
Re: Определить ошибку
« Ответ #3 : 06.09.2021, 12:04:11 »
методом тыка вышел на следующие моменты
ошибка вываливается если больше 2 параметров передаем
смотрю строку
Код
$query = "insert into tbl_info(name,description) values(?,?)";
именно момент values(?,?) смущает
если меняем на
Код
$query = "insert into tbl_info(name,description,test) values(?,?,?)";
то валит ошибки
Код
Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables in /import-excel/DataSource.php on line 147
типа не соответствие количества переменных
и вот не вкурю никак где это количество переменных
если же строчку делаем
Код
$query = "insert into tbl_info(name,description,test) values(?,?)";
то вываливает изначальную ошибку
UPD
пока писал нашел ошибку
Код
$paramType = "ss";
надо на каждый столбец добавлять s
Чтобы оставить сообщение,
Вам необходимо Войти или Зарегистрироваться
 

Получить ошибку

Автор KevinSimon

Ответов: 0
Просмотров: 239
Последний ответ 22.09.2023, 15:20:21
от KevinSimon
После переноса сайта выдает ошибку

Автор rezchik

Ответов: 5
Просмотров: 563
Последний ответ 14.04.2023, 21:53:12
от rezchik
Как определить главную страницу без меню?

Автор d0ublezer0

Ответов: 4
Просмотров: 933
Последний ответ 23.03.2023, 13:26:57
от gen2023
Модуль Яндекс карты выдает ошибку Warning: count(): Parameter must be an array

Автор 62411

Ответов: 0
Просмотров: 371
Последний ответ 19.02.2023, 13:34:54
от 62411
Responsive Testimonials Pro выдает ошибку

Автор SoulWolf

Ответов: 2
Просмотров: 484
Последний ответ 22.01.2023, 17:38:57
от SoulWolf