Jump to content


  • Posts

  • Joined

  • Last visited

  • Days Won


Posts posted by Strider64

  1. 3 minutes ago, LeonLatex said:

    @mac_gyver, If you look in bottom of my first posting you find my login form. I dont have a registration form yet because so early in the development process i manually put the testing user accounts in mysql manually. I dont have time to use more time on this now, so i will start develop another system, and this time with email confirmation and a confirmation code. Is less use of time to put a new one together than looking for errors in this login system. I dont think there is only one error. The system has going through many changes through the last year, so it's time to let the old one rest. Any way, thanks for using time for trying to help 😃

    You don't need a registration form/page as all you have to do is hash your password that you want to use. That's what I do when I develop my website(s).

  2. You need to do something like this ->

            // Add an event listener to the edit form's submit event
            editForm.addEventListener("submit", async function (event) {
                // Prevent the default form submit behavior
                // Create a FormData object from the edit form
                const formData = new FormData(editForm);
                //console.log("form data", formData);
                // Send a POST request to the edit_update_blog.php endpoint with the form data
                const response = await fetch("edit_update_blog.php", {
                    method: "POST",
                    body: formData,
                // Check if the request was successful
                if (response.ok) {
                    const result = await response.json();
                    // If the response has a "success" property and its value is true, clear the form
                    if (result.success) {
                        resultInput.value = '';          // Clear the current value of the search input field
                        resultInput.placeholder = "New Search"; // Set the placeholder to `New Search`
                        image_for_edit_record.src = "";
                        image_for_edit_record.alt = "";
                        editForm.reset(); // Resetting the edit form
                        searchForm.reset(); // Resetting the search form
                        // Reset select box to default (first) option
                        const selectBox = document.querySelector('select[name="heading"]');
                        selectBox.selectedIndex = 0;
                } else {
                        "Error submitting the form:",
                    // Handle error response

    also using `console.log` helps in debugging, plus your `sql_connection.php` is expecting back json data back.

    • Great Answer 1
  3. 19 minutes ago, Adamhumbug said:

    Hi All,

    As i am trying to learn more and more i wanted to know if there was a way of looking at a raw fetchall() when running functions in php.

    I have a function call on my page which is set to var_dump the return.

    Is it possible to show the whole array on that page?

    Sure, I just do something like this

    echo "<pre>" . print_r($results, 1) . "</pre>";

    It's a great way to debug also.

  4. /* ----- Upload File / Image ----- */
    function uploadFile(uid) {
        const url = 'process.php';
        const form = document.querySelector('form');
        form.onsubmit = function(e) {
            const files = document.querySelector('[type=file]').files;
            const formData = new FormData();
            for (let i = 0; i < files.length; i++) {
                let file = files[i];
                formData.append('files[]', file);
                formData.append('uploadid', uid);
            fetch(url, {
                method: 'POST',
                body: formData
            }).then(response => {
                return response.text();
            }).then(data => {

    Instead of using the addEventListener method for the form submission, you can directly bind the function to the form's onsubmit?

  5. I just wanted to add that when I took a course in web design one of the things to do is keep the form simple as possible. I'm assuming all that data is coming from a form? If that case I would simplify it down a bit as most visitors will leave that website if they see a HTML form that l large.

    An example of what I'm talking about.

            <form class="registerStyle" action="register.php" method="post">
                <input id="secret" type="hidden" name="user[secret]" value="">
                <div id="qr-code-container" class="d-none">
                    <img id="qr-code-image" src="" alt="QR Code">
                    <p id="qr-code-info">Scan QR Code for 2FA</p>
                <div class="first">
                    <label for="first_name">First Name</label>
                    <input id="first_name" type="text" name="user[first_name]" value="" tabindex="2" required>
                <div class="last">
                    <label for="last_name">Last Name</label>
                    <input id="last_name" type="text" name="user[last_name]" value="" tabindex="3" required>
                <div class="screenName">
                    <label class="text_username" for="username">Username <span class="error"> is unavailable!</span>
                    <input id="username" class="io_username" type="text" name="user[username]" value="" tabindex="4"
                <div class="telephone">
                    <label for="phone">Phone (Optional)</label>
                    <input id="phone" type="tel" name="user[phone]" value="" placeholder="555-555-5555"
                           pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" tabindex="5">
                <div class="emailStyle">
                    <label class="emailLabel" for="email">Email <span class="emailError"> is invalid</span> </label>
                    <input id="email" type="email" name="user[email]" value="" tabindex="1" autofocus required>
                <div class="password1">
                    <label for="passwordBox">Password</label>
                    <input class="passwordBox1" id="passwordBox" type="password" name="user[password]" value=""
                           tabindex="6" required>
                    <label for="passwordVisibility">Show Passwords (private computer)</label>
                    <input class="passwordBtn1" id="passwordVisibility" type="checkbox" tabindex="7">
                <div class="password2">
                    <label for="redoPassword">ReEnter Password</label>
                    <input class="passwordBox2" id="redoPassword" type="password" name="user[comfirm_password]" value="" tabindex="8"
                <div class="birthday">
                    <label for="birthday">Birthday (optional)</label>
                    <input id="birthday" type="date" name="user[birthday]" value="1970-01-01" tabindex="9">
                <div class="submitForm">
                    <button class="submitBtn" id="submitForm" type="submit" name="submit" value="enter" tabindex="10">

    or at least pull the data in easier -> Example:

    $user = $_POST['user'];


  6. My suggestion is to use composer https://getcomposer.org/ as it will save you a lot a headaches and you don't have to reinvent the wheel.

    Then you can just do something like the following ->

    // Include the configuration file and autoload file from the composer.
    require_once __DIR__ . '/../config/config.php';
    require_once "vendor/autoload.php";
    // Import the ErrorHandler and Database classes from the PhotoTech namespace.
    use brainwave\{
        LoginRepository as Login
    // Instantiate the ErrorHandler class
    $errorHandler = new ErrorHandler();
    // Set the exception handler to use the handleException method from the ErrorHandler instance
    set_exception_handler([$errorHandler, 'handleException']);
    // Create a new instance of the Database class
    $database = new Database();
    // Create a PDO instance using the Database class's method
    $pdo = $database->createPDO();
    $login = new Login($pdo);
    if ($login->check_login_token()) {
        header('location: dashboard.php');
    $cms = new ImageContentManager($pdo);

    a sample class ->

    // ErrorHandler.php
    namespace brainwave;
    use PDOException;
    use Throwable;
    use JsonException;
    class ErrorHandler implements ErrorHandlerInterface
        public function handleException(Throwable $e): void
            if ($e instanceof PDOException) {
                error_log('PDO Error: ' . $e->getMessage());
            } elseif ($e instanceof JsonException) {
                error_log('JSON Error: ' . $e->getMessage());
            } else {
                error_log('General Error: ' . $e->getMessage());

    I would also check out namespace for PHP classes.

    • Like 1
  7. 1 hour ago, PNewCode said:

    I figured it out. I was trying to add stuff to the wrong if statement. Instead I just changed the following, and now it works :)


     if (isset($_POST["submit"]))
    $pname = "";
         $allowed_img = array('gif', 'png', 'jpg', 'jpeg');


    This is taken from my website project ->


    $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    $extensions = array("jpeg", "jpg", "png");
    if (in_array($file_ext, $extensions, true) === false) {
        $errors[] = "extension not allowed, please choose a JPEG or PNG file.";
         * If no errors save ALL the information to the
         * database table.
        if (empty($errors) === true) {
            // Code that does it....

    I know my variable naming isn't exact, but it should give you a basic way in doing it.

    I have the GitHub repository -> https://github.com/Strider64/brain-wave-blitz/blob/master/create_cms.php feel free to look around.

    • Like 1
  8. A simple way in my opinion would to do something like the following.

    fetch('https://example.com/data-endpoint') // replace with your actual URL
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        return response.json(); // this returns a promise
      .then(data => {
        console.log(data); // this will log the whole data to the console
        // you can access any data point like this:
        console.log(data.newOffers); // logs: null
        console.log(data.usedOffers[0].price); // logs: 49.23
        // if you want to loop through all the usedOffers you can do something like this:
        data.usedOffers.forEach(offer => {
          console.log(`Offer ID: ${offer.id}`);
          console.log(`Price: ${offer.price}`);
          console.log(`Delivery Rate: ${offer.deliveryRate}`);
          // ... and so on for other properties
      .catch(e => {
        console.log('There was a problem with the fetch operation: ' + e.message);

    I'm half asleep that from the JavaScript side, but I find JavaScript more flexible than PHP and easier.

  9. I do it a little different way - I do all the time figure in JavaScript (I use Vanilla JavaScript) ->

    "use strict";
    // Function to calculate the time remaining till a certain end time
    const getTimeRemaining = (countdown_date) => {
        // Parse the end time and current time into milliseconds
        const endtimeParsed = Date.parse(countdown_date);
        const nowParsed = Date.parse(new Date());
        // Calculate the total remaining time in milliseconds
        const total = endtimeParsed - nowParsed;
        // Breakdown the total time into days, hours, minutes, and seconds
        const seconds = Math.floor((total / 1000) % 60);
        const minutes = Math.floor((total / 1000 / 60) % 60);
        const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
        const days = Math.floor(total / (1000 * 60 * 60 * 24));
        // Return a time object that has the total remaining time and the breakdown
        return {
    // Function to display a countdown clock on the webpage
    const myClock = (id, countdown_date) => {
        // Find the clock and its components by their IDs
        const clock = document.getElementById(`display_clock${id}`);
        const daysSpan = clock.querySelector(`.day${id}`);
        const hoursSpan = clock.querySelector(`.hour${id}`);
        const minutesSpan = clock.querySelector(`.minute${id}`);
        const secondsSpan = clock.querySelector(`.second${id}`);
        // Function to update the clock display
        const updateClock = () => {
            // Get the remaining time
            const time = getTimeRemaining(countdown_date);
            // Update the display of each component of the clock
            // padStart() is used to ensure that all components are two digits
            daysSpan.textContent = time.days;
            hoursSpan.textContent = String(time.hours).padStart(2, '0');
            minutesSpan.textContent = String(time.minutes).padStart(2, '0');
            secondsSpan.textContent = String(time.seconds).padStart(2, '0');
            // If the total remaining time is zero or less, stop the clock by clearing the interval
            if (time.total <= 0) {
        // Call updateClock once immediately, then at regular intervals
        const timeInterval = setInterval(updateClock, 1000);
    function fetchRoutine() {
        // Define the data you want to send to the server
        const grabDate = "myDate=endDate";
        // Define the options for the fetch call
        const fetchOptions = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'XMLHttpRequest'
            body: grabDate
        // Make the fetch call
        fetch('countdown_date.php', fetchOptions)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                // If the response was ok, proceed to parse it as JSON
                return response.json();
            .then(data => {
                console.log('data', data);
                document.getElementById("countdown_date").textContent = data.date_format;
                document.getElementById("display_title").textContent = data.title;
                let countdown_date = new Date(Date.parse(data.time_left));
                myClock(1, countdown_date);
            .catch(error => {
                console.error('There has been a problem with your fetch operation:', error);

    Here's the HTML

    <!DOCTYPE html>
    <html lang="en">
            <meta charset="UTF-8">
            <title>Countdown Clock</title>
            <link rel="stylesheet" href="reset.css">
            <link rel="stylesheet" href="countdown.css">
            <div class="info">
                <h1 id="display_title"></h1>
                <h2 id="countdown_date"></h2>
            <div id="display_clock1">
                <figure class="box">
                    <div class="day1"></div>
                <figure class="box">
                    <div class="hour1"></div>
                <figure class="box">
                    <div class="minute1"></div>
                <figure class="box">
                    <div class="second1"></div>
            <script src="count_down.js"></script>

    and the css

        -webkit-box-sizing: border-box;
        box-sizing: border-box;
    div.info {
        display: block;
        width: 100%;
        max-width: 300px;
        height: auto;
        text-align: center;
        padding: 2px;
        margin: 10px auto;
    div.info::after { content: ''; display: block; clear: both; }
    h1 {
        font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif;
        font-size: 1.2em;
        line-height: 1.5;
    h2 {
        font-family: Arial, Helvetica, sans-serif;
        font-size: 1.0em;
        font-style: italic;
        font-weight: 300;
    div#display_clock1 {
        display: block;
        width: 100%;
        max-width: 190px;
        height: auto;
        margin: 5px auto;
        background-color: pink;
    div#display_clock1 figure.box {
        float: left;
        display: block;
        width: 100%;
        max-width: 40px;
        height: 70px;
        color: #fff;
        text-align: center;
        padding: 0;
        margin-left: 5px;
    div#display_clock1 figure.box div {
        background-color: #2e2e2e;
        height: 50px;
        line-height: 50px;
    div#display_clock1 figure.box figcaption {
        font-family: Arial, Helvetica, sans-serif;
        font-size: 0.6em;
        line-height: 20px;
        font-weight: bold;
        color: #000;

    it's an old script that I made changes to, so it used a little PHP

    header('Content-type: application/json');
    $endDate  = filter_input(INPUT_POST, 'myDate');
    if ($endDate === 'endDate') {
        $count_down_date = new DateTime('2023-07-17 00:00:00', new DateTimeZone("America/Detroit"));
        $data['time_left'] = $count_down_date->format("Y/m/d H:i:s");
        $data['date_format'] = $count_down_date->format("l - F j, Y");
        $data['title'] = "Countdown to ";
    function errorOutput($output, $code = 500) {
        echo json_encode($output);
     * If everything validates OK then send success message to Fetch / JavaScript
    function output($output) {
        echo json_encode($output);

    This could be done in JavaScript or even pulling from a Database Table. Like I said it's an old script that I modernized it a little.

  10. 2 hours ago, Barand said:

    If you want to hide them, why include them in the query in the first place?

    There are times that it needs to be done, for example if a game has multiple choices and there are only 2 possible answers.

    This is a JavaScript pulling data from a database table using fetch ->

            // This line sets the text content of the button to the corresponding answer (ans1, ans2, ans3, ans4)
            // with a "📷" character at the beginning.
            button.textContent = `📷 ${[ans1, ans2, ans3, ans4][index]}` || "";
            // If there's no corresponding answer, the button is disabled (its pointer events are set to "none").
            // Otherwise, the button is enabled (its pointer events are set to "auto").
            if (![ans1, ans2, ans3, ans4][index]) {
                button.style.pointerEvents = "none";
            } else {
                button.style.pointerEvents = "auto";

    Though I have of admit most of the time is a waste of time coding for empty fields.

  11. I have been developing an online trivia game for years now and I have finally wrapped this around my head. (Well, at least I think 😂 )


                        <div id="answers">
                            <button class="buttonStyle" id="ans1"></button>
                            <button class="buttonStyle" id="ans2"></button>
                            <button class="buttonStyle" id="ans3"></button>
                            <button class="buttonStyle" id="ans4"></button>


    // Function to handle the event when an answer is selected.
    const pickAnswer = (answerIndex) => {
        return () => {
            choice = answerIndex;
            // Only show the next button if the next question exists
            if (index < triviaData.length - 1) {
                nextButton.style.display = "block"; // show the next button after an answer is chosen
    // The `startGame` function takes an object as an argument with properties: ans1, ans2, ans3, ans4, id, question.
    // These properties represent the answers to the current question, the question's id, and the question itself, respectively.
    const startGame = ({ ans1, ans2, ans3, ans4, id, question }) => {
        // This line sets the id of the current question to the "data-record" attribute of the element with id "currentQuestion".
        document.querySelector("#currentQuestion").setAttribute("data-record", id);
        // This line sets the display number of the current question (index + 1) to the text content of the element with id "currentQuestion".
        document.querySelector("#currentQuestion").textContent = (index + 1).toString();
        // This line sets the text content of the element with id "question" to the question itself.
        document.querySelector("#question").textContent = question;
        // This loop iterates over each of the answer buttons.
        answerButtons.forEach((button, index) => {
            // This line checks if there was a previous "pickAnswer" event listener attached to the button,
            // and if so, removes it.
            const previousPickAnswer = button.__pickAnswer__;
            if (previousPickAnswer) {
                button.removeEventListener("click", previousPickAnswer);
            // This line creates a new "pickAnswer" event listener, and attaches it to the button.
            const newPickAnswer = pickAnswer(index + 1);
            button.addEventListener("click", newPickAnswer, false);
            button.__pickAnswer__ = newPickAnswer;
            // This line sets the text content of the button to the corresponding answer (ans1, ans2, ans3, ans4)
            // with a "📷" character at the beginning.
            button.textContent = `📷 ${[ans1, ans2, ans3, ans4][index]}` || "";
            // If there's no corresponding answer, the button is disabled (its pointer events are set to "none").
            // Otherwise, the button is enabled (its pointer events are set to "auto").
            if (![ans1, ans2, ans3, ans4][index]) {
                button.style.pointerEvents = "none";
            } else {
                button.style.pointerEvents = "auto";

    I comment the script out and I think it's self-explanatory. OK, I'm tired as this is the latest I have stayed up. 🤣

  12. I use classes as I like mobility of the code going from one website to the another is easier for me. I don't use Frameworks or Libraries. I like using Vanilla JavaScript as I don't have to think about having a library. I find out that I really don't write that much more code just using good old plain JavaScript.


    Here's a JavaScript Online Trivia game that I updating. I am using CodePen to do a mockup first of it -> https://codepen.io/Strider64/pen/NWEpZdj

    Like already stated everyone has their own coding style and I am sure you will find yours.

  13. Maybe something like this for variable naming and form field names?

    $fullName = filter_input(INPUT_POST, 'fullName');
    $phone = filter_input(INPUT_POST, 'phone');
    $email = filter_input(INPUT_POST, 'email');
    $propertyType = filter_input(INPUT_POST, 'propertyType');
    $address = filter_input(INPUT_POST, 'address');
    $priceRange = filter_input(INPUT_POST, 'priceRange');
    $bedrooms = filter_input(INPUT_POST, 'bedrooms'); 
    $bathrooms = filter_input(INPUT_POST, 'bathrooms'); 
    $preApproved = filter_input(INPUT_POST, 'preApproved'); 
    if ($preApproved === "yes")  {
        echo $preApprovalAmount;
    $parkingType = filter_input(INPUT_POST, 'parkingType'); 
    $buyingTimeline = filter_input(INPUT_POST, 'buyingTimeline'); 
    $exploreZips = filter_input(INPUT_POST, 'exploreZips'); 
    $dreamHomeWish = filter_input(INPUT_POST, 'dreamHomeWish');


    • Like 1
  14. You're going to need to setup some kind of security check - Here's a example


    function check_security($id) {
        // Example of PHP Connection
        $db = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
        $sql = "SELECT security FROM user_table WHERE id=:id LIMIT 1";
        $stmt = $db->prepare($sql);
        // Bind the named parameter :id to the value $id
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        // Fetch the result as an associative array
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result && $result['security'] === 'admin') {
            return true;
        return false;

    then simply

    // Check if the user has admin security by calling the check_security function
    if (check_security($id)) {
        // If the function returns true, echo out an HTML anchor tag that leads to delete-post.php
        // The id of the row to delete is passed in the query string of the URL
        // Inside the anchor tag is a button with the class btn3 and the text DELETE
        echo '<a href="delete-post.php?id='.$row['id'].'"><button class="btn3">DELETE</button></a>';

    You will still need to check the delete-post.php in order to stop some one from directly accessing that file. This is just a quick example and you can even do that for the original user - just check to see if the user's id for the post matches the original poster's id. Just setup an addition column like user_id in the database table that contains the posts (if you haven't already done so).

    • Like 1
  15. "await" is great if you need have all the data before you moving on especially good when developing a game.

    // Fetch the First ID
    const fetchFirstId = async () => {
        try {
            // fetch the data from the server
            const response = await fetch('get-first-id.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                body: JSON.stringify({resetScore: false})
            // parse the response as JSON
            const data = await response.json();
            id = data.first_id; // Grab the First ID the DB Table
            await changeImageSource(data.image);
            await fetchQuestion();
            await fetchWord(); // fetch the answers
            //await fetchImage();
        } catch (error) {


  16. You can do a full text content search on a `content` field, but the main thing is you have to search a column in order to find what you are looking for.

    This is done in PDO, but gives an example on what I'm trying to say -


     // Extract the search term and heading from the request, if they exist.
        $searchTerm = isset($request['searchTerm']) ? $request['searchTerm'] : null;
        $heading = isset($request['heading']) ? $request['heading'] : null;
        // If a search term was provided, use a full-text search on the 'content' field.
        // Before this can work, you'll need to make sure your content column is indexed for full-text searching.
        // You can do this with the following SQL command:
        // Example:
        // ALTER TABLE gallery ADD FULLTEXT(content);
        if($searchTerm !== null) {
            $sql = "SELECT * FROM gallery WHERE MATCH(content) AGAINST(:searchTerm IN NATURAL LANGUAGE MODE) LIMIT 1";
            $stmt = $pdo->prepare($sql);
            $stmt->bindValue(':searchTerm', $searchTerm);
            // If a heading was provided, search for exact matches on the 'heading' field.
        } else if($heading !== null) {
            $sql = "SELECT * FROM gallery WHERE heading = :heading LIMIT 1";
            $stmt = $pdo->prepare($sql);
            $stmt->bindValue(':heading', $heading);
            // If neither a search term nor a heading was provided, throw an exception.
        } else {
            throw new Exception("No valid search term or heading provided");
        // Execute the prepared statement.
        // Fetch the results and handle them as needed.
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);


  17. On 6/8/2023 at 10:08 AM, elsafraslastra said:

    Hello, I need a code to create a stopwatch (on the server side with start, stop and pause) to be able to be seen by several clients in real time while it is running (only see it without being able to stop, start  or pause).


                                                                                                                                                               Thank you so much.

    Game designers/developers do that all the time with a countdown timer - example -> https://www.phototechguru.com/trivia.php. though the server side would be a little tricky if it is automated. Like someone stated websockets might be worth looking into if that is the case?

  18. This is how I do my page layouts - I start off with grids

    /* Approximately the size of a 1248px large display monitor */
    @supports (grid-area: auto) {
      @media screen and (min-width: 78em) {
        .name-website {
          display: block;
        .site {
          display: grid;
          grid-template-columns: 78em;
          column-gap: 1.250em;
          justify-content: center;
        // More CSS 

    then I use flex for individual sections or elements

            #file_grid_area {
              grid-area: file_grid_area;
              display: flex;
              box-sizing: border-box;
              background-color: darken(#8ebd94, 0.20);
              padding: 1.250em 1.250em 0;
              [type="file"] {
                border: 0;
                clip: rect(0, 0, 0, 0);
                height: 1px;
                overflow: hidden;
                padding: 0;
                position: absolute !important;
                white-space: nowrap;
                width: 1px;
              [type="file"] + label {
                background-color: #000;
                border-radius: 4rem;
                color: #fff;
                cursor: pointer;
                display: inline-block;
                padding: 0.625em 1.250em;
                margin-bottom: 1.25em;

    along with media queries

    /* Approximately the size of a 1248px large display monitor */
    @supports (grid-area: auto) {
      @media screen and (min-width: 78em) {

    that way it's easy to changing the layout without to much modification to the HTML (If at all) and making too much changes to the CSS. I have also found that i don't write that much CSS or repetitive CSS.


    Hope that Helps.


    I use SASS (A CSS Preprosser)

  19. I also find using PDO to be much cleaner. Here's an example -

            // ... more code above ...
    		// Prepare the SQL query with placeholders
            $sql = "UPDATE gallery SET category = :category, heading = :heading, content = :content, image_path = :image_path, thumb_path = :thumb_path WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            // Bind the values to the placeholders
            $savePath = $saveDirectory . $destinationFilename;
            $stmt->bindParam(':image_path', $savePath);
            $stmt->bindParam(':thumb_path', $thumb_path);
        } else {
            // Prepare the SQL query with placeholders
            $sql = "UPDATE gallery SET category = :category, heading = :heading, content = :content WHERE id = :id";
            $stmt = $pdo->prepare($sql);
        // Bind the values to the placeholders
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->bindParam(':category', $category);
        $stmt->bindParam(':heading', $heading);
        $stmt->bindParam(':content', $content);
        // Execute the prepared statement
        // Check if the update was successful
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Record updated successfully.']);
        } else {
            echo json_encode(['success' => false, 'message' => 'No record updated.']);


  20. Figuring out the offset  and using it in the query really helps -

            $sql = 'SELECT * FROM gallery WHERE page =:page AND category =:category ORDER BY id DESC, date_added DESC LIMIT :perPage OFFSET :blogOffset';
            $stmt = $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);

    and this might  help

    // 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 */
    /* To figure out offset -> $offset = $per_page * ($current_page - 1) */
    $offset = $gallery->offset($per_page, $current_page);

    Just an example of pagination

  21. You really don't need if statement or try/catch blocks and that is something a human pointed me out on another forum. I believe he's also on this forum as well.

    For example I have this function(method in OOP)

            $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);

    No try/catch block, if statement as any errors are caught by exception.

    Something to read up on is this

    // Register the exception handler method
    set_exception_handler([$errorHandler, 'handleException']);

    here's a good link on it https://www.php.net/manual/en/function.set-exception-handler.php

    For debugging

    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);

    and a good link in using PDO as in my opinion it is easier to implement and more versatile - https://phpdelusions.net/pdo

    Even the website writes "

    Although there are several error handling modes in PDO, the only proper one is PDO::ERRMODE_EXCEPTION. So, one ought to always set it this way, either by adding this line after creation of PDO instance,

    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    or as a connection option, as demonstrated in the example above. And this is all you need for the basic error reporting"

    • Like 1
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.