-
Posts
482 -
Joined
-
Last visited
-
Days Won
13
Everything posted by Strider64
-
<?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.
-
I think you're making things more difficult that it really needs to be? Here's an example of how you can save an image path in PHP: $image_path = "images/my_image.jpg"; In this example, the variable $image_path is set to the path of the image file "my_image.jpg" located in the "images" directory. You can then use this variable to display the image on a webpage or perform other operations with the image file. To display an image in HTML, you can use the <img> tag and set the src attribute to the path of the image file. <img src="images/my_image.jpg" alt="My Image">
-
I'm asking a stupid question but way are you validating a person name? The Late Prince would had have trouble with that. 🤣 The person's age is another head scratcher. If some of that information is not right simply have it where a person can edit the information, have it idiot proof like the person's age as an example or have a confirmation page.
-
Personally, I just upload images privately to my own website, but I came across a tutorial a long time ago that stated simply doing this would help. Though it would be a memory hog and something a visitor would not appreciate, so I never used it. protected function file_contains_php() { $contents = file_get_contents($this->file['tmp_name']); $position = strpos($contents, '<?php'); return $position !== false; } There was a member (I forget his name) here a long time ago that taught me a valuable lesson in programming and that is professionals who write security code do it for a living. They test it out, verify before making it public and even then they sometimes get it wrong. So do you think you can? He was referring to me and the script I just wrote. I agreed with him and used a third party script even though it was painful in trashing that script as I spent all night writing it. 🤣
-
There are plenty of good online help on PDO - https://phpdelusions.net/pdo
-
Please Review my code and highlight my mistake
Strider64 replied to Ehsan_Nawaz's topic in PHP Coding Help
first of all you should use an unique index for email and I don't understand the also having for username (though that too). Though I now can see both...tired. Second take a look at this $sql = "SELECT * FROM register WHERE username:username AND email:email"; See anything missing? I give you a hint it's between username :username and also email :email. Here's a good link https://phpdelusions.net/pdo and I even still use it from time to time. -
Update to 1st row when try to update other rows
Strider64 replied to Ooilchen's topic in PHP Coding Help
I think I might chime in as well. I think you're trying to do too much with all that code. Coding should work for you, not against you. This is how I generally start off developing a web page. First, I design my web page with HTML/CSS on how I want it to look then I proceed onto coding the page. Then I try to keep as much as the code separated as much as possible, by that I mean having most of the PHP at the top of the file (page) and the HTML at the bottom of the page. The JavaScript in a separate file (though I might have a little amount of JavaScript sprinkle in) and if I'm using FETCH/JSON the PHP in a separate file as well. When I do have PHP in the HTML I try to keep it to the bare minimum instead of encapsulating all the HTML with an echo statement. Even the HTML I use over and over for other pages I have as a separate file with an include statement though that is usually done when I have most of the website up and running. A fragmented Example: <body class="site"> <header class="headerStyle"> <!-- Button to open the modal login form --> <button id="myButton" onclick="document.getElementById('id01').style.display='block'">Login</button> <!-- The Modal --> <div id="id01" class="modal"> <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span> <!-- Modal Content --> <form class="modal-content animate" method="post"> <div class="imgcontainer"> <img src="assets/images/img-john-pepp-150-150-001.jpg" alt="Avatar" class="avatar"> </div> <div class="container"> <label for="uname"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="user[username]" required> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="user[hashed_password]" required> <button type="submit" name="submit" value="login">Login</button> <label> <input type="checkbox" checked="checked" name="user[remember]"> Remember me </label> </div> <div class="container" style="background-color:#f1f1f1"> <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel </button> <span class="psw">Please <a href="register.php">Register</a></span> </div> </form> </header> <?php include_once 'assets/includes/inc.navigation.php'; ?> <section class="main"> <?php foreach ($cms as $record) { echo '<header class="sectionHeader">'; echo '<h2 class="sectionHeadingText">'. $record['heading'] . '</h2>'; echo '</header>'; echo '<article class="sectionArticle">'; echo '<img class="imageArticle right-side" src="' . $record['image_path'] . '" alt="LEGO Bookstore">'; echo '<p class="articleText">' . nl2br($record['content']). '</p>'; echo ' </article>'; echo '<footer class="sectionFooter">'; echo '<p class="sectionText">Written by ' . $record['author'] . ' on ' . CMS::styleDate($record['date_added']) .' </p>'; echo '</footer>'; } ?> <div class="flex_container"> <?= $pagination->links(); ?> </div> </section> Though coders do have their own preferences, but this is my preference as I find it easier to go straight to the problem if I am having one instead of hunting through a LOT OF HTML. -
Functions with same name without code duplication
Strider64 replied to john_zakaria_s's topic in PHP Coding Help
Not trying to sound rude, but you might think about dusting off your resume if that is one of your job duties. If it isn't (which has happen to me in the past) explained to him/her that you don't know how to accomplish the task. -
I personally like Active Record Pattern and I implement on my websites that I develop and design as it makes the job easier. The website goes up faster and lot less coding when all you have to do is transport the classes over and make a few minor modifications to the code. I didn't use a library and learn how to do ARP by watching a tutorial which is kind of ironic as the person who did the tutorial was using mysqli, but I like using PDO so I just switched it over to that. Active Record is good for small to medium size websites in my opinion and if I was building a large website I probably go with MVC or something like that. The reason I don't use libraries is I like to code and see how it basically it is done at the native level when it comes to PHP and I don't use libraries like jQuery with JavaScript as I use plain Vanilla js. I see comments all the time that a person writes more code with Vanilla JavaScript, but I personally don't think it is all that much more code being written (other than the helper functions). Sorry getting off topic a little bit.
-
I just want to point out that ids are great for buttons if you are changing a single button's appearance or you want a certain button to do a certain action. A good example is doing a trivia game as you can have each button be a possible answer. You would still use a class for general styling of the buttons and the id to personalize the button either in CSS or JavaScript (Which I did a lot in developing a trivia game). Here's an example: <div id="questionBox"> <h2 id="question">What is the Question?</h2> <button class="buttonStyle" id="ans1">Ans1</button> <button class="buttonStyle" id="ans2">Ans2</button> <button class="buttonStyle" id="ans3">Ans3</button> <button class="buttonStyle" id="ans4">Ans4</button> </div> Though I am using JavaScript to control the buttons. A small snippet - let q = document.querySelector('#question'); let answer1 = document.querySelector('#ans1'); let answer2 = document.querySelector('#ans2'); let answer3 = document.querySelector('#ans3'); let answer4 = document.querySelector('#ans4'); let index = 0; let totalRecords = 0; let triviaData = null; const checkAnswer = () => { } const displayData = ({ans1, ans2, ans3, ans4, id, question}) => { console.log('trivia data', question); console.log(`The database table id is ${id}`) q["textContent"] = question; answer1["textContent"] = ans1; answer2["textContent"] = ans2; answer3["textContent"] = ans3; answer4["textContent"] = ans4; I am updating my online Trivia Game, but I just wanted to show that ids can be important to the <button></button> element. The CSS .buttonStyle { display: block; width: 100%; height: 3.125em; border: none; outline: none; cursor: pointer; background-color: #F5F5F5; font-family: 'Rubik', sans-serif; font-size: 1.2em; color: #2E2E2E; text-transform: capitalize; text-align: left; padding-left: 0.625em; margin: 0 auto; }
-
Syntax issues, still a newbie but getting there!
Strider64 replied to Crazycabling's topic in PHP Coding Help
I'll add my .02 cents to the discussion. What I like do is to design the web page first and if I know something is going to repeat itself (though it's also good for non-repeating code as well) then I just add the PHP to the HTML when I am coding it. As an example a blog or a page that will have more than one article to the page -> <?php foreach ($cms as $record) { echo '<header class="sectionHeader">'; echo '<h2 class="sectionHeadingText">'. $record['heading'] . '</h2>'; echo '</header>'; echo '<article class="sectionArticle">'; echo '<img class="imageArticle right-side" src="' . $record['image_path'] . '" alt="LEGO Bookstore">'; echo '<p class="articleText">' . nl2br($record['content']). '</p>'; echo ' </article>'; echo '<footer class="sectionFooter">'; echo '<p class="sectionText">Written by ' . $record['author'] . ' on ' . CMS::styleDate($record['date_added']) .' </p>'; echo '</footer>'; } ?> I would start off with straight HTML then add the PHP to the page. I personally like using echo as I can easily modify certain HTML elements easier, but that is just probably me. 😀 -
Like already stated you don't store an array in a database table, but you can store the individual values as long as the correct key names (index names) in an array matching the tables columns. Here's an example: function insertData(array $data, $pdo, $table) { try { /* Initialize an array */ $attribute_pairs = []; /* * Set up the query using prepared states with the values of the array matching * the corresponding keys in the array * and the array keys being the prepared named placeholders. */ $sql = 'INSERT INTO ' . $table . ' (' . implode(", ", array_keys($data)) . ')'; $sql .= ' VALUES ( :' . implode(', :', array_keys($data)) . ')'; /* * Prepare the Database Table: */ $stmt = $pdo->prepare($sql); /* * Grab the corresponding values in order to * insert them into the table when the script * is executed. */ foreach ($data as $key => $value) { if($key === 'id') { continue; } // Don't include the id: (Normally not needed if it is NEW data) $attribute_pairs[] = $value; // Assign it to an array: } return $stmt->execute($attribute_pairs); // Execute and send boolean true: } catch (PDOException $e) { if ($e->errorInfo[1] === 1062) { return false; } throw $e; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; // Not for a production server: } return true; }
-
Thank You
-
What I mean is the id field (Auto Increment) start at 1 and I have existing records that have an id of 130 lets say. I wrote new questions/answers and it started back at 1. So if I add more questions that get up to say 130 will the exist questioning be OVER WRITTEN 🙄. If I get another rude reply I am going to delete this account and use other forums. You would think a person who didn't understand what I was writing would say could you clarify it and to top it all it's an administrator that made the reply.
-
I have updated a online trivia game and used an old database table that has existing questions. I was wondering if the new questions would overwrite existing questions because questions have been deleted in the past with this database table? Thanks in Advance, John
-
Totally disagree as FETCH is very easy to implement and is very elegant in my opinion - However, every coder has a different style. 😉 /* Handle General Errors in Fetch */ const handleErrors = function (response) { if (!response.ok) { throw (response.status + ' : ' + response.statusText); } return response.json(); }; /* Success function utilizing FETCH */ const quizUISuccess = (parsedData) => { console.log('trivia data', parsedData); mainGame.style.display = 'grid'; d.getElementById('content').scrollIntoView(); //gameData = parsedData; gameData = parsedData.sort(() => Math.random() - .5); // randomize questions: totalQuestions = parseInt(gameData.length); createQuiz(gameData[gameIndex]); }; /* If Database Table fails to load then answer a few hard coded Q&A */ const quizUIError = (error) => { /* * If game database table fails to load then give a few questions * and answers, so that the game will still work properly. */ failed = true; mainGame.style.display = 'grid'; d.getElementById('content').scrollIntoView(); console.log("Database Table did not load", error); gameData = [{ "id": 1, "user_id": 1, "hidden": "no", "question": "[Blank] is the length of time when the film or digital sensor inside the camera is exposed to light, also when a camera's shutter is open when taking a photograph. The amount of light that reaches the film or image sensor is proportional to the [Blank].", "category": "photography", "answers": [ "Shutter Speed or Exposure Time", "ISO", "", "" ] }, { "id": 2, "user_id": 1, "hidden": "no", "question": "[Blank] was one of the earliest photographers in American history, best known for his scenes of the Civil War. He studied under inventor Samuel F. B. Morse, who pioneered the daguerreotype technique in America. [Blank] opened his own studio in New York in 1844, and photographed Andrew Jackson, John Quincy Adams, and Abraham Lincoln, among other public figures.", "category": "photography", "answers": [ "Robert Capa", "Steve McCurry", "Ansel Adams", "Matthew Brady" ] } ] totalQuestions = gameData.length; //console.log(gameData[gameIndex]); createQuiz(gameData[gameIndex]); }; /* create FETCH request */ const createRequest = (url, succeed, fail) => { fetch(url) .then((response) => handleErrors(response)) .then((data) => succeed(data)) .catch((error) => fail(error)); };
-
People put too much into printing web pages. I created a simple blood pressure reading page (I'm trying to keep my blood pressure under control) and use simple CSS to print out the readings - A sample of the CSS: // Avoid page breaks straight after a heading. h1, h2, h3, h4, h5, h6 { page-break-after: avoid; } /* Avoid page breaks inside paragraphs, blockquotes, lists, and preformatted text. */ p, blockquote, ul, ol, dl, pre { page-break-inside: avoid; } @media print { header, footer { display: none; } } Here's the link to the page - https://www.phototechguru.com/print_bp.php