-
Who's Online 0 Members, 0 Anonymous, 528 Guests (See full list)
- There are no registered users currently online
All Activity
- Today
-
Thank you much appreciated
-
MoilDob joined the community
- Yesterday
-
You need to unserialise the data. $dbdata = 'a:5:{s:16:"WPFormsDB_status";s:6:"unread";s:4:"Name";s:13:"Lional Hewitt";s:14:"Contact Number";s:10:"0763229844";s:5:"Email";s:22:"[email protected]";s:18:"Comment or Message";s:5:"test2";}'; $data = unserialize($dbdata); echo "Name : {$data['Name']}<br>"; echo "Contact : {$data['Contact Number']}<br>"; // etc Alternatively $dbdata = 'a:5:{s:16:"WPFormsDB_status";s:6:"unread";s:4:"Name";s:13:"Lional Hewitt";s:14:"Contact Number";s:10:"0763229844";s:5:"Email";s:22:"[email protected]";s:18:"Comment or Message";s:5:"test2";}'; $data = unserialize($dbdata); foreach ($data as $key => $value) { echo "<b>$key</b> : $value<br>"; }
-
Hi I have this entry in a database from wpforms a:5:{s:16:"WPFormsDB_status";s:6:"unread";s:4:"Name";s:13:"Lional Hewitt";s:14:"Contact Number";s:10:"0763229844";s:5:"Email";s:22:"[email protected]";s:18:"Comment or Message";s:5:"test2";} From this I want to extract Lional Hewitt, 0763229844, [email protected], and test2 into separate variables. I see each form is referenced by s:13, s:10, s:22, and s:18. Is there someway to splat the string with those values Thank you
-
I have no idea, insufficient information. You need to show the code that executes that query and checks for the number of rows returned
-
Not sure if PHP or SQL problem. Why does my $query = "SELECT * FROM `HAusers` "; give me a record read count of minus 1 when I have 24 records in the BD Table? There are no error messages.
-
Michele1405 joined the community
-
Injar joined the community
-
stufflhd joined the community
-
I am trying to use ChatGPT as the chatbot for my Magento 2 website, and I want to pass product data to it. To do this, I collected all the products and stored them in a JSON file, which I then read to embed the data in the `systemRoleContent` of the system role. However, the issue I am facing is that the JSON file is quite large. { "bot_response": "Error: ChatBot Error: Unexpected API response structure: {\n \"error\": {\n \"message\": \"Request too large for gpt-4o on tokens per min (TPM): Limit 30000, Requested 501140. The input or output tokens must be reduced in order to run successfully. Visit https://platform.openai.com/account/rate-limits to learn more.\",\n \"type\": \"tokens\",\n \"param\": null,\n \"code\": \"rate_limit_exceeded\"\n }\n}\n" } I noticed that there is a function that needs to be added to the API configuration, which allows you to run a query to select products based on keywords found in their names or descriptions that match keywords in the user’s message. The challenge is that users initially may not know the names of the products; they come to the chatbot to discover them. How can I address this issue? This is the code that I am working with right now: <?php namespace MetaCares\Chatbot\Model; use Magento\Framework\App\ObjectManager; class ChatBot { private $authorization; private $endpoint; private $conversationHistory = []; private $productsFile; private $fetchingDateFile; private $didFetchProducts = false; public function __construct() { $this->authorization = 'sk-proj-'; $this->endpoint = 'https://api.openai.com/v1/chat/completions'; $this->productsFile = __DIR__ . '/products.json'; $this->fetchingDateFile = __DIR__ . '/fetching_date.json'; $currentTime = time(); $timeDifferenceSeconds = 24 * 3600; if (!file_exists($this->fetchingDateFile)) { file_put_contents($this->fetchingDateFile, json_encode(['last_fetch_time' => 0])); } $fetchingData = json_decode(file_get_contents($this->fetchingDateFile), true); $lastFetchTime = $fetchingData['last_fetch_time'] ?? 0; if ($currentTime - $lastFetchTime > $timeDifferenceSeconds) { $products = $this->fetchProductsUsingModel(); $productsJson = json_encode($products); file_put_contents($this->productsFile, $productsJson); $fetchingData['last_fetch_time'] = $currentTime; file_put_contents($this->fetchingDateFile, json_encode($fetchingData)); $this->didFetchProducts = true; } $jsonSampleData = file_get_contents($this->productsFile); $systemRoleContent = <<<EOT Nom: Meta Cares Bot Description BOT Meta Cares répond aux questions sur les produits du site et fournit des conseils santé fiables. Tu aides les clients de Meta Cares à faire des choix éclairés tout en offrant un accompagnement personnalisé, sécurisé et adapté à leurs besoins. catalogue Meta Cares {$jsonSampleData} Liste des Sites Référencés : - PubMed : [https://pubmed.ncbi.nlm.nih.gov/](https://pubmed.ncbi.nlm.nih.gov/) - ScienceDirect : [https://www.sciencedirect.com/](https://www.sciencedirect.com/) --- - Génération d’images DALL·E : Désactivée EOT; $this->conversationHistory[] = [ 'role' => 'system', 'content' => $systemRoleContent ]; if (session_status() == PHP_SESSION_NONE) { session_start(); } if (isset($_SESSION['chat_history'])) { $this->conversationHistory = $_SESSION['chat_history']; } } public function fetchProductsUsingModel(): array { return $products; } private function getCategoryNames(array $categoryIds): array { return $categoryNames; } public function sendMessage(string $message): array { try { $this->conversationHistory[] = [ 'role' => 'user', 'content' => $message ]; $data = [ 'model' => 'gpt-4o', 'messages' => array_map(function ($msg) { return [ 'role' => $msg['role'] === 'bot' ? 'assistant' : $msg['role'], 'content' => $msg['content'] ]; }, $this->conversationHistory) ]; $response = $this->makeApiRequest($data); $arrResult = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new \Exception('Invalid API response format'); } if (!isset($arrResult['choices']) || !isset($arrResult['choices'][0]['message']['content'])) { throw new \Exception('Unexpected API response structure: ' . $response); } $assistantResponse = $arrResult['choices'][0]['message']['content']; $this->conversationHistory[] = [ 'role' => 'bot', 'content' => $assistantResponse ]; $_SESSION['chat_history'] = $this->conversationHistory; return [ "conversationHistory" => $_SESSION['chat_history'], 'didFetchProducts' => $this->didFetchProducts, 'response' => $assistantResponse, ]; } catch (\Exception $e) { throw new \Exception('ChatBot Error: ' . $e->getMessage()); } } private function makeApiRequest(array $data): string { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $this->endpoint, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'Authorization: Bearer ' . $this->authorization, ], CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0 ]); $response = curl_exec($ch); if (curl_errno($ch)) { $error = curl_error($ch); curl_close($ch); throw new \Exception('API request failed: ' . $error); } curl_close($ch); return $response; } }
- Last week
-
Fatouse joined the community
-
MiclDob joined the community
-
need access for different account roles on a php page
mac_gyver replied to ianhaney10's topic in PHP Coding Help
the only user data you should store in a session variable upon login should be the user id, to identify WHO the logged in user is. this will either be set or it won't be. you should query on each page request to get any other user data, such as a username, permissions, or role. this is so that any changes made to this other user data takes effect on the very next page request. this will allow you to promote or demote a user without requiring them to logout and back in for the change to take effect. do you really want a situation where you have demoted or banned a user and they can still access a page because their session data says they can? i recommend that you simplify the logic and separate the login test from the user role test. also, to test if a variable is in a set of values, define an array of the permitted values and use in_array() to perform the test. using these suggestions, the logic would become - $page_roles = ['Member','Secretary']; // roles permitted for the current page $user_role = 'Guest'; // default value for a non-logged in user // is there a logged in user if(isset($_SESSION['user_id'])) { // query here to get any other user data, such as the user role, and store it in a regular variable // fake a value $user_role = 'Member'; // $user_role = 'Secretary'; // $user_role = 'Other'; } // logic to determine if the current user can access something on this page if(in_array($user_role,$page_roles)) { // access permitted echo 'permitted'; } // logic to determine if the current user cannot access something on this page if(!in_array($user_role,$page_roles)) { // access denied echo 'denied'; } -
need access for different account roles on a php page
ianhaney10 replied to ianhaney10's topic in PHP Coding Help
Think I just solved it by changing a line to the following if(!isset($_SESSION["account_loggedin"]) || $_SESSION["account_loggedin"] !== true || $_SESSION["account_role"] != 'Member' && $_SESSION["account_role"] != 'Secretary') { -
I have two different user roles, one is Member and the other is Secretary and I need to be able to allow access to a php page if either Member or Secretary is logged in. I originally had the code below which worked if a Member role was logged in <?php session_start(); // If the user is not logged in redirect to the login page... if(!isset($_SESSION["account_loggedin"]) || $_SESSION["account_loggedin"] !== true || $_SESSION["account_role"] != 'Member') { include('includes/baseurl.php'); $title = "Show Diary - The British Rabbit Council"; $pgDesc=""; include ( 'includes/header.php' ); ?> I added the Secretary role to the code but it won't allow me to access the page, I think it's because I'm not logged in as a Member role and am logging as the Secretary role but I need access to the php page if I am logged in as either Member or Secretary The current code I have is below <?php session_start(); // If the user is not logged in redirect to the login page... if(!isset($_SESSION["account_loggedin"]) || $_SESSION["account_loggedin"] !== true || $_SESSION["account_role"] != 'Member' || $_SESSION["account_role"] != 'Secretary') { include('includes/baseurl.php'); $title = "Show Diary - The British Rabbit Council"; $pgDesc=""; include ( 'includes/header.php' ); ?> Can anyone help please, thank you in advance
- Earlier
-
Is pro mysql the best book to learn mysql administration?
gizmola replied to oslon's topic in MySQL Help
I don't know that there is a best book. MySQL has been around for a long time, and due to its origin as an open source database with a GPL license, as well as it's relatively unique pluggable engine, it has been extended and forked. Oracle acquired MySQL and at that point, the original MySQL developer forked the code and created MariaDB. Percona also has a fork. So there are now a variety of flavors of "MySQL" with different features and versioning. Whatever book or resource you might get, you want to be sure it is relatively recent and contains information based on the most recent MySQL releases. If your focus is administration, there is a lot of general use content in that book. A book that is more focused on administration like this one might be better. To be clear, I have no experience with any of these books. If you have used a Udemy account, and you are patient, you can routinely license courses for under $10 US. That might be a cheaper way to get similar training. You might consider starting with youtube and looking for other online resources, and combine that with use of the official MySQL docker instance to experiment and learn. -
The main problem is that you aren't validating the input. Or at least not as far as I can see. Do that, as in validate that the body contains those fields with expected types and doesn't contain anything else, and the question is basically irrelevant...
-
Hi All, I have started fiddling with MERN stack as i was looking for something to progress my knowledge. It has all been raw PHP and i fancied expanding my horizens. I know that this is a PHP forum, but i love the users on here so i am hoping that there is sympathy for me posting here (hope that this post is in the most appropriate channel) I am making a controller where i will write all of my api endpoints. My question is about best practices. Should i be writing the following where i break down what is being passed in: const {first_name, last_name, email, password, isAdmin} = req.body; const user = new User({ first_name, last_name, email, password, isAdmin }); or should i just accept whatever is passed in, like this const user = req.body; const newUser = new User(user); This is my first project so i really am finding my feet. For clarity, this would be an add user function export const addUser = async (req, res) =>{ const user = req.body; const newUser = new User(user); } As always, i appreciate youre responses.
-
I have had a good look through your code and made a few minor changes for better readability, simplicity and understanding. There is so much code in yours when there is really no need for it. I have added some Javascript (as mentioned above) that calculates the total on price changes. I have also made the total field read only to prevent it being changed. You can change that easy in the HTML. Hope it helps. Look through it and learn from it. <!DOCTYPE html> <?php $con = mysqli_connect("localhost", "root", "", "receipt"); $data["product"] = []; $sql = "SELECT * FROM feedetails"; $res = $con->query($sql); if ($res->num_rows > 0) { while ($row = $res->fetch_assoc()) { $data["product"][] = $row; } } if (!$res) { trigger_error('Invalid query: ' . $con->error); } ?> <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.6.1.min.js"></script> <style> html { counter-reset: rows; } tr { counter-increment: rows; } tbody td { border: 1px dotted grey; padding: 0.25rem; } tbody tr td:first-of-type::before { content: counter(rows); display: table-cell; } tfoot td { background: grey; padding: 0.5rem; color: white; } </style> </head> <body> <div class="container mt-5"> <div class="row"> <div class="col-md-12"> <table class='table table-bordered'> <tbody id='table'> <tr class='crow'> <td style='width:150px;'></td> <td style='width:350px;'> <select class="form-control pid" required name="pid[]"> <option value='' price='0'>Select</option> <?php foreach ($data["product"] as $row): ?> <option value='<?= $row["fid"] ?>' price='<?= $row["famount"] ?>'><?= $row["fdescription"] ?></option> <?php endforeach; ?> </select> </td> <td> <input type="text" name="price[]" class="form-control price" required> </td> <td> <input data-action='remove' type='button' value='Remove' class='btn btn-link btn-xs rmv' required /> </td> </tr> </tbody> <tfoot> <tr> <td><input data-action='add' type='button' class='btn btn-link add' value='+Add Row' /></td> <td colspan='2' class='text-right'>Total</td> <td><input type='text' name='grand_total' class='form-control' required readonly /></td> </tr> </tfoot> </table> </div> </div> </div> <script> const d = document; const total = d.querySelector('input[name="grand_total"]'); d.addEventListener('click', e => { if (e.target.classList.contains('btn-link') && e.target.dataset.action === 'add') { let tbody = d.querySelector('tbody#table'); let tr = tbody.querySelector('tr:first-of-type'); let clone = tr.cloneNode(true); clone.querySelector('input[name="price[]"]').value = ''; tbody.appendChild(clone); } if (e.target.classList.contains('btn-link') && e.target.dataset.action === 'remove') { if (d.querySelectorAll('tbody#table tr').length > 1) { let value = e.target.closest('tr').querySelector('input[name="price[]"]').value; d.querySelector('tbody#table').removeChild(e.target.closest('tr')); total.value -= parseFloat(value); } } }); d.addEventListener('keyup', e => { let col = d.querySelectorAll('input[name="price[]"]'); total.value = [...col].map(n => n.value > 0 ? n.value : 0).reduce((a, b) => parseFloat(a) + parseFloat(b), 0); }); $("body").on("change", ".pid", function() { var p = $(this).find(":selected").attr("price"); $(this).closest("tr").find(".price").val(p); }); </script> </body> </html>
-
Hello, I’m Manav Gangwani, an engineer from Bangalore with a deep passion for technology. I’m constantly fascinated by the latest tech innovations and enjoy exploring how they can be used to solve problems and create new opportunities.
-
To ensure that the total is automatically updated without needing to click on the total box, you'll need to use JavaScript to listen for changes in the input fields and update the total dynamically.
-
Here're its table of contents. Can anyone here tell me if there is a better book than this? This book is a huge investment (Costs 50-60$ to me in local currency after taxes, shipping etc.)
-
Not sure I get what you're trying to get out of this, but I would expect a read/while loop should be able to get the two values in each line, append the values to two arrays, do some quick math with a counter to determine "line" things... What have you tried so far, what did you expect it to do, and what did it actually do?
-
U-DLCI,6 C/R,1 EA,1 L-DLCI,4 FECN,1 BECN,1 DE, EA,1 This is a file called table.csv Now, what I what I want is this. The 2nd column values are in bits. bits_per_line=8 Now, I traverse through the file and save the first and second column values into an array. packet_arr=("U-DLCI" "C/R" ....) count_arr=(6 1 1 ...) Now I start a counter that will count if bits_per_line ls over 8, if so, I do a new line. counter=6+1+1 This counter will act upon every line. Then I just print the contents. I can't seem to write a bash shell scripting code for this however, (Even though I have completed tons of udemy courses and made many stuffs).
-
Barand's solution is righ.The issue you're facing is likely because the URL behaves differently depending on whether index.php is explicitly mentioned. The code snippet you provided should work, but it can be simplified for clarity. Here's a refined version: <?php $currentpage = $_SERVER['REQUEST_URI']; if ($currentpage == '/' || $currentpage == '/index.php') { // Code for root or index.php page } else { // Code for other pages } ?>
-
Examples of php scripting projects without laravel?
Moorcam replied to oslon's topic in PHP Coding Help
Here's one simple script that fetches news from a news website. #!/bin/bash # Define the URL of the local news channel NEWS_URL="https://www.localnewschannel.com" # Fetch the HTML content of the news page HTML_CONTENT=$(curl -s "$NEWS_URL") # Extract the headlines using grep and sed HEADLINES=$(echo "$HTML_CONTENT" | grep -oP '(?<=<h2 class="headline">).*?(?=</h2>)') # Display the headlines echo "Latest News Headlines:" echo "$HEADLINES" There's an idea. -
Help Needed with Fetching and Updating Vehicle Data Using API
Moorcam replied to GaneshNaiknavre's topic in PHP Coding Help
The script checks if the mileage and location data are valid before attempting to update the database. If either of these checks fails, the update will be skipped. // Update the database if data is valid if ($api_miles > 0 && $latitude !== null && $longitude !== null) { $update_query = "UPDATE created_jobs SET run_km = IFNULL(run_km, 0) + ?, current_km = IFNULL(current_km, 0) + ?, latitude = ?, longitude = ? WHERE vehicle_no = ?"; $stmt = $mysqli->prepare($update_query); if ($stmt) { $stmt->bind_param("ddsss", $api_miles, $api_miles, $latitude, $longitude, $vehicle_no); if (!$stmt->execute()) { error_log("Failed to execute statement for vehicle_no {$vehicle_no}: " . $stmt->error); } else { error_log("Updated vehicle_no: {$vehicle_no} | KM Added: {$api_miles} | Lat: {$latitude} | Lng: {$longitude}"); } } else { error_log("Failed to prepare statement for vehicle_no {$vehicle_no}: " . $mysqli->error); } } else { error_log("Skipping update for vehicle_no {$vehicle_no} due to invalid data."); } See if that helps. -
How to ECHO which item was found/matched after running "foreach"
Psycho replied to myphp's topic in PHP Coding Help
To be honest, I vacillated between several options. Pretty sure all of these would have worked. if (!empty($foundKeywords)) { if ($foundKeywords) { if (count($foundKeywords)) { if (sizeof($foundKeywords)) { Also considere4d having the function returning a Boolean FALSE if no keywords were found instead of an empty array. But decided that an empty array was simpler. -
How to ECHO which item was found/matched after running "foreach"
gizmola replied to myphp's topic in PHP Coding Help
The code Psycho provided is a fairly standard way of solving this problem. Notice how he made use of the empty() function. Empty works well here, because it will return false if it receives an empty array, and true for anything else. -
MySql (with whatever variations in capitalization you like) is the database server type. mysqli and PDO are php's extensions that allow your php code to communicate with the database server. if you understand what your mysqli based code is doing, you should be able to convert the code. all it's doing is - building an sql query statement. which should be in a php variable, in order to separate the sql as much as possible from the php, and allow you to separate the common php code used or in this case change the database extension being used. there's no difference between the sql query statement for the mysqli or PDO extensions, when using positional ? prepared query place-holders. prepare the sql query. there's no difference in the php syntax for the the mysqli or PDO extensions, except that the connection variable must be (and is usually named) for the extension being used. bind input data/execute the prepared query. If you are using php8.1 or higher, the php syntax for the execute statement is exactly the same. you can then use msyqli's get_result() and fetch_all() methods to fetch all the data from the result set.
-
Can a submit button trigger 2 actions?
singingsands replied to singingsands's topic in PHP Coding Help
For several reasons I prefer to stay with MySQL for this project. How do I switch the autosuggest code from POD to MySQL?
