Make number of rows in a matrix equal to a previous answer

I am writing a survey in SurveyJS and I would like the number of rows in a survey to equal a previous answer. It would be something like this, except that this fails:

const surveyJson = {
  "elements": [
    {
      "type": "text",
      "name": "num_classrooms",
      "inputType": "number",
      "min": 1,
      "max": 20,
      "title": "How many classrooms do you teach in this school?",
      "isRequired": true
    },
    {
  "type": "matrixdynamic",
  "name": "familyMatrix",
  "title": "Classroom Information",
  "columns": [
    {
      "name": "name",
      "title": "Name",
      "cellType": "text"
    },
    {
      "name": "age",
      "title": "Age",
      "cellType": "number"
    }
  ],
  "rowCount": "{num_classrooms}",
  "minRowCount": "{num_classrooms}",
  "maxRowCount": "{num_classrooms}"
    }
  ]
}

I know that I can let the user add or delete rows in a matrix, but for clarity I prefer that the user first give the number of classrooms and only after fill information.

I searched online for an answer and also tried AI, but couldn’t find a solution. The problem is similar to this question from Kobo Toolbox: asking for number of household members and adding a row for each member.

How can I do the same in SurveyJS?

rbv_api.setFieldValue, not updating text area field

I have been give an older project to work within Metacom Portals that I understood it was known as Rollbase (Event Bridge Infinite Blue). I have the issue of trying to change a text area field value via rbv_api.setFieldValue to my static value but it does not work. There is also a different solution with a different approach that seems to work but the difference is not huge since my solution is even simpler just putting the static value in the set field value (the other solution takes the response from a JSON request).

Check below my implementation and see why it would not work, permissions are all on yes and there is no default value overwriting it. When I print before and after setting the value it shows null for both. The value to be entered is static in the formula. No other errors.

Formula: rbv_api.setFieldValue("TEST_Operation", {!id}, "Text_Test", "TEST");

Model don’t load in Forge Viewer – always gets OBJECT_TREE_UNAVAILABLE_EVENT

I’m working on a 3-legged application where I list the different models available in my hub and load both the viewer and the selected model.

In general, everything works fine except for certain models. Every time I try to load one of those problematic models, I get the following error.
enter image description here

I’m using the OBJECT_TREE_CREATED_EVENT, but it never gets triggered. Instead, I always hit the OBJECT_TREE_UNAVAILABLE_EVENT.

I’ve tried different approaches when initializing the viewer, but none of them work.

For context, I can access the model through ACC, and when I check the object count, it returns over 29 million objects.

enter image description here

Could this issue be related to the extremely high number of objects? And if so, is there any way to work around or solve this?

Model won’t load in Forge Viewer – always gets OBJECT_TREE_UNAVAILABLE_EVENT – possible object count issue?

I’m working on a 3-legged application where I list the different models available in my hub and load both the viewer and the selected model.

In general, everything works fine except for certain models. Every time I try to load one of those problematic models, I get the following error.
enter image description here

I’m using the OBJECT_TREE_CREATED_EVENT, but it never gets triggered. Instead, I always hit the OBJECT_TREE_UNAVAILABLE_EVENT.

I’ve tried different approaches when initializing the viewer, but none of them work.

For context, I can access the model through ACC, and when I check the object count, it returns over 29 million objects.

enter image description here

Could this issue be related to the extremely high number of objects? And if so, is there any way to work around or solve this?

How to use sendChecklist for telegram bot?

I send

Request::send('sendChecklist', [
'chat_id' => 'my int id',
'checklist' => json_encode([
    'title' => 'qwerty',
    'tasks' => [
        [
            'id' => 1,
            'text' => 'a',
        ],
        [
            'id' => 2,
            'text' => 'b',
        ]
    ],
]);

via https://github.com/php-telegram-bot/core longman/telegram-bot
comment line in Request::send() before (because this is new feature)

//        self::ensureValidAction($action);

And get response:

LongmanTelegramBotEntitiesServerResponse {#56
  +bot_username: "my bot username"
  +raw_data: array:3 [
    "ok" => false
    "error_code" => 400
    "description" => "Bad Request: PREMIUM_ACCOUNT_REQUIRED"
  ]

Why?
I am premium user.

evaluate php pdo wrapper class created by coding and security point of view [closed]

I have created following php PDO wrapper class with the help of google and other some websites and my little knowledge.

I will use this for less coding work without change whole previous coded websites and to replace my previous mysqli wrapper class and keep same structure for my previous websites created with mysqli wrapper class and add pdo with prepared statements and more security in those websites.

I want to know

-  will it be good php pdo wrapper or not? 
-  will it cover secured functions ?  

Providing code with some usage examples

<?php
 define('HST', 'localhost'); // Your database host
 define('USR', 'root');      // Your database username
 define('PWD', '');          // Your database password
 define('DBN', 'test_db');   // Your database name
 define('SEND_ERRORS_TO', ''); // e.g., '[email protected]'
 define('DEFAULT_TIMEZONE', 'Asia/Kolkata');

/* ^^ can be defined in different file and can be included that file here. */

 date_default_timezone_set(DEFAULT_TIMEZONE);


class DB {
    private $host;
    private $dbName;
    private $user;
    private $password;
    private $charset;
    private $pdo;
    private $queryCount = 0;
    private $errorEmailRecipient = SEND_ERRORS_TO;

    /**
    * Constructor: Connect to a given MySQL server.
    *
    * Usage Example:
    * $database = new DB(HST, DBN, USR, PWD, 'utf8mb4');
    *
    * @param string $host The database host (e.g., 'localhost').
    * @param string $dbName The database name.
    * @param string $user The database username.
    * @param string $password The database password.
    * @param string $charset The character set (default: 'utf8mb4').
    */
    public function __construct($host = HST, $dbName = DBN, $user = USR, $password = PWD, $charset = 'utf8mb4') {
    $this->host = $host;
    $this->dbName = $dbName;
    $this->user = $user;
    $this->password = $password;
    $this->charset = $charset;

    $dsn = "mysql:host={$this->host};dbname={$this->dbName};charset={$this->charset}";
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, // Throw exceptions on errors
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,     // Default fetch mode to associative array
        PDO::ATTR_EMULATE_PREPARES   => false,                // Disable emulation for better security and performance
    ];

    try {
        $this->pdo = new PDO($dsn, $this->user, $this->password, $options);
    } catch (PDOException $e) {
        $errorMessage = "Database connection failed: " . $e->getMessage();
        error_log($errorMessage); // Log the error
        $this->send_error_email("Database Connection Error", $errorMessage);
        die($errorMessage); // Terminate script execution
    }
  }

     /**
     * Execute arbitrary SQL queries (SELECT, INSERT, UPDATE, DELETE, etc.).
     * This function uses prepared statements to prevent SQL injection.
     *
     * Usage Example:
     * $stmt = $database->execute_query("SELECT * FROM users WHERE id = ?", [1]);
     * if ($stmt) {
     * $user = $stmt->fetch();
     * print_r($user);
     * }
     *
     * $stmt = $database->execute_query("INSERT INTO products (name, price) VALUES (?, ?)", ["Laptop", 1200.50]);
     * if ($stmt->rowCount() > 0) {
     * echo "Product added successfully!";
     * }
     *
     * @param string $sql The SQL query string.
     * @param array $params An associative or indexed array of parameters to bind to the query.
     * @return PDOStatement|false Returns the PDOStatement object on success, or false on failure.
     */
    public function execute_query($sql, $params = []) {
    try {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        $this->queryCount++;
        return $stmt;
    } catch (PDOException $e) {
        $errorMessage = "Query execution failed: " . $e->getMessage() . " SQL: " . $sql . " Params: " . json_encode($params);
        error_log($errorMessage);
        $this->send_error_email("Database Query Error", $errorMessage);
        return false;
    }
}


     /**
     * Retrieve the number of rows from a table based on multiple WHERE clauses.
     *
     * Usage Example:
     * $conditions = [
     * 'status' => 'active',
     * 'category_id' => 5
     * ];
     * $active_products_count = $database->num_rows('products', $conditions);
     * OR $active_products_count = $database->num_rows('products', ['status' => 'active','category_id' => 5]);
     * echo "Number of active products: " . $active_products_count;
     *
     * @param string $table The name of the table.
     * @param array $conditions An associative array of column => value pairs for the WHERE clause.
     * @return int The number of rows matching the conditions, or 0 on error.
     */
    public function num_rows($table, $conditions = []) {
    $sql = "SELECT COUNT(*) FROM `{$table}`";
    $params = [];
    $whereClause = $this->build_where_clause($conditions, $params);

    $sql .= $whereClause;

    $stmt = $this->execute_query($sql, $params);
    if ($stmt) {
        return (int) $stmt->fetchColumn();
    }
    return 0;
 }


    /**
     * Retrieve the query results in a single array.
     * This function now accepts table name, conditions, selected columns, order by, group by, and limit.
     *
     * Usage Example:
     * // Fetch all users
     * $allUsers = $database->get_results('users');
     *
     * // Fetch active users, selecting specific columns
     * $activeUsers = $database->get_results('users', ['status' => 'active'], ['id', 'name', 'email']);
     * foreach ($activeUsers as $user) {
     * echo $user['name'] . " - " . $user['email'] . "<br>";
     * }
     *
     * // Fetch products with price greater than 100, ordered by price descending, limited to 5
     * $expensiveProducts = $database->get_results('products', ['price >' => 100], ['name', 'price'], 'price DESC', null, 5);
     *
     * // Fetch the latest user added (by ID)
     * $latestUser = $database->get_results('users', [], ['id', 'name'], 'id DESC', null, 1);
     * if (!empty($latestUser)) {
     * echo "Latest user: " . $latestUser[0]['name'];
     * }
     *
     * // Get count of users by role
     * $userRoleCounts = $database->get_results('users', [], ['role', 'COUNT(id) as user_count'], '', 'role');
     * foreach ($userRoleCounts as $roleCount) {
     * echo "Role: " . $roleCount['role'] . ", Count: " . $roleCount['user_count'] . "<br>";
     * }
     *
     * // Example with OR condition:
     * $conditions_or = [
     * 'status' => 'active', // This will be ANDed
     * '_OR_' => [           // This whole block will be ORed together
     * ['role' => 'admin'],
     * ['role' => 'editor', 'department' => 'marketing'] // This is (role = 'editor' AND department = 'marketing')
     * ]
     * ];
     * $users_complex = $database->get_results('users', $conditions_or, ['name', 'email', 'role', 'department']);
     *
     * @param string $table The name of the table to retrieve data from.
     * @param array $conditions An associative array of column => value pairs for the WHERE clause.
     * Supports operators like 'column >', 'column <', 'column LIKE', 'column IN', etc.
     * @param array $selectColumns An array of column names to select (default: ['*'] for all columns).
     * @param string $orderBy An ORDER BY clause (e.g., 'column_name ASC', 'column_name DESC').
     * @param string $groupBy A GROUP BY clause (e.g., 'column_name', 'column1, column2').
     * @param int|null $limit A LIMIT clause (e.g., 10).
     * @param int $fetch_style The PDO fetch style (e.g., PDO::FETCH_ASSOC, PDO::FETCH_OBJ).
     * @return array An array of query results. Returns an empty array on no results or error.
     */

     public function get_results($table, $conditions = [], $selectColumns = ['*'], $orderBy = '', $groupBy = '', $limit = null, $fetch_style = PDO::FETCH_ASSOC)  {
    $selectClause = implode(", ", $selectColumns);
    $params = [];
    $whereClause = $this->build_where_clause($conditions, $params);

    $sql = "SELECT {$selectClause} FROM `{$table}`{$whereClause}";

    if (!empty($groupBy)) {
        $sql .= " GROUP BY {$groupBy}";
    }

    if (!empty($orderBy)) {
        $sql .= " ORDER BY {$orderBy}";
    }

    if ($limit !== null && is_int($limit) && $limit > 0) {
        $sql .= " LIMIT {$limit}";
    }

    $stmt = $this->execute_query($sql, $params);
    if ($stmt) {
        return $stmt->fetchAll($fetch_style);
    }
    return [];
 }


     /**
     * Determine if one value or an array of values contain common MySQL function calls.
     * This is a basic check and should not replace prepared statements for security.
     *
     * Usage Example:
     * if ($database->contains_mysql_functions($_GET['order_by'])) {
     * echo "Potential SQL injection attempt detected!";
     * } else {
     * // Proceed with using $_GET['order_by'] in ORDER BY clause (carefully!)
     * }
     *
     * @param mixed $value The string or array of strings to check.
     * @return bool True if any common MySQL function is found, false otherwise.
     */
    public function contains_mysql_functions($value) {
    $functions = [
        'SLEEP', 'BENCHMARK', 'UNION', 'SELECT', 'INSERT', 'UPDATE', 'DELETE',
        'DROP', 'TRUNCATE', 'ALTER', 'CREATE', 'GRANT', 'REVOKE', 'RENAME',
        'LOAD_FILE', 'OUTFILE', 'INFILE', '@@', 'CONCAT', 'CAST', 'CONVERT',
        'ASCII', 'CHAR', 'UNHEX', 'HEX', 'MID', 'SUBSTRING', 'LEFT', 'RIGHT',
        'IF', 'CASE', 'AND', 'OR', 'XOR', 'NOT', 'NULL', 'VERSION', 'DATABASE',
        'USER', 'CURRENT_USER', 'SYSTEM_USER', 'SESSION_USER', 'SCHEMA',
        'INFORMATION_SCHEMA', 'MYSQL.USER', 'PASSWORD', 'MD5', 'SHA1', 'SHA2',
        'AES_ENCRYPT', 'AES_DECRYPT', 'FROM_UNIXTIME', 'UNIX_TIMESTAMP',
        'GROUP_CONCAT', 'ORDER BY', 'GROUP BY', 'HAVING', 'LIMIT', 'OFFSET'
    ];

    $regex = '/b(' . implode('|', $functions) . ')b/i';

    if (is_array($value)) {
        foreach ($value as $val) {
            if (preg_match($regex, $val)) {
                return true;
            }
        }
    } else {
        if (preg_match($regex, $value)) {
            return true;
        }
    }
    return false;
  }


    /**
    * Check if a table exists in the current database.
    *
    * Usage Example:
    * if ($database->table_exists('users')) {
    * echo "Table 'users' exists.";
    * } else {
    * echo "Table 'users' does not exist.";
    * }
    *
    * @param string $tableName The name of the table to check.
    * @return bool True if the table exists, false otherwise.
    */
    public function table_exists($tableName) {
    $sql = "SHOW TABLES LIKE ?";
    $stmt = $this->execute_query($sql, [$tableName]);
    return $stmt && $stmt->rowCount() > 0;
  }


      /**
      * Execute an INSERT query from values that define table, field names, and field values.
      *
      * Usage Example:
      * $new_user_data = [
      * 'name' => 'Alice Smith',
      * 'email' => '[email protected]',
      * 'status' => 'active'
      * ];
      * if ($database->insert('users', $new_user_data)) {
      * echo "New user inserted successfully!";
      * echo "Last Insert ID: " . $database->last_insert_id();
      * } else {
      * echo "Failed to insert new user.";
      * }
      *
      * @param string $table The table name.
      * @param array $data An associative array of column => value pairs to insert.
      * @return bool True on success, false on failure.
      */
     public function insert($table, $data){
    if (empty($data)) {
        return false;
    }

    $columns = implode(", ", array_keys($data));
    $placeholders = implode(", ", array_fill(0, count($data), '?'));
    $params = array_values($data);

    $sql = "INSERT INTO `{$table}` ({$columns}) VALUES ({$placeholders})";
    $stmt = $this->execute_query($sql, $params);
    return $stmt !== false;
  }


   /**
    * Execute an INSERT MULTI query for inserting multiple rows at once.
    *
    * Usage Example:
    * $products_to_add = [
    * ['name' => 'Keyboard', 'price' => 75.00, 'category_id' => 1],
    * ['name' => 'Mouse', 'price' => 25.50, 'category_id' => 1],
    * ['name' => 'Monitor', 'price' => 299.99, 'category_id' => 2]
    * ];
    * if ($database->insert_multi('products', $products_to_add)) {
    * echo "Multiple products inserted successfully!";
    * } else {
    * echo "Failed to insert multiple products.";
    * }
    *
    * @param string $table The table name.
    * @param array $dataArray An array of associative arrays, where each inner array represents a row to insert.
    * @return bool True on success, false on failure.
    */
    public function insert_multi($table, $dataArray) {
    if (empty($dataArray) || !is_array($dataArray[0])) {
        return false;
    }

    $columns = implode(", ", array_keys($dataArray[0]));
    $placeholders = "(" . implode(", ", array_fill(0, count($dataArray[0]), '?')) . ")";

    $values = [];
    $params = [];
    foreach ($dataArray as $row) {
        $values[] = $placeholders;
        $params = array_merge($params, array_values($row));
    }

    $sql = "INSERT INTO `{$table}` ({$columns}) VALUES " . implode(", ", $values);
    $stmt = $this->execute_query($sql, $params);
    return $stmt !== false;
 }

    /**
    * Execute an UPDATE query from values that define table, field names, field values, and conditions.
    *
    * Usage Example:
    * $update_data = ['status' => 'inactive', 'last_login' => date('Y-m-d H:i:s')];
    * $conditions = ['id' => 1];
    * if ($database->update('users', $update_data, $conditions)) {
    * echo "User ID 1 updated successfully!";
    * } else {
    * echo "Failed to update user ID 1.";
    * }
    *
    * @param string $table The table name.
    * @param array $data An associative array of column => new_value pairs to update.
    * @param array $conditions An associative array of column => value pairs for the WHERE clause.
    * @return bool True on success, false on failure.
    */
    public function update($table, $data, $conditions) {
    if (empty($data) || empty($conditions)) {
        return false;
    }

    $setParts = [];
    $params = [];
    foreach ($data as $column => $value) {
        $setParts[] = "`{$column}` = ?";
        $params[] = $value;
    }
    $setClause = implode(", ", $setParts);

    $whereClause = $this->build_where_clause($conditions, $params);

    $sql = "UPDATE `{$table}` SET {$setClause} {$whereClause}";
    $stmt = $this->execute_query($sql, $params);
    return $stmt !== false;
  }

    /**
    * Execute a DELETE query from values that define table and conditions.
    *
    * Usage Example:
    * $conditions = ['status' => 'inactive', 'last_login <' => '2023-01-01'];
    * if ($database->delete('users', $conditions)) {
    * echo "Inactive users deleted successfully!";
    * } else {
    * echo "Failed to delete inactive users.";
    * }
    *
    * @param string $table The table name.
    * @param array $conditions An associative array of column => value pairs for the WHERE clause.
    * Supports operators like 'column >', 'column <', 'column LIKE', etc.
    * @return bool True on success, false on failure.
    */
    public function delete($table, $conditions) {
    if (empty($conditions)) {
        // Prevent accidental full table deletion without conditions
        error_log("Attempted to delete from table '{$table}' without conditions. Operation aborted.");
        $this->send_error_email("Security Alert: Unconditional Delete Attempt", "Attempted to delete from table '{$table}' without conditions.");
        return false;
    }

    $params = [];
    $whereClause = $this->build_where_clause($conditions, $params);

    $sql = "DELETE FROM `{$table}` {$whereClause}";
    $stmt = $this->execute_query($sql, $params);
    return $stmt !== false;
 }

     /**
     * Helper function to build the WHERE clause string and populate parameters array.
     * Supports AND conditions at the top level and one special '_OR_' group.
     * The '_OR_' group should contain an array of condition sets, where each set
     * is ANDed internally, and then these sets are ORed together.
     *
     * @param array $conditions An associative array of column => value pairs for the WHERE clause.
     * Can include a special '_OR_' key for OR conditions.
     * @param array $params Reference to the main parameters array to add new values.
     * @return string The WHERE clause string (e.g., " WHERE `column` = ? AND (`other_column` = ? OR `another_column` = ?)").
    */
    private function build_where_clause($conditions, &$params)  {
    $whereParts = [];
    $orGroupClauses = [];

    foreach ($conditions as $key => $value) {
        if ($key === '_OR_' && is_array($value)) {
            // This is an OR group, process each sub-condition set
            $currentOrGroupParts = [];
            foreach ($value as $orConditionSet) {
                if (is_array($orConditionSet)) {
                    $subConditionParts = [];
                    foreach ($orConditionSet as $subColumn => $subValue) {
                        // Build each individual condition within the OR group
                        $operator = '=';
                        $field = $subColumn;
                        $isBinary = false;

                        if (strpos(strtoupper(trim($subColumn)), 'BINARY ') === 0) {
                            $isBinary = true;
                            $field = substr(trim($subColumn), 7);
                        }

                        if (preg_match('/(.*?)s*(<|>|<=|>=|!=|<>|LIKE|NOT LIKE|IN|NOT IN|IS NULL|IS NOT NULL)$/i', $field, $matches)) {
                            $field = trim($matches[1]);
                            $operator = strtoupper(trim($matches[2]));
                        }

                        $field_escaped = "`{$field}`";
                        if ($isBinary) {
                            $field_escaped = "BINARY {$field_escaped}";
                        }

                        if ($operator === 'IN' || $operator === 'NOT IN') {
                            if (is_array($subValue)) {
                                $placeholders = $this->in_clause_helper($field, $subValue, $params);
                                $subConditionParts[] = "{$field_escaped} {$operator} ({$placeholders})";
                            } else {
                                error_log("Invalid value for IN/NOT IN clause within OR group for column '{$field}'. Value must be an array.");
                                continue;
                            }
                        } elseif ($operator === 'IS NULL' || $operator === 'IS NOT NULL') {
                            $subConditionParts[] = "{$field_escaped} {$operator}";
                        } else {
                            $subConditionParts[] = "{$field_escaped} {$operator} ?";
                            $params[] = $subValue;
                        }
                    }
                    if (!empty($subConditionParts)) {
                        $currentOrGroupParts[] = "(" . implode(" AND ", $subConditionParts) . ")";
                    }
                } else {
                    error_log("Invalid OR condition set format. Expected an array of associative arrays.");
                }
            }
            if (!empty($currentOrGroupParts)) {
                $orGroupClauses[] = "(" . implode(" OR ", $currentOrGroupParts) . ")";
            }
        } else {
            // This is a regular AND condition
            $operator = '=';
            $field = $key; // $key is the column name
            $isBinary = false;

            if (strpos(strtoupper(trim($key)), 'BINARY ') === 0) {
                $isBinary = true;
                $field = substr(trim($key), 7);
            }

            if (preg_match('/(.*?)s*(<|>|<=|>=|!=|<>|LIKE|NOT LIKE|IN|NOT IN|IS NULL|IS NOT NULL)$/i', $field, $matches)) {
                $field = trim($matches[1]);
                $operator = strtoupper(trim($matches[2]));
            }

            $field_escaped = "`{$field}`";
            if ($isBinary) {
                $field_escaped = "BINARY {$field_escaped}";
            }

            if ($operator === 'IN' || $operator === 'NOT IN') {
                if (is_array($value)) {
                    $placeholders = $this->in_clause_helper($field, $value, $params);
                    $whereParts[] = "{$field_escaped} {$operator} ({$placeholders})";
                } else {
                    error_log("Invalid value for IN/NOT IN clause for column '{$field}'. Value must be an array.");
                    continue;
                }
            } elseif ($operator === 'IS NULL' || $operator === 'IS NOT NULL') {
                $whereParts[] = "{$field_escaped} {$operator}";
            } else {
                $whereParts[] = "{$field_escaped} {$operator} ?";
                $params[] = $value;
            }
        }
    }

    // Combine all AND parts and the OR group clauses
    $finalWhereParts = array_merge($whereParts, $orGroupClauses);

    return empty($finalWhereParts) ? '' : " WHERE " . implode(" AND ", $finalWhereParts);
  }


    /**
    * Truncate a table (removes all rows and resets auto-increment counter).
    *
    * Usage Example:
    * if ($database->truncate_table('logs')) {
    * echo "Table 'logs' truncated successfully!";
    * } else {
    * echo "Failed to truncate table 'logs'.";
    * }
    *
    * @param string $tableName The name of the table to truncate.
    * @return bool True on success, false on failure.
    */
    public function truncate_table($tableName) {
    try {
        $sql = "TRUNCATE TABLE `{$tableName}`";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();
        $this->queryCount++;
        return true;
    } catch (PDOException $e) {
        $errorMessage = "Failed to truncate table '{$tableName}': " . $e->getMessage();
        error_log($errorMessage);
        $this->send_error_email("Database Truncate Error", $errorMessage);
        return false;
    }
  }


    /**
    * Send email messages with MySQL access and query errors.
    * Requires mail() function to be configured on the server.
    *
    * Usage Example (internal, called by class methods on error):
    * $this->send_error_email("Database Connection Error", "Could not connect to MySQL.");
    *
    * @param string $subject The subject of the email.
    * @param string $message The body of the email.
    * @return bool True if the email was sent successfully, false otherwise.
    */
   public function send_error_email($subject, $message) {
    if ($this->errorEmailRecipient === null || $this->errorEmailRecipient === '') {
        // No recipient set, so don't send email
        return false;
    }

    $headers = 'From: [email protected]' . "rn" .
               'Reply-To: [email protected]' . "rn" .
               'X-Mailer: PHP/' . phpversion();

    // In a real application, you might want to format the message better
    // and include more context like $_SERVER data, stack trace, etc.
    $fullMessage = "An error occurred in your application:nn" .
                   "Subject: " . $subject . "n" .
                   "Message: " . $message . "nn" .
                   "Timestamp: " . date('Y-m-d H:i:s') . "n" .
                   "Script: " . ($_SERVER['PHP_SELF'] ?? 'N/A') . "n" .
                   "Referer: " . ($_SERVER['HTTP_REFERER'] ?? 'N/A') . "n" .
                   "User Agent: " . ($_SERVER['HTTP_USER_AGENT'] ?? 'N/A');

    return mail($this->errorEmailRecipient, $subject, $fullMessage, $headers);
  }

    /**
    * Set the email recipient for error notifications.
    *
    * Usage Example:
    * $database->set_error_email_recipient('[email protected]');
    *
    * @param string $email The email address to send error notifications to.
    */
    public function set_error_email_recipient($email) {
    $this->errorEmailRecipient = $email;
  }

    /**
    * Display the total number of queries performed during all instances of the class.
    *
    * Usage Example:
    * echo "Total queries executed: " . $database->get_query_count();
    *
    * @return int The total number of queries executed.
    */
    public function get_query_count() {
      return $this->queryCount;
   }


   /**
   * Checks if a record exists in a table based on given conditions.
   * This function securely uses prepared statements via num_rows.
   *
   * Usage Example:
   * $check_user = ['user_email' => '[email protected]', 'user_id' => 48];
   * $exists = $database->exists('users', $check_user);
   *
   * @param string $table The database table name.
   * @param array $conditions An associative array of column name => column value to match.
   * @return bool True if the record exists, false otherwise.
   */
   public function exists($table = '', $conditions = []) {
    if (empty($table) || empty($conditions)) {
        return false;
    }
    return $this->num_rows($table, $conditions) > 0;
  }


   /**
   * Returns the number of fields (columns) in the result set of a query.
   *
   * Usage Example:
   * $stmt = $database->execute_query("SELECT id, name, email FROM users LIMIT 1");
   * $numFields = $database->get_num_fields($stmt); // Output: 3
   *
   * @param PDOStatement|false $stmt The PDOStatement object returned by execute_query.
   * @return int The number of fields, or 0 if statement is invalid.
  */
  public function get_num_fields($stmt) {
    if ($stmt instanceof PDOStatement) {
        return $stmt->columnCount();
    }
    return 0;
  }

  /**
  * Returns an array of field (column) names from the result set of a query.
  *
  * Usage Example:
  * $stmt = $database->execute_query("SELECT id, name, email, status, created_at FROM users LIMIT 1");
  * $fieldNames = $database->get_list_fields($stmt); // Output: ['id', 'name', 'email', 'status', 'created_at']
  *
  * @param PDOStatement|false $stmt The PDOStatement object returned by execute_query.
  * @return array An array of column names, or an empty array if statement is invalid.
  */
  public function get_list_fields($stmt)  {
    $fieldNames = [];
    if ($stmt instanceof PDOStatement) {
        for ($i = 0; $i < $stmt->columnCount(); $i++) {
            $meta = $stmt->getColumnMeta($i);
            $fieldNames[] = $meta['name'];
        }
    }
    return $fieldNames;
  }

 } /* end of class DB */

Expecting your valuable suggestions on it.

in my laravel project cant return but i can echo [closed]

If I try to return a view I can’t get a response

 <?php
    
    use AppHttpControllersProfileController;
    use IlluminateSupportFacadesRoute;
    
    Route::get('/', function () {
        // echo view('welcome'); its working`your text`
        return view('welcome'); // not working
    });

if i make return echo its working i can see it on my localhost and see it in the network response place. Cant return a blade or variable.

I ask AI and its always say clear with artisan command or delete and clone it i tried everything but not working but on my friends computer its working i think the error is for my computer but i don’t know why?

SELECT clause in php-activeRecord not working

I have this query without SELECT clause

$itemList = Job::find('all', array('conditions' => array('jobs.deleted = ?' . $sql_conditional_fragment, 0),
    'include'    => array('job_type','client_upload' => array('outer_client_user'), 'outer_client_offer', 'user', 'retailer', 'job_status'),
    'joins'      => '
    LEFT JOIN client_uploads cu ON cu.id = jobs.client_upload_id 
    LEFT JOIN users ON users.id = jobs.user_id 
    LEFT JOIN job_statuses js ON js.id = jobs.job_status_id
    LEFT JOIN retailers r ON r.id = jobs.retailer_id',
    'order'      => $sort,
    'limit'      => $limit,
    'offset'     => $offset
    ));

The actual table names

jobs, job_types, job_statuses, retailers, users, client_uploads

outer_client_user and outer_client_offer are not actual table names in the DB.

These are tables from diff DB with names – users and offer. But both have a corresponding Model with actual table name and connection name defined.

can any help me with selecting only handful of columns from all the tables?

What I tried:

'select' => 
  'jobs.id, jobs.legibility, jobs.num_items, jobs.total_spent,
   jobs.processed_at, jobs.created_at, jobs.approved, 
   users.first_name, users.last_name, outer_client_user.user_first_name, 
   outer_client_user.user_last_name, job_types.name,
   job_types.abbreviation, r.name, outer_client_offer.offer_name, js.name'

How to query parts of a PHP variable separately?

I am making a search bar in HTML/PHP/JS/MySQL. With the code I have right now, if someone enters the value book 1: conquest into the search bar, the SQL query looks for a column value of ALL the words in the search bar.

But, If someone spells a word wrong in the search bar, or enters Conquest instead of conquest, they will get the dreaded no results found result. But, every other search bar I’ve came across doesn’t suffer from this problem. Is it possible to change this?

<?php
  define("DB_HOST", "localhost");
  define("DB_NAME", "officiallasereyeswebsite");
  define("DB_CHARSET", "utf8");
  define("DB_USER", "root");
  define("DB_PASSWORD", "");
  $search = $_GET['search'];
  $pdo = new PDO(
    "mysql:host=".DB_HOST.";charset=".DB_CHARSET.";dbname=".DB_NAME,
    DB_USER, DB_PASSWORD, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);

  $stmt = $pdo->prepare("SELECT * FROM `items` WHERE `item` LIKE ? OR `code` LIKE ?");
  $stmt->execute(["%".$search."%", "%".$search."%"]);
  $results = $stmt->fetchAll();
  if (isset($_GET["ajax"])) { echo json_encode($results); }
?>

Simple way to convert generated blob from docx.js to PDF?

I created a website (html+javascript) which can generate a report with docx.js pressing the “Download DOCX” button.

You can see the current website here:
https://tkfdm.github.io/FAIR-Data-Assessment-Tool/

And the index.html here (line 1310~1569):
https://github.com/tkfdm/FAIR-Data-Assessment-Tool/blob/b5d1e6e440573bb2e9f537f22bc324f94d720e54/index.html

At the end – after the whole document is constructed – it simply creates the blob/docx file:

        Packer.toBlob(doc).then(blob => {
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = `${getTimestampString()}-fair-assessment-report.docx`;
            a.click();
            URL.revokeObjectURL(url);

My question is now if there is an easy way to transform this docx/blob into a pdf file. I know, that docx.js itself doesn’t offer this functionality, but are there other frameworks?

Is it possible to mock vite’s mode environment variable inside of Cypress tests?

In my application, we are applying a different header color based on the environment the application is run in. To do this, I am using the env variable MODE set by my vite config.

  useEffect(() => {
    if (import.meta.env.MODE === 'production') {
      import('./Header.prod.css')
    } else if (import.meta.env.MODE === 'beta') {
      import('./Header.beta.css')
    } else {
      import('./Header.dev.css')
    }
  }, [])

I was able to confirm that the above code works to set the color on the header.

However, I would like to write a Cypress Component visual regression test to make sure that the correct color is being set based on the value of import.meta.env.MODE, and when I try to set the value of MODE in my Cypress test the value of import.meta.env.MODE does not change.

  it(
    'should have beta styling when vite mode is beta',
    {
      env: {
        MODE: 'production'
      }
    },
    () => {
      cy.mount(<Header />)
    }
  )

Is there any way to set the value of import.meta.env variables inside of Cypress tests (i.e. not setting it at build time) so that I can test that the correct header color is being applied?

How do I make the text box grow once the user has reached the end of the text box in CSS, Javascript and HTML [closed]

I want my text box to grow as the user types in it.

I already tried some suggestions but they don’t seem to be working.
The rest of this is placeholder text so I don’t have to type anymore: This is a block of placeholder text intended to fill space while the final content is being written. It doesn’t carry specific meaning but gives a clear sense of how real content will look once it’s added. Designers and developers often use placeholder text to test layouts, check font styles, or preview how a page will appear. It helps keep the creative process moving without waiting for complete text to be ready.

You can use this kind of generic content in websites, brochures, documents, or anywhere a visual draft is needed. It can also help clients focus on the structure and design without being distracted by real content. Placeholder text like this allows for flexibility and clarity during the early stages of design and development.

Feel free to adjust the length, tone, or structure of this text to better match the project you’re working on. Whether you’re creating a blog, an app, a presentation, or even a printed flyer, having realistic placeholder text helps everything feel more complete. Use it to explore different styles, test formatting, or collaborate with others before finalizing the content. Why does this text have to be so long I just want to ask a question and gain reputation!

How to redirect to a custom Thank You page after checkout now that additional scripts is deprecated?

I’m currently working on a Shopify store using the Basic plan.

Until now, I was redirecting users to a custom Thank You page after checkout using the “Additional Scripts” section available in the Checkout Settings.

window.location.href = "https://myshop.com/thank-you"

This worked perfectly for redirecting users after order completion.

However, Shopify has announced that Additional Scripts is being deprecated, and they recommend migrating to Custom Web Pixels for post-checkout tracking and logic.

I implemented a custom web pixel and was able to successfully receive checkout events like checkout_completed. However, I’ve hit a major blocker:

Redirection to a custom Thank You page doesn’t work from the web pixel script.

After some research, I found that Shopify Web Pixels run inside a sandboxed iframe, so the script cannot access or control the parent DOM — meaning no redirection is possible using window.top or window.location.

What is the correct or recommended way to implement a custom Thank You page (or redirect to one) after checkout in Shopify, now that Additional Scripts is deprecated?

Any help, workarounds, or official documentation links would be greatly appreciated!

I tried web pixel to listen the customer’s checkout event and added redirected logic

analytics.subscribe('checkout_completed', (event) => {

  console.log("Checkout completed event received:", event);
  window.top.location.href = "https://myshop.com/thank-you";

}

Expected Result: Need to redirect to custom thank you page URL

jquery data table features not working with dynamic table

My datatable is working fine, all the features like pagination, sorting, searching are working with static table data content.
But when I fetch data from database and render in datatable features like pagination, sorting, searching and other CSS are not working.

My view page code::

<div class="table-responsive">
                            <table id="example" class="table table-striped table-bordered" style="width:100%">
                                <thead>
                                    
                                    <tr>
                                        <th
                                        >Index</th>
                                        <th>Name</th>
                                        <th data-orderable="false">Image</th>
                                        <th data-orderable="false">Edit</th>
                                        <th data-orderable="false">Delete</th>
                                    </tr>
                                </thead>

                                <tbody>
                                </tbody>
                                
                                <tfoot>
                                    <tr>
                                        <th>Index</th>
                                        <th>Name</th>
                                        <th>Image</th>
                                        <th>Edit</th>
                                        <th>Delete</th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                        

<script>
$(document).ready(function () {

    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

    $('#example').DataTable();

    fetchproduct();

        function fetchproduct() {
            $.ajax({
                type: "GET",
                url: "/fetchproducts",
                dataType: "json",
                success: function (response) {
                    $('tbody').html("");
                    $.each(response.products, function (key, item) {
                        $('tbody').append('<tr>
                            <td>' + item.id + '</td>
                            <td>'+ item.name +  '</td>
                            <td> <img src="images/'+item.image_path+'"> </td>
                            <td><button type="button" value="' + item.id + '" class="btn btn-primary editbtn btn-sm">Edit</button></td>
                            <td><button type="button" value="' + item.id + '" class="btn btn-danger deletebtn btn-sm">Delete</button></td>
                        </tr>');
                    });
                }
            });
        }
});
</script>

</body>
</html>

Controller code and route::

public function fetchproduct()
    {
        $products = Product::all();
        return response()->json([
            'products'=>$products,
        ]);
    }
    
// route
Route::get('products', [ProductController::class, 'index'])->name('products.index');
Route::post('products', [ProductController::class, 'store'])->name('products.store');
Route::get('fetchproducts', [ProductController::class, 'fetchproduct']);

When I load the datatable, all the data is rendered at once. Pagination feature is not working. Also sorting and searching are also not working. Why is it so?