Jump to content

Strider64

Members
  • Posts

    470
  • Joined

  • Last visited

  • Days Won

    12

Posts posted by Strider64

  1.  

    Both scripts are poor, but the second one is even worse than the first.

     

    First of all, you can't just dump a PHP value into your HTML markup, especially when that value comes from the user. This makes your application wide open to cross-site scripting attacks and leads to all kinds of bugs. Every value which isn't hard-coded must be escaped with htmlspecialchars().

     

    Mixing PHP logic and HTML markup is generally poor style. It quickly turns your application into an unreadable, unmaintainable mess. One of the most important principles of modern programming is that separate aspects should in fact be separated: The PHP code is for the logic, the HTML markup is for the presentation. Both are only loosely coupled; for example, instead of generating an HTML document, you might as well create a PDF file or an Excel sheet or whatever.

     

    So what you should do is keep your PHP and your HTML separate: Put all the code on top of the script and move all the HTML to the bottom. When you're more experience, you should also consider using a template engine like Twig.

     

    Last but not least, you really need to start writing proper HTML. Maybe this was just a quick example, but invalid markup and ancient elements like font are just lame.

     

    A sanitized version of the code might look like this:

    <?php
    
    // The parameter may or may not be present; we need to actually check this.
    $color = null;
    if (isset($_GET['clr']))
    {
        $color = $_GET['clr'];
    }
    
    ?>
    <!DOCTYPE HTML>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <title>Test</title>
        </head>
        <body>
            <?php if ($color): ?>
                <p>The color you chose is: <?= htmlspecialchars($color, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></p>
            <?php else: ?>
                <p>Please choose a color</p>
            <?php endif; ?>
        </body>
    </html>
    

    I personally don't like mixing PHP and html code for it makes it confusing it confusing for me :confused: . I personally would do the following instead:

    <?php
    
    // The parameter may or may not be present; we need to actually check this.
    $color = null;
    if (isset($_GET['clr']))
    {
        $color = htmlspecialchars($_GET['clr'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
    
    ?>
    <!DOCTYPE HTML>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <title>Test</title>
        </head>
        <body>
            <?php 
            if ($color) {
                echo "<p>The color you chose is " . $color . ". </p>\n";
            } else {
                echo "<p>Please choose a color</p>\n";
            }
            ?>
        </body>
    </html>
    

    That way you can see what is going on in PHP even though it has html in it. I know I have gotten into some heated debates in other forums over this and at one time I thought the other way. However, the main thing is that the php is secure no matter what way you do it.

  2. Look at my signature below for a login/registration script....I really hate tooting my own horn.  You can even find it in mysqli or PDO format, I personally would recommend the PDO tutorial for that's one I'm most comfortable with. 

  3. The following is how I would go about doing it in CSS:

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <style>
    .clearfix:before, .clearfix:after {	content: " ";	display: table; }
    .clearfix:after {	clear: both; }
    .clearfix { *zoom: 1; }
    body { font-size: 100%;	padding: 0;	margin: 0; }
    div.header_box {
    	position: fixed;
    	top: 0;
    	box-sizing: border-box;
    	display: block;
    	width: 100%;
    	max-width: 100%;
    	height: 100%;
    	max-height: 60px;
    	z-index: 200;
    }
    div.header {
    	width: 100%;
    	max-width: 978px;
    	height: 60px;
    	text-align: center;
    	background-color: #000;
    	z-index: 200;
    	padding: 0;
    	margin: 0 auto;
    }
    div.container {
    	position: relative;
    	top: 60px;
    	box-sizing: border-box;
    	display: block;
    	width: 100%;
    	max-width: 978px;
    	height: auto;
    	background-color: orange;
    	z-index: 100;
    	padding: 10px 30px;
    	margin: 0 auto;
    }
    h1 {
      font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif;
    	font-size: 1.4rem;
    	color: #fff;
    }
    p {
    	font-family: Arial, Helvetica, sans-serif;
    	font-size: 1.2rem;
    	line-height: 1.5;
    	color: #fff;
    }
    </style>
    </head>
    
    <body>
    <div class="header_box">
      <div class="header clearfix">
        <h1>My Website</h1>
      </div>
    </div>
    <div class="container">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, vel aut ex suscipit. Fugiat, nam, doloribus, sint atque obcaecati saepe voluptatum ullam ad reprehenderit nihil dolor numquam quod voluptate dicta non laborum debitis repudiandae consequuntur architecto ab laudantium incidunt porro sed repellendus ducimus magni deserunt voluptatem laboriosam quam deleniti assumenda eum cumque aut voluptates inventore minus in illo nobis unde magnam! Nulla, ipsa, architecto eligendi voluptatem minus incidunt deserunt nam molestias non veritatis. Voluptatem, nulla, harum, aperiam quia possimus ut suscipit recusandae quasi laboriosam vero pariatur et. Deserunt, aut, nesciunt modi suscipit est voluptatibus odit sequi. Quis, repellendus, iste, nobis maiores laborum enim aliquid veniam ab amet tempore aut hic error dolor. Fugiat, iure, dicta sit ipsa totam qui similique distinctio rem sunt deserunt voluptatibus accusantium recusandae cumque voluptatem pariatur repudiandae molestiae illum quisquam repellat vitae esse commodi ipsum unde provident sed. Quasi, eius, possimus, sequi velit distinctio totam debitis suscipit necessitatibus optio sit accusamus quia et alias obcaecati commodi voluptas magni dolorem assumenda iusto quam rerum sunt cumque ea libero ab doloribus quae fuga ducimus eligendi sed temporibus fugit officia illum quis esse placeat perspiciatis asperiores omnis odit quo sint itaque. Doloremque, expedita dignissimos optio atque nihil architecto esse quisquam eius sapiente aperiam odio sequi sit! Dolore quis recusandae omnis voluptas totam accusamus soluta tempore iste earum beatae! Voluptatem suscipit error officiis mollitia placeat aliquid similique deserunt fuga corrupti sequi. Optio, consequatur, pariatur, accusamus eligendi quidem nam distinctio qui dolorum tempora possimus consequuntur hic sunt iusto animi earum. Fugiat, iusto, harum, similique assumenda laudantium maiores fuga quidem error deleniti distinctio praesentium perspiciatis temporibus quia perferendis tempore commodi ratione. Fugit, exercitationem, earum nihil omnis nulla blanditiis temporibus obcaecati voluptatibus molestias dolorem porro unde quas! Nobis, temporibus, magnam sit et eos nemo omnis nulla laborum excepturi labore quisquam id iusto in.</p>
      <p>Quaerat, enim quod facere quos rerum modi saepe cumque voluptatum rem illum reprehenderit fugit mollitia praesentium sapiente dignissimos quis ea. Dolore reiciendis consequuntur necessitatibus placeat quae. Reiciendis, eum, blanditiis, aut quam amet corporis facilis autem maiores mollitia neque illo voluptatem architecto? Eos, esse, amet ipsum qui non laudantium quo molestias nam illum eius quia molestiae. Aspernatur, minus reiciendis cumque possimus eos eum repellendus doloribus voluptates debitis officiis eveniet tempora harum ea dignissimos eaque in nihil exercitationem culpa eligendi unde accusamus ratione dolores illum consectetur magni id nesciunt porro inventore ipsum voluptate fugit sint consequatur cupiditate accusantium quisquam mollitia officia perferendis libero et saepe optio ab aperiam ducimus laudantium laborum fuga! Ex, quia nisi reprehenderit illum sit accusamus hic debitis magnam. Repudiandae, blanditiis, molestias, et iure culpa itaque aperiam provident nam veniam nulla ullam reprehenderit! Ullam, et, amet, reiciendis eos minima at quaerat excepturi adipisci error iure repellat dolore asperiores fugit nostrum eaque unde explicabo quisquam dolorum dignissimos in natus eveniet magni. Esse, velit atque id architecto possimus reiciendis dolorum sapiente non libero repellat ipsam facere aperiam! Quo, reiciendis asperiores officiis quos veniam iusto explicabo natus et tempore ut. Aspernatur, eaque, asperiores optio placeat sunt et unde at labore molestias tenetur impedit rerum quo quod aliquid ipsa excepturi ab iste adipisci mollitia quibusdam esse autem rem cumque voluptatem saepe quae aperiam laudantium ratione ipsam iure voluptatibus libero recusandae facere. Quasi, aliquam, ipsa expedita delectus sit eveniet nesciunt fuga in omnis accusantium vero inventore placeat voluptatibus voluptates repellat eum quia possimus vel eligendi maxime veniam laborum ea est ut numquam! Necessitatibus, esse, enim, accusantium dolorum obcaecati aut praesentium harum laboriosam maxime doloremque magnam amet ea quae. Nihil natus voluptatum aliquid laboriosam itaque voluptates recusandae ea fuga. Nostrum, nesciunt, alias, explicabo quod vero molestias voluptatem deserunt repudiandae a totam quam porro consequuntur ex.</p>
      <p>Labore, sit, voluptate voluptatibus corporis error id harum neque distinctio quasi fuga unde tenetur ipsum illo nobis fugiat quis beatae? Ex, architecto, consequatur recusandae sint eaque nobis atque provident qui. Eveniet, unde nemo necessitatibus ab ducimus eligendi fuga maxime nesciunt magni architecto vel omnis consequatur ipsa! Unde, aliquam, ipsum, id, quis similique nisi sunt tenetur qui optio excepturi natus nemo eos porro sint iusto molestias placeat totam numquam. Modi, harum velit reprehenderit vero quaerat nihil veniam. Tenetur, quidem ea debitis pariatur libero consectetur beatae fugit optio accusamus itaque laborum accusantium voluptatem blanditiis culpa corporis animi voluptates quo est laudantium velit iure necessitatibus hic voluptate! Laudantium, hic omnis dolorem sunt deleniti dolore rem doloremque provident neque molestiae. Non, vero, voluptas facere ad ea debitis sunt saepe eaque quasi sapiente delectus provident cupiditate eligendi! Accusantium, aperiam, harum voluptas veritatis atque deleniti ratione asperiores nam consectetur aut delectus error tempora ullam adipisci neque debitis quos repellat? Incidunt, facere, amet, ipsum, possimus adipisci minus aliquid repellendus voluptatum accusamus maxime vitae error consequatur doloribus soluta commodi et ducimus tenetur cumque qui suscipit in voluptates iure mollitia saepe eaque sunt sapiente laborum molestias odit iusto. Quisquam officia nisi perferendis ex quibusdam quam odit quis aspernatur suscipit voluptates? Velit, nemo, perspiciatis, eius, quas quae alias rerum id ut inventore cum quo corrupti quia veniam ea labore sapiente veritatis voluptatem dolorem excepturi aliquam asperiores nam officiis quod nihil eaque voluptates error non aperiam libero voluptas. Vel, itaque, dolore, veniam ea asperiores mollitia magni sit est tempore distinctio id veritatis! Quaerat, cum, optio aspernatur consequatur dolore repellat sequi vero saepe sed odit quidem magni animi debitis ullam et veritatis perspiciatis obcaecati incidunt odio provident. Quo, ea, quam tenetur corporis a eos voluptate odit ab quidem laudantium nostrum molestias est laboriosam similique architecto ratione assumenda quasi nemo perspiciatis unde aspernatur?</p>
      <p>Id, accusantium, animi eaque minus illum ut unde molestiae accusamus quidem quasi ea iure rem natus velit nostrum cupiditate beatae voluptates assumenda numquam labore odit eos veritatis nesciunt sint soluta porro eius quae commodi voluptatum nihil neque laboriosam esse illo temporibus ab tempore recusandae officia repellat autem ex alias vero sapiente consectetur blanditiis reprehenderit repudiandae. Molestiae, accusamus, cupiditate, fuga consectetur id dolores distinctio illo recusandae obcaecati voluptates totam eius quasi voluptas soluta tempore consequuntur aliquid quidem cumque temporibus earum impedit nulla eaque. Magnam, error, beatae, et at voluptates excepturi perferendis perspiciatis consectetur quaerat sit voluptatibus laudantium tenetur amet eum officiis aperiam ipsam voluptas deleniti quos dolor assumenda mollitia blanditiis dolorum facere impedit fugit obcaecati debitis delectus ipsum incidunt provident vero earum iusto. Ipsam, maiores aut! Autem, ducimus, possimus deserunt unde deleniti dolor illo aperiam accusamus incidunt obcaecati tempora dicta aliquid atque culpa eveniet illum ab! Fuga corrupti dolorem culpa nihil libero quos autem. Iure beatae nam modi asperiores commodi. Esse, excepturi dolor doloremque ut corporis. Nostrum, sit, doloribus, eum, soluta dolores impedit obcaecati perferendis blanditiis magni tempora autem consequatur officiis aspernatur itaque voluptatibus ratione laboriosam cumque eos! Odit, fugiat, doloribus nulla iusto neque alias voluptatem numquam suscipit minus dignissimos necessitatibus fuga perferendis quidem nemo illum sed accusantium nostrum maiores in excepturi porro blanditiis eos vero aspernatur labore recusandae soluta reiciendis ab iure illo autem assumenda eveniet vel. Harum, incidunt, iure velit ex cupiditate obcaecati quod corporis enim consectetur molestiae deleniti nesciunt earum numquam assumenda temporibus dolor amet voluptatum sed explicabo ratione dolorem accusamus beatae veniam qui quia animi ab. Laudantium, eius impedit sunt nemo cupiditate veritatis commodi. Repellendus, mollitia, adipisci velit nisi esse eos at ducimus natus magni doloribus neque sunt quis commodi soluta quisquam reiciendis aut! Consequatur, accusantium, natus quia ducimus sunt repellat facilis excepturi libero atque non dolores!</p>
      <p>Quasi, aliquid, quos, earum, nihil sint commodi sed temporibus voluptate reiciendis est porro perspiciatis optio ullam! Ea, velit, temporibus, molestiae vel asperiores dolorum obcaecati pariatur aspernatur ab eveniet sunt placeat quasi tempore sint cumque mollitia debitis expedita. Debitis, magni provident autem et optio dolorem impedit enim nulla a sed. Sit, commodi, vero, tempora facere amet beatae ex nisi illum iure vel a labore mollitia architecto ab sint odio saepe earum deserunt dignissimos veritatis similique adipisci optio possimus et blanditiis eveniet voluptatibus officiis magnam aspernatur eligendi pariatur dolor dolorum minus officia odit praesentium accusamus. Minima, dolorem, doloremque, sed voluptatum vitae veritatis eaque soluta itaque architecto quisquam deserunt dolores? Eligendi in repudiandae odio adipisci perspiciatis quidem nemo. Iusto, adipisci, blanditiis tempore earum quo numquam vel quasi voluptatum necessitatibus illum fugiat odio dignissimos explicabo odit labore praesentium sunt! Dolorem, iure, praesentium, quod, blanditiis id ullam repellat quae quis necessitatibus pariatur expedita error quaerat earum reiciendis illum sequi maxime enim autem repellendus adipisci voluptas porro facere aut fuga dolorum omnis optio aspernatur ab asperiores modi! Aut, quae molestiae sunt quibusdam fugit ullam. Possimus, nam commodi nostrum aliquid sint non natus. At, voluptate, ad repellat repellendus cumque temporibus maiores deserunt voluptas eaque dicta est atque ab aspernatur delectus illum explicabo ut reprehenderit fugiat voluptates enim. Harum, similique, deleniti, maiores, fuga porro vel id optio aperiam dolorem aliquid odit enim magnam ipsam amet accusamus quas nihil sit saepe nobis ipsa quo suscipit odio molestiae nam modi. Molestias, amet, suscipit blanditiis deserunt officiis consequuntur sint voluptate dolorem earum repudiandae. Iusto, veniam autem nihil commodi animi illo voluptate error labore. Officiis, eaque, magnam, reiciendis omnis dolore veritatis doloremque odio maxime totam ducimus rem voluptatum quibusdam consequuntur dolorum officia sed consequatur architecto quam quo perspiciatis velit facilis laboriosam ex repudiandae hic. Amet, quae tempore similique repellat sit quam odio!</p>
    </div>
    </body>
    </html>
    
    

    I didn't do the footer, but it's the same principle except that position would be at the bottom instead of the top. ;D  

  4. Well I'm going to buck the trend - For best performance place your JavaScript files at the BOTTOM of the HTML page (That way you page can fully load).

    ....
    <script>JavaScript</script>
    </body>
    </html>
  5. Grabbing the Results is even easier, I made a little addition to the script:

    <?php
    /* Make the Mysqli Connection */
    $con = mysqli_connect("localhost", "username", "your_password", "myblog");
    // Check connection
    if (mysqli_connect_errno()) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    if (isset($_POST['submit']) && $_POST['submit'] == "Enter") {
    
      /* Set the SQL Statement */
      $sql = "INSERT INTO article (title, content, author) VALUES ( ?, ?, ?)";
      /* Prepare an SQL statement for execution */
      $stmt = mysqli_prepare($con, $sql);
      /* Binds variables to a prepared statement as parameters */
      mysqli_stmt_bind_param($stmt, "sss", $title, $content, $author);
      /* Grab the variables from the user's input */
      $title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_SPECIAL_CHARS);
      $content = filter_input(INPUT_POST, 'post', FILTER_SANITIZE_SPECIAL_CHARS);
      $author = filter_input(INPUT_POST, 'author', FILTER_SANITIZE_SPECIAL_CHARS);
    
      /* Execute the Statement */
      mysqli_stmt_execute($stmt);
    
      /* Close State */
      mysqli_stmt_close($stmt);
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>PHP BLOG</title>
      </head>
      <body>
        <form action="" method="post">
          Author: <input type="text" name="author">
          <br>      
          Title: <input type="text" name="title">
          <br>
          Post: <br><textarea name="post"></textarea>
          <br>
          <input type="submit" name="submit" value="Enter">
        </form>
        <br>
        <br>
    <?php
    $query = "SELECT title, content, author FROM article ORDER by id DESC LIMIT 100";
    
    if ($stmt = mysqli_prepare($con, $query)) {
    
      mysqli_stmt_execute($stmt);
    
      mysqli_stmt_bind_result($stmt, $title, $content, $author);
    
      while (mysqli_stmt_fetch($stmt)) {
        echo "<h1>" . $title . "</h1>\n";
        echo "<p>" . $content . "</p>\n";
        echo "<p>" . $author . "</p>\n";
      }
    
      mysqli_stmt_close($stmt);
    }
    ?>
      </body>
    </html>
    
  6. I've decided to help you out, you were close. I made comments in the code in order for you to see it step-by-step. I'm assuming in your table you have an id that auto increments and is the primary key. 

    <?php
    /* Make the Mysqli Connection */
    $con = mysqli_connect("localhost", "username", "your_password", "myblog");
    // Check connection
    if (mysqli_connect_errno()) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    if (isset($_POST['submit']) && $_POST['submit'] == "Enter") {
    
      /* Set the SQL Statement */
      $sql = "INSERT INTO article (title, content, author) VALUES ( ?, ?, ?)";
      /* Prepare an SQL statement for execution */
      $stmt = mysqli_prepare($con, $sql);
      /* Binds variables to a prepared statement as parameters */
      mysqli_stmt_bind_param($stmt, "sss", $title, $content, $author);
      /* Grab the variables from the user's input */
      $title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_SPECIAL_CHARS);
      $content = filter_input(INPUT_POST, 'post', FILTER_SANITIZE_SPECIAL_CHARS);
      $author = filter_input(INPUT_POST, 'author', FILTER_SANITIZE_SPECIAL_CHARS);
    
    
      /* Execute the Statement */
      mysqli_stmt_execute($stmt);
    
      /* Close State */
      mysqli_stmt_close($stmt);
    
      /* Close Connection */
      mysqli_close($con);
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>PHP BLOG</title>
      </head>
      <body>
        <form action="" method="post">
          Author: <input type="text" name="author">
          <br>      
          Title: <input type="text" name="title">
          <br>
          Post: <br><textarea name="post"></textarea>
          <br>
          <input type="submit" name="submit" value="Enter">
        </form>
      </body>
    </html>
    
  7. <?php
          $setFlag = false; // Set ending html condition to false:
          $y = 1; // Current Row of Thumbnails to be Displayed:
          $x = 1; // Picture Count:
          if (isset($resultDir)) {
            while ($pictures = $resultDir->fetch()) { // Fetch Picture Paths from Database:
              if ( ($x %  == 1) { // Check every 8th Picture:
                echo '<div  class="tNav shadow rounded"><ul>';
                $setFlag = true; // Set ending html condition to true:
              }
              echo  '<li><a data-row="' . $y . '" data-thumbnail="' . $x . '" id="thumb' . $x .'" class="thumbnail" href="' . htmlspecialchars($pictures->getPicName()) . '" ><img data-pic="' . $x . '" class="thumbs" src="' . htmlspecialchars($pictures->getThumbnail()) . '" alt="Thumbnails"></a></li>';
              if ( ($x %  == 0) {
                $y += 1;
                echo '</ul></div>';
                $setFlag = false; // Set ending html back to false:
              }
    
              $x += 1;
            }
          }
          if ($setFlag) echo '</ul></div>'; // If amount of pics isn't 8 set end html tags:
      ?>
    

    That's just a small part of the code and there's a whole lot more that goes with it - Here's what it looks like when finished - http://www.blissfulpicture.com/index.php  ;D

     

    ....and before I could do that I had to walk http://www.jrpepp.com/displayPage.php?page=188 No, one here is going to write you the code for these forums are to help learn. 

  8. I didn't do the onclick  warning, but I figure you can figure that out. That's just making the page spiffy anyways. ;D  This is how I would do it, though it could be modified to fit your needs, specially if you're pulling in the $user variable from someplace else.

    <?php 
    $id=64; // Temporay id variable:
    $user = 'Clint Eastwood'; // Temporary user name variable:
    ?>
    <!DOCTYPE HTML>
    <html lang="en"> 
    <head>
    	<meta charset="UTF-8">
    	<title>Home Page</title>
    </head>
    <body>
    	
    	<div class="record" >
    		<div class="delete-record">
    			<a class="delete" data-user="<?php echo $user; ?>" data-id="<?php echo $id; ?>" href="delete.php">Delete Record</a> 
    		</div>
        <span id="result"></span>
    	</div>	
    	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    	<script>
    		$(function() {
    			var $delBtn = $('a.delete'),
    			    $myURL  = $('a.delete').attr('href'),
    			    $user   = $('a.delete').data('user'),
    			    $id     = $('a.delete').data('id');
    			
    			console.log($myURL, $user, $id);
    			$delBtn.on('click', function(event) {
    				event.preventDefault();
    				var params = { id: $id, user: $user }; // Set parameters
    				var myData = jQuery.param( params ); // Set parameters to corret AJAX format				
    				$.ajax({
    					type:"post",
    					url:$myURL, // Set the URL to from the href attribute in the anchor tag:
    					data: myData,
    					success:function(info){
    						$('#result').html(info); // Display the result back when deleted: 
    					}
    				});	// End of Ajax function:							
    			}); // End of Delete Button
    
    		});	// End of Doc Ready Function:
    	</script>
    </body>
    </html>
    

    Below is the delete.php file that I tested it out with:

    <?php
    echo $result = $_POST['id'] . ' ' . $_POST['user'];
    
  9. If you just want a simple CSS solution -

    body{
    min-height: 1000px;
    max-height: auto;
    overflow-y : auto;
    }
    

    The above code will make sure that your <footer> always starts after a minimum height of 1000px. So, when content is less, footer starts after 1000px and if body content is big, it automatically gets pushed down. 

    Oops, I didn't see the overflow-y, but I still don't like the solution for the simple fact that you are relying on information that could possibly be discarded (from a design point of view in the future) because of the overflow.  Though it does work.

  10. I have made an online quiz https://www.pepster.com/ in php, jQuery and Ajax, but with that said I think you logic is reversed. You should wait on the user's response, may be something like:

    <?php
    $result['question'] = 'Who portrayed Ferris Bueller in "Ferris Bueller\'s Day off"?';
    $result['answer1'] = 'Tom Hanks';
    $result['answer2'] = 'Matthew Broderick';
    $result['answer3'] = 'Alan Ruck';
    ?>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    </head>
    
    <body>
    <?= '<h1>' . $result['question'] . '</h1>'; ?>
    <form action="myQuiz.php" method="post">
    	 <input type="radio" name="answerA" value="A"> <?php echo $result['answer1']; ?> <br>
    	 <input type="radio" name="answerB" vluee="B"> <?php echo $result['answer2']; ?> <br>
    	 <input type="radio" name="answerC" value="C"> <?php echo $result['answer3']; ?> <br>
       <input type="submit" name="submit" value="Submit">
    </form>
    </body>
    </html>
    

    Then check against the database table against the user's response.

    If you want to get a detail look into how to build a quiz I made a tutorial: http://www.jrpepp.com/tutorialTrivia.php

     

    Note: the tutorial doesn't match the actual game play for I have been improving the trivia game myself, but it should give you an idea how to go about building a php quiz.

     

  11. Here's something I did for a college course - http://jsfiddle.net/Strider64/3G7nP/

     

    It's just a simple accordion and all I did was convert it over to information  fruits, veggies, and dairy for my script had images and my own lightbox attached to it. I have been making my own library of scripts that way I don't have to re-invent the wheel every new project. Anyways, I hope it will help you out a little.

     

    It might have a few quirks in it, for like I said I converted it over from an old college project.

  12. I used to run a bbs (bulletin board service who don't know what that is) and even then people could get double accounts. I once had the notion of only having one phone per account (Back then verification was done by bbs software actually calling back the user's computer), but thought that a household could have more than one person for that phone (I know you are thinking boy was I stupid, but remember I was only 13-16 at the time). The only way I can think of not having people creating double accounts is having a membership fee, but having run a bbs for a long time I know from past experience people are cheap and want everything for free.  :happy-04:

  13. "One question for the Tom Hanks move had the answers "Castaway" and "Cast Away". Really? That's splitting hairs a bit isn't it?"  Well, there is a movie named Castaway (http://www.imdb.com/title/tt0092732/?ref_=fn_al_tt_1), so not really. :happy-04:

     

    Joking aside, I realize my scoring system is kind of messed up right now, for I have been working implementing  random questions and tweaking other things in the code. I plan on going to a certain number of question per day or a way to exit out of the questions, plus I will have a visual queue on how many questions are left ( 10 out 20 for example). Just getting the game switched over from Flash has been a chore, but like I said I have vast areas that need improving, so maybe I will lower my estimate down to 40-45 percent done. I will eventually have a better scoring system ( I have something that I have in back of mind that I am trying to implement). I will fixing the links still working after time has run out or answered (where they won't be links), with flash it was simple for all I had to do was disable the event listener. sigh. I will be diffidently improving the visuals and using a lot of your suggestions. I'll be editing my questions and answers when I get time to get rid of the grammatical and spelling errors.

     

    Thanks for the input.

  14. I'm in the process of writing an online movie trivia game in PHP, Ajax and jQuery, I have completed about 65 percent in what I want to achieve. I have it where users can add their own movie questions and once they are approved by me they will appear in the game. I eventually want to make the game play better and have where a person can log on via social media (Facebook, Google+, etc). Here's the link to the website: https://www.pepster.com/

     

    Everything is original or have permission to use,  I converted an old Flash trivia game that I developed in college and I have been spending the last month or two developing this website (along with my main website). I know haven't critique other websites, but I have notice there isn't much activity going on here lately, but I promise I will in the future. I'm look for input on game play, new features that you might like to see and over website design.

     

    Best Regards,

         John

     

     

  15. To pull it from a database table is even easier

    <?php
    
    # User class - Store user info and functions to access/control the flow of data.
    
    class User {
    
        // The member attributes containing required and optional information.
        // The attributes must correspond to the database table columns:
    
        private $id = NULL;
        private $userType = NULL; // Required (assigned enum)
        private $username = NULL; // Required 
        private $email = NULL; // Required   
        private $pass = NULL; // Required
        private $fullName = NULL;
        private $validation_code = NULL;
        private $address = NULL;
        private $city = NULL;
        private $state = NULL;
        private $zipCode = NULL;
    
        // Method returns the user ID:
        public function getId() {
            return $this->id;
        }
    
        // Grab the user's username:
        public function getUsername() {
            return $this->username;
        }
    
        // Grab the user's full name:
        public function getFullName() {
            return $this->fullName;
        }
    
        // Grab the password:
        public function getPass() {
            return $this->pass;
        }
    
        public function getUserType() {
            return $this->userType;
        }
    
        // Clear the password once user is logged in:
        public function clearPass() {
            $this->pass = NULL;
        }
    
        public function getEmail() {
            return $this->email;
        }
    
        // Method returns a Boolean if the user is an administrator:
        public function isAdmin() {
            return ($this->userType == 'author');
        }
    
        public function isSysop() {
            return ($this->userType == 'sysop');
        }
    
        public function isNewUser() {
            return ($this->userType == 'public');
        }
    
        // Method returns a Boolean indicating if the user is an administrator
        // or if the user is the original author of the provided page:
        public function canEditPage(Page $page) {
            return (($this->isAdmin() && ($this->id == $page->getCreatorId())));
        }
    
        // Method returns a Boolean indicating if the user is an administrator or an author:
        public function canCreatePage() {
            return ($this->isAdmin() || $this->isSysop());
        }
    
    }
    

    Then you could do something like:

    // Validate the form data:
    if (isset($_POST['action']) && $_POST['action'] == 'loginUser') {
    
        // Check against the database:
        $query = 'SELECT id, userType, username, email, pass, fullName, address, city, state, zipCode FROM users WHERE username=:username';
        $stmt = $pdo->prepare($query);
        $stmt->execute(array(':username' => $_POST['username']));
    
        $stmt->setFetchMode(PDO::FETCH_CLASS, 'User');
        $stored_user_data = $stmt->fetch();
    
       // More code goes here.....
    

    I pulled this from one of my scripts.


  16. <?php

    class user {

    private $username;
    private $id;
    private $level;
    private $forename;
    private $surname;
    private $email;
    private $dob;

    public function user($username, $id, $level, $forname, $surname, $email, $dob) {
    $this->username = $username;
    $this->id = $id;
    $this->level = $level;
    $this->forename = $forname;
    $this->surname = $surname;
    $this->email = $email;
    $this->dob = $dob;
    }

    public function destroy() {
    unset($this->username);
    unset($this->id);
    unset($this->level);
    unset($this->forename);
    unset($this->surname);
    unset($this->uemail);
    unset($this->dob);
    }

    public function setUsername($username) {
    $this->username = $username;
    }

    public function getUsername() {
    return $this->username;
    }

    public function setId($id) {
    $this->id = $id;
    }

    public function getId() {
    return $this->$id;
    }

    public function setLevel($level) {
    $this->level = $level;
    }

    public function getLevel() {
    return $this->level;
    }

    public function setForename($forename) {
    $this->foreName = $forename;
    }

    public function getForename() {
    return $this->forename;
    }

    public function setSurname($surname) {
    $this->surName = $surname;
    }

    public function getSurname() {
    return $this->surname;
    }

    public function setEmail($email) {
    $this->email = $email;
    }

    public function getEmail() {
    return $this->email;
    }

    public function setDob($dob) {
    $this->dob = $dob;
    }

    public function getDob() {
    return $this->dob;
    }

    };

    $user = new user("Jbonnett", "0", "Admin", "Jamie", "Bonnett", "jbonnett@site.co.uk", "01/09/1992");

    echo $user->getEmail();
    echo '<br>';
    echo $user->getLevel();

     

  17. If you know the items to be unchecked or checked then why don't you just update them? I'm assuming that each item has an unique id, thus you could just update the selected id rows.

     

    Interestingly I have built something similar and all I do is :

    $id = $_POST['id'];
    if ( isset($_POST['checked'])) {
    	
    	$checked = $_POST['checked'];
    	
    	$query = 'UPDATE thelist SET checked=:checked, dateAdded=NOW() WHERE id=:id';
    	
    	$stmt = $pdo->prepare($query);
    	
    	$result = $stmt->execute(array(':checked' => $checked, ':id' => $id));
    	
    }
    

    I do this real time using AJAX, but this could be modified to something that you are doing. I am guessing that it will entail using array and a loop.

     

    To see a working example of what I'm talking about : http://www.thegrocerylist.us/

     

    I would also break down what you do in sections (methods/functions), for example add function, update function(s) and delete functions. You'll be surprise that you will have about the same amount of code ( maybe even less).

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