-
Posts
473 -
Joined
-
Last visited
-
Days Won
12
Everything posted by Strider64
-
PHP Mailer don't function, SMTP Error: Could not authenticate
Strider64 replied to DaryllB's topic in PHP Coding Help
$mail->SMTPSecure = "PHPMailer::ENCRYPTION_STARTTLS"; should be this I believe $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; Incorrect URL <a href='http://localhost/myproject/verify-email.php?token=$verify_token'>Click Me </a> Instead of using md5(rand()) for generating the password, you should use PHP's built-in password hashing functions like password_hash(). You have two calls to the sendemail_verify() function. Remove the first one (before the "send or not?" echo statement) as it is redundant and might lead to confusion. You are using $_POST['password'] as the value for the $verify_token variable. Instead, you should generate a random token using functions like bin2hex(random_bytes($length)). -
I know PDO can look confusing at first, but once you get the hang of using PDO it's so much easier that mysqli in my opinion. Here's your code in PDO though I haven't tested it out. <?php if (isset($_POST['flagged'])) { try { $dsn = "mysql:host=localhost;dbname=$database;charset=utf8mb4"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; $pdo = new PDO($dsn, "root", "", $options); $sql = "UPDATE `reservations` SET flagged = 'Yes' WHERE id = :id"; $stmt = $pdo->prepare($sql); $flaggedId = $_POST['flagged']; $stmt->bindParam(':id', $flaggedId, PDO::PARAM_INT); $stmt->execute(); echo "<style>body {background-color: red;}</style>"; } catch (PDOException $e) { // Handle any errors though not for a production server echo "Error: " . $e->getMessage(); } } Here's a nice link on how to use PDO -> https://phpdelusions.net/pdo I still use that website when I have a brainfart. 🤣
-
The following are the basic steps in doing pagination. // Grab the current page the user is on if (isset($_GET['page']) && !empty($_GET['page'])) { $current_page = urldecode($_GET['page']); } else { $current_page = 1; } $per_page = 1; // Total number of records to be displayed: // Grab Total Pages $total_pages = $gallery->total_pages($total_count, $per_page); /* Grab the offset (page) location from using the offset method */ /* $per_page * ($current_page - 1) */ $offset = $gallery->offset($per_page, $current_page); // Figure out the Links that you want the display to look like $links = new Links($current_page, $per_page, $total_count, $category); // Finally grab the records that are actually going to be displayed on the page $records = $gallery->page($per_page, $offset, 'gallery', $category); and this the actual function/method in grabbing the record(s) to be displayed $sql = 'SELECT * FROM gallery WHERE page =:page AND category =:category ORDER BY id DESC, date_added DESC LIMIT :perPage OFFSET :blogOffset'; $stmt = $this->pdo->prepare($sql); // Prepare the query: $stmt->execute(['page' => $page, 'perPage' => $perPage, 'category' => $category, 'blogOffset' => $offset]); // Execute the query with the supplied data: return $stmt->fetchAll(PDO::FETCH_ASSOC);
-
syntax error unexpected 'public' (t_public)
Strider64 replied to LeonLatex's topic in PHP Coding Help
I remember when I was in college the classes I took required Dreamweaver, but all the instructors would say "Even thought the syllabus and I'm required to show how to use Dreamweaver when you get into the real world ditch Dreamweaver and use a real IDE". That was many moons ago and even back then all the students groaning having to pay for Dreamweaver. 😂 Back then it wasn't subscription based, but we at least received a student discount. -
If you want to keep the login form on the same page, you can modify the code to only redirect when necessary. For example, you can check if the user has submitted the login form and then only redirect them if the login fails. Here's a simple example: if (session_status() == PHP_SESSION_NONE) { session_start(); } if (isset($_POST['submit'])) { // Assuming there's a submit button in the login form // Validate user credentials, and set $_SESSION['logged-in-user'] if successful // ... } else { if (empty($_SESSION['logged-in-user'])) { // Show the login form and any error messages here // ... } else { // Redirect to a different page, or show content for logged-in users // ... } } This code will only show the login form if the user is not logged in and hasn't submitted the form. Once they submit the form and successfully log in, the page will show content for logged-in users or redirect to another page as desired.
-
First of all this is the proper way of doing this line <?php echo '<td><button type="submit" name="status" value="'.htmlspecialchars($value['id']).'">status</button></td>'; ?> Second I don't why you are doing the following? if(!$customer_details) Plus showing how you handle the database connection and how you change the values would be helpful.
-
Well, I hope it is just for practice as that code has a lot of security vulnerabilities to it even if you got all the syntax errors ironed out.
-
Stuck on my next step for quiz app
Strider64 replied to webdeveloper123's topic in Application Design
I have been developing another JavaScript game though I have a Trivia game that is what you are looking for? If you look at the JavaScript either by using inspect or viewing the source code it might give an idea in what direction to take? https://www.fanoflego.com/trivia.php This is the game I have been developing -> https://www.phototechguru.com/hangman/can_you_solve.php that might also help? This GitHub Repository might also help? https://github.com/Strider64/phototechguru though the Trivia game is an older version of it. -
Running PHP Function from 'onclick' Action not working
Strider64 replied to CodeRed-Alpha's topic in PHP Coding Help
You missing the point - JavaScript is Client Side and PHP is Server Side. You need to use AJAX or FETCH have communication between the two. Example: // Add an event listener to the edit form's submit event editForm.addEventListener("submit", async function(event) { // Prevent the default form submit behavior event.preventDefault(); // Create a FormData object from the edit form const formData = new FormData(editForm); console.log("form data", formData); // Send a POST request to the update_question.php endpoint with the form data const response = await fetch("update_question.php", { method: "POST", body: formData, }); // Check if the request was successful if (response.ok) { const result = await response.json(); console.log(result); // If the response has a "success" property and its value is true, clear the form if (result.success) { const searchTerm = document.getElementById("searchTerm").value; await displayRecord(searchTerm); } } else { console.error( "Error submitting the form:", response.status, response.statusText ); // Handle error response } }); }); -
I don't know exactly it is called, but sometimes you have to give your ISP `permission` to use certain email clients. I know Gmail for example does and I had to change some settings on my email server portion.
-
Here a simple breakdown $cookie_name = 'my_cookie'; $cookie_value = 'my_value'; $cookie_domain = 'www.example.com'; $cookie_lifetime = strtotime('+6 months'); $cookie_options = array( 'expires' => $cookie_lifetime, 'path' => '/', 'domain' => $cookie_domain, 'secure' => true, 'httponly' => true, 'samesite' => 'Lax' ); setcookie($cookie_name, $cookie_value, $cookie_options); a login example - // Verify the username and password if (verify_credentials($username, $password)) { // Generate a unique token $token = bin2hex(random_bytes(32)); // Store the token in the user's database record (or other persistent storage mechanism) store_token_in_database($user_id, $token); // Set a cookie with the token and a 6-month expiration time setcookie('login_token', $token, [ 'expires' => strtotime('+6 months'), 'path' => '/', 'domain' => 'example.com', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax' ]); // Store the token in the user's session $_SESSION['login_token'] = $token; // Redirect the user to the dashboard or home page header('Location: dashboard.php'); exit; } else { // Invalid username or password $error = 'Invalid username or password'; }
-
I suggest looking into using PDO https://phpdelusions.net/pdo as well as the code is so much cleaner in my opinion as well. Here's an example of what I'm talking about -> $sql = "INSERT INTO lego_trivia (points, question, answer, canvas_images) VALUES (:points, :question, :answer, :canvas_images)"; $stmt = $pdo->prepare($sql); // Bind the values to the placeholders $stmt->bindValue(':points', $points, PDO::PARAM_INT); $stmt->bindValue(':question', $question); $stmt->bindValue(':answer', $answer); $stmt->bindValue(':canvas_images', $savePath); // Execute the prepared statement $insertSuccess = $stmt->execute();
-
Don't know the real difference, but if you want to use emojis then UTF8mb4 is the way to go -> "Database character encoding: Ensure that your database is using the utf8mb4 character set and the utf8mb4_unicode_ci collation. This character set supports storing emojis and other Unicode characters properly." Though you still use `<meta charset="UTF-8">` in the HTML and set the following if you're using PDO -> $dsn = "mysql:host=localhost;dbname=your_database_name;charset=utf8mb4"; $pdo = new PDO($dsn, $username, $password);
-
I have setup a little Codepen giving the basic structure of using grids, Flexbox and media queries. I still use a variation of it now with my websites. Here's the link -> https://codepen.io/Strider64/pen/gOGqrxo In my opinion it's better than just throwing all div elements all over the place. Just another option and I think you will be surprise how less CSS you use.
-
Creating a Quiz in PHP/PDO - help with ERD
Strider64 replied to webdeveloper123's topic in Application Design
My hangman type of game is setup differently, but I keep everything together. Here's my table setup CREATE TABLE `lego_trivia` ( `id` int NOT NULL, `question` varchar(255) COLLATE utf8mb4_general_ci NOT NULL, `answer` varchar(255) COLLATE utf8mb4_general_ci NOT NULL, `canvas_images` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `points` int NOT NULL DEFAULT '10' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; and here's just one of my PHP files <?php require_once '../assets/config/config.php'; require_once "../vendor/autoload.php"; use FanOfLEGO\Database; $pdo = Database::pdo(); // Parse the input data $data = json_decode(file_get_contents('php://input'), true); if (!$data) { try { errorOutput('Invalid input data', 400); } catch (JsonException $e) { } exit(); } $current_id = (int) $data['current_id']; try { $stmt = $pdo->prepare('SELECT id, canvas_images FROM lego_trivia WHERE id > :current_id ORDER BY id LIMIT 1'); $stmt->bindValue(':current_id', $current_id, PDO::PARAM_INT); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); if ($result) { // Makes it, so we don't have to decode the json coming from javascript header('Content-type: application/json'); $data = ['next_id' => $result['id'], 'image' => $result['canvas_images']]; //canvas_images is the path output($data); } else { // Reached the end of the table output(['end_of_table' => true]); } } catch (PDOException $e) { errorOutput($e->getMessage(), 500); } function errorOutput($output, $code = 500) { http_response_code($code); echo json_encode(['error' => $output]); } function output($data) { http_response_code(200); echo json_encode($data); } and a link to the some-what finished game https://www.fanoflego.com/hangman/can_you_solve.php My point is that it is easier to keep everything organized if it is in one table though have a separate table for high scores is something I will will be working on next. -
<?php $host = 'localhost'; // your database host $dbname = 'mydatabase'; // your database name $username = 'myusername'; // your database username $password = 'mypassword'; // your database password try { $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set additional PDO attributes if needed } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
-
Like requinix says you should show the full code as it sounds more than hiding a submit button. For example: /* Success function utilizing FETCH */ const sendUISuccess = function (result) { //console.log('Result', result); if (result) { document.querySelector('#recaptcha').style.display = "none"; submit.style.display = "none"; document.querySelector('.pen').setAttribute('src', 'assets/images/target.png'); //messageSuccess.style.display = "block"; document.querySelectorAll('form > *').forEach(function (a) { a.disabled = true; }); } }; // Function to handle errors when sending data to the database const sendUIError = function (error) { console.log("Database Table did not load", error); }; // Function to handle errors when saving data to the database const handleSaveErrors = function (response) { if (!response.ok) { throw new Error(`Save request failed with status ${response.status}: ${response.statusText}`); } return response.json(); }; // Function to save the data to the database const saveDataToDatabase = (url, onSuccess, onError, data) => { fetch(url, { method: 'POST', body: JSON.stringify(data) }) .then(response => handleSaveErrors(response)) .then(data => onSuccess(data)) .catch(error => onError(error)); }; This is a portion of my JavaScript that uses Fetch to get a response back after a user sends the message. It hides the submit button, but verifies the message was sent and a few other things.
-
Suggested search using PHP/JSON/AJAX help
Strider64 replied to CodeRed-Alpha's topic in PHP Coding Help
I love using fetch and full name can be used -> JavaScript function searchUser(fullName) { // Construct the SQL query as a string with a parameter placeholder const query = 'SELECT * FROM users WHERE full_name = ?'; // Send a POST request to the PHP script with the SQL query and the user's full name as the request body fetch('search_user.php', { method: 'POST', body: JSON.stringify({ query: query, fullName: fullName }) }) .then(response => { if (response.ok) { return response.json(); } throw new Error('Network response was not ok.'); }) .then(data => { // Handle the response data console.log(data); }) .catch(error => { console.error('There was a problem with the fetch operation:', error); }); } // Call the searchUser function with the full name you want to search for searchUser('John Smith'); Example being done in PHP <?php // Get the SQL query and the user's full name from the POST request body $query = $_POST['query']; $fullName = $_POST['fullName']; // Create a new PDO object to connect to the database $dsn = 'mysql:host=localhost;dbname=mydatabase'; $username = 'myusername'; $password = 'mypassword'; try { $pdo = new PDO($dsn, $username, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); exit(); } // Prepare the SQL query as a statement $stmt = $pdo->prepare($query); // Execute the statement with the user's full name as the parameter $stmt->execute(array($fullName)); // Fetch the results as an associative array $results = $stmt->fetchAll(PDO::FETCH_ASSOC); // Send the results as JSON data to the client header('Content-Type: application/json'); echo json_encode($results); ?> -
Here's a simple login (not tested) that might get you started? $dsn = 'mysql:host=localhost;dbname=database'; $username = 'username'; $password = 'password'; try { $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare("SELECT id, hashed_password FROM users WHERE username = :username LIMIT 1"); $stmt->execute(array(':username' => $username)); if ($stmt->rowCount() == 1) { $user = $stmt->fetch(PDO::FETCH_ASSOC); if (password_verify($password, $user['hashed_password'])) { session_start(); unset($password); session_regenerate_id(); $_SESSION['last_login'] = time(); $_SESSION['id'] = $user['id']; header("Location: admin.php"); exit(); } } $error[] = 'Invalid username or password.'; } catch (PDOException $e) { die('Error: ' . $e->getMessage()); } That reads it in and the following writes the user's username and password $username = 'exampleuser'; $password = 'secretpassword'; // Hash the password using the default algorithm (currently bcrypt) $hashed_password = password_hash($password, PASSWORD_DEFAULT); // Connect to the MySQL database using PDO $dsn = 'mysql:host=localhost;dbname=database'; $username = 'username'; $password = 'password'; try { $pdo = new PDO($dsn, $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Prepare an SQL statement to insert the username and hashed password into the users table $stmt = $pdo->prepare("INSERT INTO users (username, hashed_password) VALUES (:username, :hashed_password)"); $stmt->bindParam(':username', $username); $stmt->bindParam(':hashed_password', $hashed_password); // Execute the statement $stmt->execute(); echo "New record created successfully"; } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } and I even throw in the SQL for a MYSQL database table CREATE TABLE users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, username VARCHAR(30) NOT NULL UNIQUE, hashed_password VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
-
.outer-div { width: 100%; text-align: center; } .logo-div, .translate-div { display: inline-block; vertical-align: middle; } .logo-div { background-color: red; color: #fff; text-align: left; padding: 1.25em; margin: 0.625em; } .translate-div { background-color: blue; color: #fff; text-align: right; padding: 1.25em; margin: 0.625em; } <div class="outer-div"> <div class="logo-div">Logo and company name</div> <div class="translate-div">Google translate dropdown menu</div> </div> https://codepen.io/Strider64/pen/ZEMZQwa
-
To address this issue, you can try adding an additional WHERE clause to the SQL query to filter the results based on the input class, as follows: $sql = "SELECT rank FROM ( SELECT ord.id , seq := seq+1 as seq , rank := CASE WHEN ord.grand_total = prev THEN rank ELSE seq END as rank , prev := ord.grand_total as grand_total FROM ( SELECT id , g.grand_total FROM student_exam_result g WHERE g.class = ? ORDER BY grand_total DESC LIMIT 18446744073709551615 ) ord JOIN (SELECT seq:=0, rank:=0,prev:=0) init ) ranked JOIN student_exam_result g ON g.id = ranked.id WHERE class = ? AND index_number = ? AND term = ? AND year = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param('sssss', $session_classs, $session_classs, $session_indexx, $session_termm, $session_yearr); $stmt->execute(); $stmt->bind_result($position); $stmt->fetch(); In this updated query, the WHERE g.class = ? clause has been added to the subquery to ensure that only students from the input class are included in the calculation of their positions. Additionally, the bind_param statement has been updated to include an additional s parameter to match the added input parameter. Note that this solution assumes that the class column in the student_exam_result table exactly matches the input session_classs value. If there are any discrepancies between the input value and the column values, you may need to adjust the query accordingly.
-
<!DOCTYPE html> <html> <head> <title>Two Frames Example</title> <script> function loadFrames() { document.getElementById("frame1").src = "page1.html"; document.getElementById("frame2").src = "page2.html"; } </script> </head> <body> <a href="#" onclick="loadFrames()">Click Here for Page 1 and Page 2</a> <br><br> <iframe id="frame1"></iframe> <iframe id="frame2"></iframe> </body> </html>
-
$query = $db->query("SELECT * FROM msg"); // Start an HTML table to display the results echo "<table>"; echo "<tr><th>ID</th><th>Message</th><th>Sender</th></tr>"; // Loop through the rows of data and add them to the table while ($row = $query->fetch(PDO::FETCH_ASSOC)) { echo "<tr>"; echo "<td>" . $row["id"] . "</td>"; echo "<td>" . $row["message"] . "</td>"; echo "<td>" . $row["sender"] . "</td>"; echo "</tr>"; } // Close the HTML table echo "</table>"; This code uses an HTML table to display the query results, with column headings for each field. Inside the while loop, each row of data is output as an HTML table row (<tr>) with cells for each column (<td>). The final echo statement closes the HTML table. Note that this code assumes that the columns in the msg table are named id, message, and sender. If your column names are different, you should update the code to reflect the correct column names.
-
Personally I would throw that script into file 13 and use PDO as it is more versatile and it isn't obsolete like mysql is. A good reference on PDO is this https://phpdelusions.net/pdo I would come up with a script something like the following -> <?php // Start the session session_start(); // Connect to the database $dsn = 'mysql:host=localhost;dbname=mydatabase'; $username = 'myusername'; $password = 'mypassword'; $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); try { $pdo = new PDO($dsn, $username, $password, $options); } catch (PDOException $e) { die('Database connection failed: ' . $e->getMessage()); } // Check if the login form was submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Retrieve the submitted form data $username = $_POST['username']; $password = $_POST['password']; // Validate the form data if (empty($username) || empty($password)) { echo 'Please enter your username and password.'; exit(); } // Query the database to verify the username and password $sql = "SELECT * FROM users WHERE username = :username LIMIT 1"; $stmt = $pdo->prepare($sql); $stmt->bindParam(':username', $username); $stmt->execute(); $user = $stmt->fetch(); if ($user && password_verify($password, $user['password'])) { // Set session variables to indicate that the user is logged in $_SESSION['loggedin'] = true; $_SESSION['username'] = $user['username']; // Redirect the user to a protected page header('Location: protected.php'); exit(); } else { echo 'Incorrect username or password.'; exit(); } } ?> Just my opinion and I think it would save you a lot of headaches in the long run.