Jump to content

Strider64

Members
  • Posts

    470
  • Joined

  • Last visited

  • Days Won

    12

Posts posted by Strider64

  1. I hope I put this in the right folder, but if not it can be moved. After spending about two days on the following code I finally have it working.

     

    Here's the code (I commented the best that I could):

    $(document).ready(function() {
    	
      var  d        = new Date(),
      $id      = $('#cmsId'),
      $title   = $('#cmsTitle'),
      $content = $('#cmsContent'),
      saveBtn  = $("#save");
      
      
        $.ajax({ // Start of ajax:
          url: 'data.php?='+d.getTime(),
          timeout: 5000, // Timeout * delay *
          cache: false, // Make sure it doesn't go to cache:
          dataType: "json", // Format type:
          success: function(info) { // Grab the data from php and then display it:
    
            // Variables * Self-Explanatory *
            var id      = info.id,
            title   = info.title,
            content = info.content;
            
            /* Display Editable Info in Form */
            $id.val(id);     
            $title.val(title);
            $content.append(content);
            
            //console.log('ID', $id, 'Title', $title, 'Content', $content);
    
          },
          error: function(request, status, error) {
            alert(status + ", " + error);
          }
      	}); // End of ajax call:
      
    
      saveBtn.click(saveFCN); // Save to database:
    
      function saveFCN(evt) {
    		evt.preventDefault(); // prevent button from firing: 
    		
    		/* Encode a set of form elements as a string for submission */
    		/* For more information goto: http://api.jquery.com/serialize/ */
    		var data = $('#sendCMS :input').serialize(); 
    		
    		/* Save Function by grabbing & sending to location save_data.php */
    		$.post($('#sendCMS').attr('action'), data , function(info) { 
    			
    		$('#debug_message').html(info); // Display the result back when saved:
    		
    	}); // End of Save:
    
    } // End of Save Function:
    
    }); // End of Doc Ready:
    

    and here's the HTML

        <form id="sendCMS" action="save_data.php" method="post">
          <input type="hidden" name="id" id="cmsId">
        	<label for="cmsTitle" class="cmsLabel">Title</label>
          <input type="text" data-id="1" class="cmsTitle" name="title" id="cmsTitle"><br><br>
          <label for="cmsContent" class="cmsLabel">Content</label><br>
          <textarea class="cmsContent" id="cmsContent" name="content"></textarea>
          
          <button id="save">SAVE</button><br><br>
        </form>
        <div id="debug_message"></div>
        
      </article>
    

    Finally here's my question (Sorry it took this long to get to the point)....I am pretty sure that it's pretty secured for it basically keeps the javascript and php separate. However, I just want to make sure from any security experts that might know different?

     

    Here's a small snippet of my php file

    $id = htmlspecialchars($_POST['id']);
    $title = htmlspecialchars(strip_tags($_POST['title']));
    $content = htmlspecialchars($_POST['content']);
    
    // Update the edited text:	 
    $query = 'UPDATE  pages SET title=:title, content=:content, dateUpdated=NOW() WHERE id=:id';
    
    // Prepare the Statement:
    $stmt = $pdo->prepare($query);
    
    // execute the statement:
    $result = $stmt->execute(array('title' => $title, ':content' => $content, ':id' => $id));
    
    if ($result) {
      echo 'Data Successfully Inserted';
    } else {
      echo 'Insertion Failed!';
    }
    

    As you can see I do you use prepared statments and I like I said the php and jquery (javascript) is separated as much as I could, but I just want to make sure.

     

    Thanks in Advanced,

             John

  2. First of all make sure you have this in your HTML file

        <!-- IMPORTANT THAT THE FOLLOWING IS INCLUDED -->
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
    

    Second this is how I go about tackling different screen sizes (media devices):

    /* MOBILE NAVIGATION
    --------------------------------------------------- */
    @media only screen and (max-width: 480px)  {
    
    }
    
    /* TABLET NAVIGATION
    --------------------------------------------------- */
    @media only screen and (min-width: 481px) and (max-width: 768px) {
    
    }
    
    /* SCREEN NAVIGATION
    --------------------------------------------------- */
    @media only screen and (min-width: 769px)  {
       
    }
     
    
  3. Usually adding someone's code and trying to get it to work majority of the time ends in failure and/or leads to sloppy insecure code. Personally the best course of action is get a up-to-date book on php that focuses on the beginner to intermediate level programmer. Just my .02 cents

     

     

    Or if you want to go the online route websites such as this : http://teamtreehouse.com/join/first-week-free?cid=1027&gclid=CN65uaj2zboCFeY-Mgod8S0AgQ can get you started in the right direction. There are free websites or ones that have limited free tutorials out there on the website, just do a Google search.

  4. I just want to add I find it funny for I was reading that same tutorial and after discussion about DI, I found this http://pimple.sensiolabs.org/ while doing a Google search. When I get time I am going to use Pimple and convert it over to that instead of the database wrapper that I'm currently using.

     

    Sorry I don't mean to hijack this thread, just trying to help. I definitely like PHP Freaks for you definitely learn something new everyday.

  5. I think maybe the first one, with the variables making a little more sense is better?

    //Insert tag and blog tag id into the blog_post_tags table
    $query = 'INSERT INTO blog_post_tags (blog_post_id, tag_id) VALUES (:blog_post_tags, :tag_id)';
    $stmt = $DBH->prepare($query);
    $result = $stmt->execute(array(':blog_post_id' => $blogPostId, ':tag_id' => $tags[$tagPostition]));

    but this one would surfice:

    //Insert tag and blog tag id into the blog_post_tags table
    $blogTagNewInsert = 'INSERT INTO blog_post_tags (blog_post_id, tag_id) VALUES (:blog_post_tags, :tag_id)';
    $blogTagNewstmt = $DBH->prepare($blogTagNewInsert);
    $result = $blogTagNewstmt->execute(array(':blog_post_id' => $blogPostId, ':tag_id' => $tags[$tagPostition]));
  6.         if (preg_match("/^[0-9a-zA-Z_]{5,}$/",$username) === 0) {
                echo 'Username must be bigger than 5 chars and contain only digits, letters and underscore';
            }
    

    You could do something like the above with the digits removed from the preg_match statement?

  7. I don't know how you have your database setup, but all you have to do is check to see if the person exists in the table and return a true value. Then you can just simply use an if-statement sending a message to the user.

     

    For example here is how I do something similar:

        // Method checks to see if username isn't already taken and returns true if it is already taken:
        public function isUsernameAvailable() {
    
            // Connect to PDO database:
            $db = Database::getInstance();
            $pdo = $db->getConnection();
    
            $query = "
                SELECT
                    1
                FROM users
                WHERE
                    username = :username1
            ";
    
            $query_params = array(
                ':username1' => $this->username
            );
    
            // These two statements run the query against your database table.
            $stmt = $pdo->prepare($query);
            $result = $stmt->execute($query_params);
    
            // The fetch() method returns an array representing the "next" row from
            // the selected results, or false if there are no more rows to fetch.	   	   
            return $row = $stmt->fetch();
            // If a row was returned, then we know a matching username was found in
            // the database already and we should return a boolean value back.	   
        }
    
  8. First I'll explain what I'm trying to do, I have already created a CMS for my website using OOP in PHP  and it works great. Now, I want it so the page doesn't reload when a person adds/edits a comment. I have no problem in retrieving the data from a php file:

     

    data.php

    <?php
    
    require('includes/utilities.inc.php');
    
    $id = 80;
    
    try {
        $query = 'SELECT id, creatorId, sticky, title, content, DATE_FORMAT(dateUpdated, "%e %M %Y") as dateUpdated FROM pages WHERE id=:id';
        $stmt = $pdo->prepare($query);
        $result = $stmt->execute(array(':id' => htmlspecialchars($id)));
    
        // If the query ran OK, fetch the record into an object:
        if ($result) {
            $stmt->setFetchMode(PDO::FETCH_CLASS, 'Page');
            $page = $stmt->fetch();
            $title = $page->getTitle();
            $content = nl2br($page->getContent());
        } else {
            throw new Exception('An invalid page ID was provided to this page');
        }
        
    } catch (Exception $e) { // Catch generic exceptions
        include('views/error.html');
    }
    
    class ReadPage {
    
        public $title;
        public $content;
    
        public function __construct($title, $content) {
            $this->title = $title;
            $this->content = $content;
        }
    
    }
    
    $e = new ReadPage($title, $content);
    
    
    echo json_encode($e);
    ?>
    

    and pulling it from Jquery.

     

    index.html (I decided to post the whole javascript/html file)

    <!DOCTYPE html>
    <html>
        <head>
            <title>Demo JSON, AJAX and CMS Website</title>
            <link href="css/stylesheet.css" rel="stylesheet">
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
            <script type="text/javascript">
    
                $(document).ready(function() {
    
    
    
                    $.getJSON("data.php", function(info) { // Load data:
    
                        var updateTitle = document.getElementById('titleCMS');
                        updateTitle.innerHTML = info.title;
                        var updateContent = document.getElementById('contentCMS');
                        updateContent.innerHTML = info.content;
    
    
    
                    }); //getJSON
    
                    $("#save").click(function() {
                        
                        var content = $('#contentCMS').html();
                        
                        $.ajax(
                                {
                                    type: "POST",
                                    url: "save_data.php",                              
                                    data: {content: content},
                                    success: function(data) {
                                        $("#debug_message").html("saved file");
                                    },
                                    failure: function() {
                                        $("#debug_message").html(
                                                "An error has occured trying to save the file");
                                    }
                                });
                    });
    
                }); // ready
    
            </script>
        </head>
        <body>
            <section>
                <header></header>
                <article>
                    <div id="debug_message"></div>
                    <div id="title"><h1 id="titleCMS"></h1></div>
                    <div id="content" contentEditable="true"><p id="contentCMS"></p></div>
                    <button id="save">Save</button>
                </article>
                <footer></footer>
            </section>
        </body>
    </html>
    
    

    The problem is when I go to put the "edited" data back into the database:

     

    save_data.php:

    <?php
    $id = 80;
    $content = $_POST['content'];
       
    require('includes/utilities.inc.php');
    
       // Update the edited text:	 
        $query = 'UPDATE  pages SET content=:content, dateUpdated=NOW() WHERE id=:id';
    
        // Prepare the Statement:
        $stmt = $pdo->prepare($query);
    
        $data = array('content' => $content);
    
    
    
        // execute the statement:
        $show_details = $stmt->execute(array(':content' => $content, ':id' => $id));
    ?>
    
    

    Using firebug in Firefox I see that it adds <font size="2" face="Arial"> and other extra HTML, obvioulsy I don't want that for I have my own css styling and what have you. I am just testing this code out on my server with hopes of modifying my existing CMS website once I get this perfected. Any useful help will be greatly appreciated.

     

    Thanks John

  9. You might be able to do what you talking about with an if statement. For example I do that with a form I'm using

        protected function addForm($formPage, $sticky, $title = NULL, $content=NULL) {
            // Creat a form:
            $this->getForm = '<div id="format-form">';
            $this->getForm .= '<form action="' . $formPage . '" method="post">';
            $this->getForm .= '<input type="hidden" name="action" value="enter" />';
            
            if ($sticky == 'yes') {
                $this->getForm .= '<select id="basic" name="sticky">';
                $this->getForm .= '<option selected="selected" value="no">Sticky Thread?</option>';
                $this->getForm .= '<option value="yes">yes</option>';
                $this->getForm .= '<option value="no">no</option>';
                $this->getForm .= '<option value="sysop">sysop</option>';
                $this->getForm .= '</select>';
            }
               
            if (isset($title)) {
                $this->getForm .= '<br><br>';
                $this->getForm .= '<label class="label-styling" for="style-title" >Title</label>';
                $this->getForm .= '<br>';
                $this->getForm .= '<input type="text" maxlength="40" id="style-title" name="title" value="' . $title . '">';
                $this->getForm .= '<br>';
            }
            
            $this->getForm .= '<br><br>';
            $this->getForm .= '<label class="label-styling" for="style-textarea">Content</label>';
            $this->getForm .= '<textarea class="expanding" name="content" id="content-style">' . $content . '</textarea>';
            $this->getForm .= '<br>';
            $this->getForm .= '<input class="submit-btn-style" type="submit" name="submit" value="Submit Blog">';
            $this->getForm .= '<br>';
            $this->getForm .= '</form>';
            
            return $this->getForm;
    
  10. // A nice password hashing library for PHP 5
    // Find it here: https://github.com/ircmaxell/password_compat/blob/master/lib/password.php
    // Read the Documentation for further help:
    // NOTE: if you're not using PHP 5, there are plenty of 
    // other good password hashing libraries out there ---> JUST GOOGLE IT!
    

    Why re-invent the wheel? There are plenty of good password hashing libraries out there and I'm sure there will be other recommendations made right here. ;D

  11. <?php
    
    $r_set[0] = array
        ('url' => "https://www.example.com/",
        'url_title' => "Example",
        'snippet' => "Example",
        'rank' => 5);
    $r_set[1] = array
        ('url' => "http://forums.phpfreaks.com/",
        'url_title' => "PHPFreaks",
        'snippet' => "PHP Help",
        'rank' => 23);
    $r_set[2] = array
        ('url' => "http://us1.php.net/manual/en/function.uasort.php",
        'url_title' => "PHP Manual",
        'snippet' => "PHP Help",
        'rank' => 1);
    
    // Print the array as is:
    echo '<h2>Array As Is</h2><pre>' . print_r($r_set, 1) . '</pre>';
    
    //Rank sorting function:
    function sort_by_rank($x, $y) {
        return ($x['rank'] > $y['rank']);
    }
    
    // Sort by Rank:    
    uasort($r_set, 'sort_by_rank');
    echo '<h2> Array Sorted by Rank</h2><pre>' . print_r($r_set, 1) . '</pre>';
    
    
    

    Maybe something like the above?

  12. To have a reliable link with session info in it, spell it out using session_name() and session_id(), not SID. Example:

    echo '<a href="page2.php?' . session_name() . ' ='  . session_id() . ' ">page2</a>' ;

  13. In your HundlelyDeveloping Title, I would suggest losing the brown drop shadow for it doesn't look right. I think you can get by with just the reflection. I would also make your paragraph's font size a little smaller (1.2em / 16 px (I believe)). Since this is a portfolio website, move your work that you want to showcase to the home page. That is your very best work and if you have other work that is very good, then put that on a separate html page. You want to showcase your work and people have a tendency to have very short attention spans, so when they land on your home page then that will be the very first thing they see. This is my suggestion when it comes to a background, make it as bland as possible (meaning a dull as possible) that way people's eyes will be focused on the main part. One last suggestion never put under construction on your website, either leave it blank or don't go live with it. Like I said it's only a suggestion. Don't be afraid of white space or thinking outside the box for a few things, with the exception when it comes to having a visible navigation menu. Always have a visible menu, you want people to be able to navigate to other areas of you website. I have seen to many portfolio websites that try to be cute by hiding the navigational menu, in my opinion that drives people away.

  14. I remember Model-View-Controller this way - You separate the Data (i.e., the Model) from the Output (i.e., the View) using the Controller as the agent. An not to split hairs, but MVC isn't "technically" a design pattern. For instance I do mine this way:

     

    index.html

    <section>
    
        <?php // Fetch the results and display them:
    
        while ($page = $result->fetch()) {
        // New instance of Controller, this enables to grab
        // the person who posted their real name or user's name:    
        $postedBy = new Controller($page->getCreatorId());
        // Display the appropiate info:    
        echo '
        <article>
        <div class="blog-styling"><div class="profile-pic-style"><img src="upload/' . $postedBy->displayPic . '" alt="Profile Picture" /></div><h6 class="postedon">Posted: ' . $page->getDateUpdated() . '</h6>       
        <h1 class="style-blog-title">' . $page->getTitle() . '<span class="postedby"> by ' . $postedBy->displayName . '</span></h1>    
        <p>' . nl2br($page->getIntro()) . '  <a class="color-theme" href="page.php?id=' . $page->getId() . '">read more here...</a></p>
        </div></article>
        ';
        }
        ?>
    </section>
    
  15. Plus $app is a new instance of a class it doesn't matter what you do it is going to create an error. I still say get the procedural style down pat so you can get a grasp of php and databases. Though turning on error reporting will help you out in the long run. :shrug: 

     

    P.S. -> I know you can fetch a class and the following is a snippet of my website

        // Check that rows were returned:
        if ($result && $result->rowCount() > 0) {
            // Set the fetch mode:
            $result->setFetchMode(PDO::FETCH_CLASS, 'Page');
            // Records will be fetched in the view:
            include('views/index.html');
        } else { // Problem!
            throw new Exception('No content is available to be viewed at this time');
        }
    

    ;D

  16. Just a recommendation, but if you are new to databases and php then why are you starting out using Object-Oriented Programming Style? I would find a current book that shows procedural style programming that uses mysqli or PDO or a video tutorial.

  17. // Password must be strong
    if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $pass) === 0)
    $errPass = '<p class="errText">Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit</p>';
    }
    

    I find trying to get one RegEx to work one at a time works better, also don't hash your password until checking it ;D .

×
×
  • 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.