Jump to content

Strider64

Members
  • Posts

    470
  • Joined

  • Last visited

  • Days Won

    12

Posts posted by Strider64

  1. Even on smaller projects once you have a library of classes built up it easier to either transfer the classes or have a centralized library of the classes. Thus saving you time and probably money if you're doing it for a client. 

    • Like 1
  2. or you could do this:

    /* Get the current page */
    $phpSelf = filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_URL);
    
    $path_parts = pathinfo($phpSelf);
    
    $basename = $path_parts['basename']; // Use this variable for action='':
    $pageName = ucfirst($path_parts['filename']);
    
    
    
    <td width="50%" align="left"><a href="<?php echo $basename . "?month=". $prev_month . "&year=" . $prev_year; ?>" style="color:#FFFFFF">Previous</a></td>
    
  3. First I would recommend not using static functions. I would also suggest maybe just pulling and displaying the data directly from the database table?

     

    For example this is what I did for a small blog/forum that I did for my own website:

        public function read($category = "sysop") {
    
            $this->sql = 'SELECT id, creator_id, category, sticky, title, content,  date_updated, date_added FROM pages WHERE category=:category ORDER BY date_added DESC';
            try {
                $this->stmt = $this->pdo->prepare($this->sql);
                $this->stmt->execute([':category' => $category]);
                $this->stmt->setFetchMode(PDO::FETCH_OBJ);
                return $this->stmt;
            } catch (Exception $ex) {
                print $ex->getMessage();
            }
        }
    

    Then I just use a view page that I called posts.php

    <?php
    
    
    while ($row = $stmt->fetch()) {
        $dateAdded = new DateTime($row->date_added, new DateTimeZone('America/Detroit'));
        $dateUpdated = new DateTime($row->date_updated, new DateTimeZone('America/Detroit'));
        ?>
        <article class="blogArticle">
            <header>
                <h1><?php echo $row->title; ?></h1>
                <p class="author">by <?php echo $blog->getUsername($row->creator_id); ?> created on <?php echo $dateAdded->format("F j, Y g:i A"); ?> updated on <?php echo $dateUpdated->format("F j, Y g:i A") ?></p>
            </header>
    
            <hr>
            <p class="blogParagraph"><?php echo nl2br(html_escape($row->content)); ?></p>
            <hr>
            <footer>
                <?php if ($user && ( $user->id === $row->creator_id || $user->security_level === 'sysop')) { ?>
                    <a class="edit" href="edit.php?edit=<?php echo urlencode($row->id); ?>">Edit</a><a class="delete" href="delete.php?delete=<?php echo urlencode($row->id); ?>" onclick="return confirm('Are you sure you want to delete this thread?');">Delete</a>
                <?php } ?>
            </footer>
        </article>
    <?php }  

    that I use for my index.php page or what have you like so

    $stmt = $blog->read();
    
    require_once 'lib/includes/header.inc.php';
    ?>
    <div class="container mainPage">
        <?php include 'lib/views/posts.php'; ?>
    <?php
    require_once 'lib/includes/footer.inc.php';
    

    You can alway build an array as you go about displaying if you have other plans for it. Just a suggestion. 

  4. If you don't use a template engine you can always use a function in you configuration file that you use to make it a little less cumbersome, for example

    function html_escape($raw_input) {
        // important! don't forget to specify ENT_QUOTES and the correct encoding
        return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');
    }
    

    then call it like 

    <p class="blogParagraph"><?php echo nl2br(html_escape($row->content)); ?></p>
    

    I believe I got this small script from a tutorial I got from a different forum written by Jacques! awhile back.  :tease-03:  :happy-04:

  5. First of all I 99 percent of the time just use regular varchar, but I fool around with enum every once in a while and came up with this method of getting the categories or what have you from an enum type:

        /* Grab the categories and put it into a category array */
        public function getCategories() {
            /* Set up the query to fetch only the category column which is an enumerated type */
            $this->sql = "SHOW COLUMNS FROM pages LIKE 'category' ";
            $this->category = $this->pdo->query($this->sql);
            /* set it up as an object */
            $this->category->setFetchMode(\PDO::FETCH_OBJ);
            /* Fetch all the rows in that particular column as objects */
            $this->enum = $this->category->fetchAll();
            
            $this->type = $this->enum[0]->Type; // Grab only the Type column:
            
            preg_match('/enum\((.*)\)$/', $this->type, $this->matches); // Strip enum() away from the string:
            $this->vals = explode(',', $this->matches[1]); // Convert it to an array:
            
            /* Trim the ' away from the individual values and put it in categories array */
            foreach ( $this->vals as  $value) {
                $this->categories[] = trim($value, "'");            
            }
            return $this->categories; // Return the array with the proper categories:
        }
    

    but like already stated it is easier to use a different type and not all databases support enum. I also think it's best to have your logic (can't find a the right word) in PHP than MySQL.  ;D  Sorry for going kind of going off topic....returning to regular broadcasting.....Though I think you could modify you table to have three columns to achieve what you want (I think)

  6. What I would do is creating a configuration file and called it config.php or utilities.inc.php (This is what I call mine) then stick it at the top of every page.

     

     

    Then you can simply have scripts/sessions configured and you don't have to keep typing it every time - here's my utilities.inc.php file as an example:

    <?php
    if ($_SERVER["SERVER_NAME"] != "localhost") {
       if ($_SERVER["HTTPS"] != "on") { // Redirect to a secure website ( https )
          header("Location: https://www.pepster.com");
          exit();
        }
    }
    /* Turn on error reporting */
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(-1);
    
    /*
     * Pepster's Place : Web Design & Development
     * John R Pepp
     * Date: July 21, 2015
     * Version: 1.0 alpha
     */
    date_default_timezone_set('America/Detroit'); // Set the Default Time Zone:
    
    /* Autoloads classes using namespaces                       */
    require_once "lib/website_project/website_project.inc.php";
    
    use website_project\database\ConnectPDO as Connect;
    use website_project\users\Members as Login;
    use website_project\blog\Blog as Journal;
    
    include 'connect/connect.php'; // Connection Variables:
    header("Content-Type: text/html; charset=utf-8");
    header('X-Frame-Options: SAMEORIGIN'); // Prevent Clickjacking:
    header('X-Content-Type-Options: nosniff');
    header('x-xss-protection: 1; mode=block');
    header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
    header("content-security-policy: default-src 'self'; report-uri /csp_report_parser");
    header("content-security-policy: script-src 'self' https://apis.google.com");
    header('X-Permitted-Cross-Domain-Policies: master-only');
    
    /* Set length of sessions and start sessions */
    $seconds = 60;
    $minutes = 60;
    $hours = 24;
    $days = 14;
    session_set_cookie_params($seconds * $minutes * $hours * $days, "");
    session_start();
    
    /* Use $user for sessions variable */
    $user = isset($_SESSION['user']) ? $_SESSION['user'] : NULL;
    /* Get the current page */
    $phpSelf = filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_URL);
    
    $path_parts = pathinfo($phpSelf);
    
    $basename = $path_parts['basename']; // Use this variable for action='':
    $pageName = ucfirst($path_parts['filename']);
    
    /* PDO Connection */
    $db = new Connect;
    $pdo = $db->getDatabase();
    
    $user_login = new Login($db);
    $blog = new Journal($db);
    
    function html_escape($raw_input) {
        // important! don't forget to specify ENT_QUOTES and the correct encoding
        return htmlspecialchars($raw_input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    } 
  7. First, let me make a comment of people supposedly stealing "HTML" markup that say they are stealing their code by just changing the design/style around and moving this there and that there. It would be stealing if all they did was change the color theme and the font then called it their own, but if the actually changed the design I don't see how you can call it stealing? There is even a website to help people learn CSS http://www.csszengarden.com/

     

    As for php, it would be stealing if  someone simply grab the php from a person website by hacking by various hacking means. However, I have been stumped in the past and used a script or two in order to get that particular page working the way I want it to, but people post tutorials all over the web (some good or some bad) just for that purpose. You still 99 percent of the time have to modify the code to fit your needs for that particular website. 

     

    Just my .02 cents. 

  8. I use unorder lists and the anchor tag for the calendar I created:

        protected function currentMonth($date) {
            $this->isHoliday = new Holiday;
    
            /* Grab the current month DateTime */
            $this->current = new DateTime($date);
    
            $this->days = $this->current->format('t'); // Days in the current month:		
            /* Generate each day of the week's date */
            for ($x = 1; $x <= $this->days; $x++) {
                if ($x < 10) {
                    $this->urlDate = $this->current->format('Y') . '-' . $this->current->format('m') . '-0' . $x;
                } else {
                    $this->urlDate = $this->current->format('Y') . '-' . $this->current->format('m') . '-' . $x;
                }
    
                $this->memo = $this->checkForEntry();
                if ($this->isHoliday->checkForHoliday($this->urlDate)) {
                    /* Grab the important date(s) of the month and put it into an array */
                    $this->highlightHoliday = 'highlightHoliday';
                } else {
                    $this->highlightHoliday = \NULL;
                }
                $this->sendDate = new DateTime($this->urlDate);
                /* Figure out if the month's day is today and highlight if it is */
    
                if ($this->today->format('Y-m-d') === ($this->urlDate)) {
                    $this->highlightToday = 'highlightToday';
                } else {
                    $this->highlightToday = \NULL;
                }
                /* The Actual Link of the day of the week for the current month */
                $this->calendar[] = '<li class="calday ' . $this->highlightHoliday . ' ' . $this->memo . '"><a class="mark ' . $this->highlightToday . '" href="calendar.php?urlDate=' . htmlspecialchars($this->sendDate->format('Y-m-d')) . '&page=' . htmlspecialchars($_SESSION['page']) . '">' . $x . '</a></li>' . "\n";
            }
        }
    

    I actually find it using the get statement for the statement and the post statement (using a form) for the booking portion of the calendar. See my signature for the website with my calendar on it (you'll have to be logged in (registered) to use the scheduling portion of the calendar). 

  9. Here's something that might help you out or get you going in the right direction - I can't guarantee that it'll work for the might be bugs (errors) that I have overlooked. ;D

    <?php
    
    require('/includes/functions.php');
    require('/includes/connect.php');
    
    error_reporting(E_ALL | E_NOTICE);
    
    session_start(); // I would put this in the connect.php or a configuration file that goes at on every page (Best Option):
    
    if ($_SERVER['REQUEST_METHOD'] == "POST") {
        $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        if (empty(trim($username)) || empty(trim($password))) {
            die("You must enter your <b>username</b> and <b>password</b>");
        }
        /* Setup the Query for reading in login data from database table */
        $query= 'SELECT username, password, rank, active FROM users WHERE username=:username';
        
        try {
            $stmt = $handler->prepare($query); // Prepare the query:
            $stmt->execute([':username' => $data['username']]); // Execute the query with the supplied user's parameter(s):
        } catch (Exception $ex) {
            die("Failed to run query: " . $ex->getMessage()); // Do Not Use in Production Website - Log error or email error to admin:
        }
    
        $stmt->setFetchMode(PDO::FETCH_OBJ); // Fetch data as object(s):
        $user = $stmt->fetch(); // Fetch the data:
    
        /* If username is in database table then it is TRUE */
        if ($user) {
            $loginStatus = password_verify($password, $user->password); // Check the user's entry to the stored password:
            unset($password, $user->password); // Password(s) not needed then unset the password(s)!:
        } else {
            return FALSE; // Return if no user is found in database table:
        }
    
        /*
         * If passwords matches and user is active then set user's account into sessions
         * then in a configuration file of some sore you can do something like
         * $user = isset($_SESSION['user']) ? $_SESSION['user'] : NULL;
         * that way all you have to do to access a user who is logged in is 
         * $user->username for example (accessing the object(s))
         */
        if ($loginStatus && $user->active === 1) {
            $_SESSION['user'] = $user; // Set the session variable of user:
            return TRUE; // Everything is OK (Passwords match && user is active):
        } else {
            return FALSE; // Invalid password was entered:
        }
       
    }
    
  10. Also I think it would be easier to assemble the array (or output) first then use json_encode, for example:

    $output = json_encode($myArray);
    
    output($output);
    
    /* If there is an error then change the error to the proper code and output the */
    /* error message via Ajax /JQuery.                                              */
    function error($output, $code = 500) {
      http_response_code($code);  
      echo $output;
    }
    
    
    /* If everything validates OK then send success message to Ajax/jQuery */
    function output($output) {
      http_response_code(200);
      echo $output;
    }
  11. You can always force the action="" to have something in it by doing something like this :

     

    $phpSelf = filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_URL);
    
    
    $path_parts = pathinfo($phpSelf);
    
    
    $basename = $path_parts['basename']; // Use this variable for action='':
    $pageName = ucfirst($path_parts['filename']);
     
    <form id="calendarLogin" class="container" action="<?php echo $basename; ?>" method="post">

    now back to the OP original problem.  ;D

  12. This isn't going to totally answer you question, but it might. What I do is I set up a mock HTML page with the proper tags and CSS to it. Then I add the PHP (or whatever language you using) to that mockup, for example I did that with this page : http://www.pepster.com/calendar.php?urlDate=2015-10-16&page=0

    It'll make you should make your task simpler and actually it isn't that more work. Just look at the source code (HTML / CSS) of that page and it should give you a general idea in how to do it. 

  13. I've since switched over to Dependency Injection, but here's a Singleton Class that I modified from a book by Larry Ullman ( A good place to learn PHP)

    class Database {
    
        private $_connection;
        // Store the single instance.
        private static $_instance;
    
        // Get an instance of the Database.
        // @return Database: 
        public static function getInstance() {
            if (!self::$_instance) {
                self::$_instance = new self();
            }
            return self::$_instance;
        }
    
        // Constructor - Build the PDO Connection:
        public function __construct() {
            $db_options = array(
                /* important! use actual prepared statements (default: emulate prepared statements) */
                PDO::ATTR_EMULATE_PREPARES => false
                /* throw exceptions on errors (default: stay silent) */
                , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
                /* fetch associative arrays (default: mixed arrays)    */
                , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            );
            $this->_connection = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);
        }
    
        // Empty clone magic method to prevent duplication:
        private function __clone() {
            
        }
    
        // Get the PDO connection:    
        public function getConnection() {
            return $this->_connection;
        }
    
    }
    

    To use:

    $db = Database::getInstance();
    $pdo = $db->getConnection(); 

    I does get rid of some of the problems, but I already stated it's best to use D.I. for it's more versatile. 

  14. I would go fixing the HTML and styling it with good old CSS first. That is what I would do.

     

    For example I created an online trivia game and created where a user can add questions/answers to the database table. I first created a HTML Form styling it with CSS then I added the necessary PHP to it.

     

    Here's the form:

        <form id="addQuestions"action="<?php echo $basename; ?>" method="post">
            <fieldset>
                <legend><?php echo isset($errorMsg) ? $errorMsg : "Add Question"; ?></legend>
                <input type="hidden" name="status" value="<?php echo ($user && $user->security_level === "sysop") ? "approved" : "pending"; ?>">
                <label class="questionLabel" for="question">Question</label>
                <textarea id="question" name="question" placeholder="Enter question here..."></textarea>
                <label class="questionData" for="answer1">Answer One</label>
                <input id="answer1" type="text" name="answer1" value="">
                <label class="questionData" for="answer2">Answer Two</label>
                <input id="answer2" type="text" name="answer2" value="">
                <label class="questionData" for="answer3">Answer Three</label>
                <input id="answer3" type="text" name="answer3" value="">
                <label class="questionData" for="answer4">Answer Four</label>
                <input id="answer4" type="text" name="answer4" value="">
                <label class="questionData" for="correct">Correct Answer</label>
                <input id="correct" type="text" name="correct" placeholder="Enter 1, 2, 3, or 4 for the correct answer!" value="">
                <input type="submit" name="submit" value="submit">
            </fieldset>
        </form>
    

    as you can see not much in the way of PHP was added to it and the form also carried nicely over to the edit form (on a different web page)

        <form id="addQuestions"action="<?php echo $basename; ?>" method="post">
            <fieldset>
                <legend><?php echo isset($errorMsg) ? $errorMsg : "Edit Question"; ?></legend>
                <input type="hidden" name="id" value="<?php echo $total_ids[$_SESSION['page']]['id']; ?>">
                <label class="questionLabel" for="question">Question</label>
                <textarea id="question" name="question" placeholder="Enter question here..."><?php echo $record->question; ?></textarea>
                <label class="questionData" for="answer1">Answer One</label>
                <input id="answer1" type="text" name="answer1" value="<?php echo $record->answer1; ?>">
                <label class="questionData" for="answer2">Answer Two</label>
                <input id="answer2" type="text" name="answer2" value="<?php echo $record->answer2; ?>">
                <label class="questionData" for="answer3">Answer Three</label>
                <input id="answer3" type="text" name="answer3" value="<?php echo $record->answer3; ?>">
                <label class="questionData" for="answer4">Answer Four</label>
                <input id="answer4" type="text" name="answer4" value="<?php echo $record->answer4; ?>">
                <label class="questionData" for="correct">Correct Answer</label>
                <input id="correct" type="text" name="correct" value="<?php echo $record->correct; ?>">
                <label class="questionData" for="status">Status</label>
                <select id="status" <?php echo ($record->status === "approved") ? 'class="statusGreen"' : 'class="statusRed"'; ?> name="status">
                    <?php
                        foreach ($statusArray as $key => $value) {
                            if ( $value === $record->status) {
                                echo '<option value="' . $record->status . '" selected>' . $record->status . '</option>';
                            } else {
                                echo '<option value="'. $value . '">' . $value . '</option>';
                            }
                        }
                    ?>
                </select>
                <input type="submit" name="submit" value="submit">
    
            </fieldset>
        </form> 

    as you can see a little more PHP was needed for the edit form and a few minor modifications need to be done to the HTML/CSS. My suggestion for you and/or anyone getting started in web design and development is get HTML/CSS and maybe JavaScript portion down pat first. Even if person considers him/her a developer, it's still very important to learn the design aspect of building a website even if someone else might be doing that portion. Like I already stated that is where I would start first. HTH John

  15. I will give my .02 cents about this. I don't think I would be very pleased if I were one of the 500 users using that website to find out that the password and other information that I entered wasn't secured at all. Sure they don't know anything about programming, but Hackers do. If there isn't any valuable information in the first place why have a login system? I have logged into the a website from more than one computer (Heck I even logged onto the same computer more than once using different browsers), I really don't see what the big deal is. It's just like visiting the same web page on multiple computers in my book. 

  16. This is something that I done over a year and half ago for fun, there are few things that I would change though it gives a good example of using json:

     

    The PHP file : 

    sendCountDown.02.php

    <?php
    date_default_timezone_set('America/Detroit'); // Set the Default Time Zone:
    
    session_start();
    
    $future = (isset($_SESSION['future'])) ?  $_SESSION['future'] :  '2015-12-25 00:00:00';
    
    $expired = new DateTime($future);
    $now = new DateTime();
    
    $e['countDown'] = $now->diff($expired, true);
    
    print json_encode($e); // JSON
    
    

    web.countdown.ajax.02.js

    $(function () {
        /*  The Countdown Timer to call the Ajax Method */
        var updateTime = setInterval(displayTime, 1000);
    
        /* The Ajax Method of Getting Time */
        function displayTime() {
            var $clock = $('.clock');
    
            $.ajax({// Start of ajax:
                url: 'sendCountDown.02.php', // Pulling time from the server:         
                dataType: "json", // Format type:
                success: function (info) { // Grab the data from php and then display it:
    
                    // Variables * Self-Explanatory *
                    var days = info.countDown.days, // Grab total days till expiration:
                            hours = info.countDown.h, // Grab total hours till expiration:
                            minutes = info.countDown.i, // Grab total mins till expiration:
                            seconds = info.countDown.s, // Grab total secs till expiration:
                            $msg = '';
    
                    if (hours < 10) {
                        hours = '0' + hours;
                    }
    
                    if (minutes < 10) {
                        minutes = '0' + minutes;
                    }
    
                    if (seconds < 10) {
                        seconds = '0' + seconds;
                    }
    
                    $msg = days + ' Days ' + hours + ' Hours ' +
                            minutes + ' Minutes ' + seconds + ' Seconds';
    
                    /* Display Time in Message */
                    $clock.text($msg);
    
                },
                error: function (response) {
                    var r = jQuery.parseJSON(response.responseText);
                    alert("Message: " + r.Message);
                    alert("StackTrace: " + r.StackTrace);
                    alert("ExceptionType: " + r.ExceptionType);
                }
            }); // End of ajax call:
    
        } // End of Function:	
    
    }); // END OF DOC READY:
    

    and the main file countDownClock.php

    <?php
    session_start();
    date_default_timezone_set('America/Detroit'); // Set the Default Time Zone:
    
    if (isset($_POST['action']) && $_POST['action'] == 'enter') {
    	$futureDate = date('Y-m-d H:i:s',strtotime($_POST['futureDate']));
    	$_SESSION['future'] = $futureDate;
    }
    ?>
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title>The Count Down Clock</title>
    <link rel="stylesheet" href="css/style.css">
    </head>
    
    <body>
    
    <?php echo (isset($futureDate)) ? '<h1 class="container headingDate">' . $futureDate . '</h1>' : '<h1 class="container headingDate">Christmas Day is 2015-12-25</h1>'; ?>
    <form id="countDownForm" class="container rounded shadow" action="countDownClock.php" method="post">
      <input type="hidden" name="action" value="enter">
      <label for="countDownStyle" class="cmsLabel">Enter Future Date: </label>
      <input id="countDownStyle" name="futureDate" value="" type="datetime" placeholder="0000-00-00 00:00:00" required>
      <input type="submit" name="submit" value="Submit" class="submitBtn">
    </form>
    
    <div class="container clockBox rounded shadow">
      <p class="clock"></p>
    </div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="web.countdown.ajax.02.js"></script>
    </body>
    </html>
    

    I think it shows how one can pull the time from php; which in my opinion that the PHP language has better date/time functions/methods that jQuery/JavaScript in the first place. That can be pulled from a database or what have you. 

  17. Maybe this will shed some light on your problem:

        <form id="trivia_quiz" action="<?php echo $basename; ?>" method="post">
            <?php
            $counter = 1;
            foreach ($_SESSION['daily_questions'] as $key => $value) {
                if (strlen($counter) < 2) {
                    $counter = "0" . $counter;
                }
                echo "<h1 class=\"question\">" . $counter . ". " . $value['question'] . "</h1>\n";
                echo '<div class="answers"><input id="button' . $key . '_1" type="radio" name="answer[' . $key . ']" value="1"><label for="button' . $key . '_1">' . $value['answer1'] . '</label>' . "</div>\n";
                echo '<div class="answers"><input id="button' . $key . '_2" type="radio" name="answer[' . $key . ']" value="2"><label for="button' . $key . '_2">' . $value['answer2'] . '</label>' . "</div>\n";
                echo '<div class="answers"><input id="button' . $key . '_3" type="radio" name="answer[' . $key . ']" value="3"><label for="button' . $key . '_3">' . $value['answer3'] . '</label>' . "</div>\n";
                echo '<div class="answers"><input id="button' . $key . '_4" type="radio" name="answer[' . $key . ']" value="4"><label for="button' . $key . '_4">' . $value['answer4'] . '</label>' . "</div><br><hr><br>\n";
                $counter += 1;
            }
            ?>
            <input type="submit" name="submit" value="submit">
        </form>
    

    I find reading 10 questions in at a time and spitting them out at once is the easiest or you can use JavaScript (I use jQuery) to have only one question displayed at a time. Though there are many ways of doing it.  

  18. What I do is use placeholder names then try to keep everything constant (prepared statements, variables and what have you).

     

    for example

    $query = "UPDATE users SET username=:username WHERE id=:id";
    $stmt = $pdo->prepare($query);
    $result = $stmt->execute([':username' => $_POST['username'], ':id' => $_POST['id']]); 

    That way is easier to spot a syntax error easier in my opinion. 

  19. I think what parkerj was trying to tell you is to put your script in a code tag that is in the editor and properly formatted. 

     

    for example:

    <?php
    
    class DbConn {
    
        private $_conn = '';
    
        public function __construct() {
    
            $this->_conn = mysqli_connect('localhost', 'root', '', 'sito');
            if ($this->_conn->errno) {
                echo "errore di conessione" . $this->_conn->error;
            }
        }
    
        public function select($fields, $tables, $conditions = '1') {
            $query = "SELECT ";
            $query .= implode(', ', $fields);
            $query .= " FROM ";
            $query .= implode(', ', $tables);
            $query .= " WHERE ";
            $query .= $conditions;
    
            error_log(var_export($query, true));
            return mysqli_query($this->_conn, $query);
        }
    
        public function update($table, $values, $conditions = '1') {
            $first = true;
    
            $query = "UPDATE " . $table;
            $query .= " SET ";
    
            foreach ($values as $name => $value) {
                if (!$first) {
                    $query .= ", ";
                }
    
                $query .= $name . " = " . $value;
                $first = false;
            }
    
            $query .= " WHERE ";
            $query .= $conditions;
    
            return mysqli_query($this->_conn, $query);
        }
    
        public function delete($table, $conditions = '0') {
            $query = "DELETE FROM " . $table;
            $query .= " WHERE ";
            $query .= $conditions;
    
            return mysqli_query($this->_conn, $query);
        }
    
        public function fetch_assoc($res) {
    
            return mysqli_fetch_assoc($res);
        }
    
        public function escape($string) {
    
            return mysqli_escape_string($this->_conn, $string);
        }
    
        public function __destruct() {
    
            $this->_conn->close();
        }
    
    }
    
    if you can help you put also the view
    
    <?php
    require_once ($_SERVER['DOCUMENT_ROOT'] . "/controllers/controller_admin.php");
    require_once ($_SERVER['DOCUMENT_ROOT'] . "/modules/module_admin.php");
    require_once($_SERVER['DOCUMENT_ROOT'] . "/libreria/DbConn.php");
    
    
    $action = (isset($_GET['action'])) ? $_GET['action'] : null;
    $id = (isset($_GET['id'])) ? $_GET['id'] : null;
    $controllerAdmin = new controller_admin($action, $id);
    $result = $controllerAdmin->menuAdmin();
    ?>
    <?php if (!empty($result)): ?>
        <h2>gestione menu</h2>
        <table>
            <thead>
                <tr>
                    <th>nome Categoria</th>
                    <th>Visibilita</th>
                    <th colspan="2">Modifica</th>
                </tr>
            </thead>
        <?php foreach ($result as $risultato): ?>
            <?php
            if ($risultato['menu_visibol'] == 1) {
                $action = "?menu&action=novisibol";
                $text = "novisibol";
                $class = "novisibol";
            } else {
                $action = "?menu&action=visibol";
                $text = "visibol";
                $class = "visibol";
            }
            ?>
                <tr>
                    <td><a href="?menu&action=edit&id=<?php echo $risultato['menu_id']; ?>"
                           title="<?php echo $risultato['menu_title']; ?>"><?php echo $risultato['menu_name']; ?></a>
                    </td>
                    <td><a title="<?php echo $text; ?>" class="<?php echo $class; ?>"
                           href="<?php echo $action . '&id=' . $risultato['menu_id']; ?>"><?php echo $text; ?></a>
                    </td>
                    <td><a href="?menu&action=edit&id=<?php echo $risultato['menu_id']; ?>" title="modifica">Modifica</a></td>
                    <td><a href="?menu&action=delete&id=<?php echo $risultato['menu_id']; ?>" title="elimina">Elimina</a></td>
    
                </tr>
        <?php endforeach; ?>
        </table>
    <?php endif; ?>
    
  20. Well if a company's website is hacked, it's isn't the web developer who takes the blame in the eyes of the public,  it's the company. Though the company that is taking the blame isn't going to give the web developer a free pass and just let it slide by without taking a hit. So it should be the web developer, but a web designer might get thrown under the bus if the company doesn't distinguish between developer and designer. Though I think that is highly unlikely for most companies are smart enough to realize it's the coding that causes the problems. So my answer is who ever developed the script is the party at fault.  However, the company that gets hacked isn't going to be very pleased with anyone that had anything to do with the website.  ;D

  21. That was the major blunt of the problem, I still had a little logic error in the script though. However, fixing all the errors helped narrow it down. 

     

    If anyone wonders what the solution is, here it is:

    <?php 
    include("bouncyballdbs.php");
    
    $lowestHighScore = $_POST['lowestHighScore'];
    
    
    $todaydate     	=  date('Y-m-d H:i:s', strtotime($_POST['todaydate']));
    $playername	    =  $_POST['playername'];
    $playerscore    =  $_POST['playerscore'];
    
    $insertScore = 'INSERT INTO ' . DATABASE_TABLE . '( todaydate, playername, playerscore ) VALUES ( :todaydate, :playername, :playerscore )';
    $insertParams = array( ':todaydate' => $todaydate, ':playername' => $playername, ':playerscore' => $playerscore );
    
    $stmt = $pdo->prepare($insertScore);
    $stmt->execute($insertParams);
    try {
            /* I had to make it a <= symbol and set the limit to 1, for I only add 1 if the player gets */
            /* a high score */
    	$query = 'DELETE FROM ' . DATABASE_TABLE . ' WHERE playerscore <= :lowestHighScore LIMIT 1';
    
    	$stmt = $pdo->prepare($query);
    	$stmt->bindParam(':lowestHighScore',  $lowestHighScore, PDO::PARAM_INT);
    	$stmt->execute();
    
    } catch (PDOException $e) { // Report the Error!	
      error_log($e->getMessage(), 3, ERRORLOG_PATH);
    } 
    
    
×
×
  • 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.