Jump to content

Steven

Members
  • Posts

    150
  • Joined

  • Last visited

Posts posted by Steven

  1. If I split my form process into different pages, how can I transfer the jobid from viewjob.php to insertComment.php?

    That is part of why I tried to keep everything on viewjob.php, because the way it knows what job the comment is for, is by grabbing the jobid from the url.

  2. I think I've got it:

    // check if post array contains data					if (count($_POST) > 1 ) {						// Make the query						$q = 'INSERT INTO notes (notebody, noteuser, notejob) VALUES (?,?,?)';						// Prepare the statement						$stmt = mysqli_prepare($con, $q);						// Assign the values to variables						$notebody = $_POST['notebody'];						$noteuser = $_SESSION ['userid'];						$notejob = $getid;						// Bind variables						mysqli_stmt_bind_param($stmt, 'sii', $notebody, $noteuser, $notejob);						// Execute						mysqli_stmt_execute($stmt);						if (mysqli_stmt_affected_rows($stmt) == 1) {							echo "<p>Duly noted, Mr. {$_SESSION ['username']}!</p>";							echo "<p class='small'>(You may need to reload the page to see your freshly crafted note)</p>";						} else {							echo '<p>Sadly, the query could not be executed.</p>';							echo '<p>'.mysqli_stmt_error($stmt).'</p>';						}						// Close statement						mysqli_stmt_close($stmt);						if ($q) {// If $q ran with no errors:							echo "<h3>Thank you!</h3>";							echo "<p>Your note has been added.</p>";						} else {							echo "<h3>Oops</h3>";							echo "<p>There is an error:<p>";							// Debugging message							echo "<p>".mysqli_error($con)."</p>";							echo "<p>Query: ".$q."</p>";						} // end of $q IF 						// prevent re-posting						header ('Location: '.$_SERVER['PHP_SELF'], true, 303);						exit;					}

    (Sorry about the ugly tabs in these code snippets, they keep getting messed up when I paste them here)...

     

    Anyway, I did trial-and-error, and wrapped the query with the "if count($_POST)>1)", and it appears to be working. After I write out a note and hit submit, it prints the success message just fine. When I reload the page, the new note is there. Despite the browser giving me a prompt about resending data, no duplicates are popping up. So, it seems like it is working, but should I be concerned that the browser is still complaining (via the pop-up) about resending data on refresh?

     

    Thanks

  3. There's a bug showing up that is causing comment posts to duplicate whenever the page is reloaded. My code seems like it's a mess right now. Especially the error reporting lines beneath "// POST USER NOTES". I'll just paste everything I have:

    <?php require('includes/config.php');?><!doctype html><html lang="en"><head>  <meta charset="utf-8">  <title>Modern Office | Management System</title>  <link rel="stylesheet" href="css/style.css">  <link rel="stylesheet" href="css/foundation.css"></head><body><?php session_start(); // Access the existing session. ?><div class="row"><div class="large-12 columns">	<?php include ('includes/header.php'); ?>	<?php include ('includes/navigation.php'); ?></div> <!-- / columns --></div> <!-- / row -->	<?php		$getid = $_GET['jobid'];		// ------- DISPLAY JOB DETAILS -------		if ($stmt = mysqli_prepare($con, "SELECT j.*, c.*, date_format(datein, '%M %d, %Y') AS dates			FROM jobs AS j INNER JOIN clients AS c			ON j.clientid = c.id WHERE j.jobid = ?			ORDER BY j.jobid DESC")) {			mysqli_stmt_execute($stmt);			// bind param			mysqli_stmt_bind_param($stmt, 'i', $getid);			// execute			mysqli_stmt_execute($stmt);			// bind result			mysqli_stmt_bind_result($stmt, $clientid, $jobid, $datein, $description, $id, $name, $dates);			while (mysqli_stmt_fetch($stmt)) {				echo '<div class="row">';					echo '<div class="large-3 medium-3 columns">';						echo '<div class="panel jobText--panel">';							echo '<p><strong>Job ID</strong><br>';							echo $jobid.'</p>';							echo '<p><strong>Client</strong><br>';							echo '<a href="viewclient.php?clientid='.$id.'">'.$name.'</a></p>';							echo '<p><strong>Job Date</strong><br>';							echo $dates.'</p>';						echo '</div>'; // close panel					echo '</div>'; // close large-3 column					echo '<div class="large-9 medium-9 columns">';					echo '<div class="jobText">';						echo '<h2>Job '.$jobid.'</h2>';						echo '<h3>Description</h3>';						echo '<p>'.$description.'</p>';						echo '<h3>Notes & Conversation</h3>';				}			// close stmt			mysqli_stmt_close($stmt);		}		?>	<?php		// ------- DISPLAY USER NOTES -------			if ($stmt = mysqli_prepare($con, "SELECT j.jobid, u.userid, u.username, n.* FROM notes AS n INNER JOIN jobs AS j ON n.notejob = j.jobid INNER JOIN users AS u ON n.noteuser = u.userid WHERE n.notejob = ? ORDER BY n.noteid DESC")) {			mysqli_stmt_execute($stmt);			$notejob = $getid;			// bind param			mysqli_stmt_bind_param($stmt, 'i', $notejob);			// execute			mysqli_stmt_execute($stmt);			// bind result			mysqli_stmt_bind_result($stmt, $jobid, $userid, $username, $noteid, $notebody, $noteuser, $notetime, $notejob);			// fetch values			while (mysqli_stmt_fetch($stmt)) {				echo "<p>".$notebody."</p>";			}		}	?>		<?php		// ------- POST USER NOTES -------		if (isset($_SESSION['userid'])) {			// Check for form submission			if ($_SERVER['REQUEST_METHOD'] == 'POST') {				// Initialize an error array				$errors = array();				// Check for a note entry				if (empty($_POST['note'])) {					// ...send form to the database					// Make the query					$q = 'INSERT INTO notes (notebody, noteuser, notejob) VALUES (?,?,?)';					// Prepare the statement					$stmt = mysqli_prepare($con, $q);					// Assign the values to variables					$notebody = $_POST['notebody'];					$noteuser = $_SESSION ['userid'];					$notejob = $getid;					// Bind variables					mysqli_stmt_bind_param($stmt, 'sii', $notebody, $noteuser, $notejob);					// Execute					mysqli_stmt_execute($stmt);										if (mysqli_stmt_affected_rows($stmt) == 1) {						echo "<p>Duly noted, Mr. {$_SESSION ['username']}!</p>";						echo "<p class='small'>(You may need to reload the page to see your freshly crafted note)</p>";					} else {						echo '<p>Sadly, the query could not be executed.</p>';						echo '<p>'.mysqli_stmt_error($stmt).'</p>';					}					// Close statement					mysqli_stmt_close($stmt);					 if ($q) {// If $q ran with no errors:						echo "<h3>Thank you!</h3>";						echo "<p>Your note has been added.</p>";					} else {						echo "<h3>Dag-gummit...</h3>";						echo "<p>Something happened, better nag Steve.<p>";						// Debugging message						echo "<p>".mysqli_error($con)."</p>";						echo "<p>Query: ".$q."</p>";					} // end of $q IF 				} else { // Report the errors					echo "<div calss='error'>";					echo "<h3>Error!</h3>					<p>The following error(s) occured:<br>";					foreach ($errors as $msg) { // Print each error						echo " - $msg<br> ";					}					echo "</p><p>Please try again.</p>";					echo "</div>"; // end error div				} // end of (empty($errors)) IF			} // end of the main Submit conditional			echo "<p class='small'>Hi there, {$_SESSION ['username']}. Want to leave a note? Knock yourself out:</p>";			echo "<form action='viewjob.php?jobid=".$getid."' method='post'>";				echo "<textarea name='notebody' class='textarea--notes'></textarea>";				echo "<p>";				echo "<input type='submit' label='Submit'>";			echo "</form>";		} else {			echo "<p>You are not logged in. <a href='login.php'>Go to the login page.</a>.</p>";		}	?></div> <!-- close jobText --></div> <!-- close large-7 column --></div> <!-- close row --></div> <!-- / columns --></div> <!-- / row --></body></html>

    ---- EDIT ------

     

    Came across this page: http://webprogrammings.net/tutorial/individual_topic/12

     

    I'll give this a try after I fill up my coffee mug and clear my head a bit.

  4. Alright, I added a column "notejob" and made it a foreign key of jobs.jobid. I'm running into a problem, however. It's giving me an error report of "Column 'notejob' cannot be null".

     

    Well, in the middle of writing this up, I realized my form's action was "viewjob.php". I had a hunch that my problem was because there was no corresponding jobid=$id appended to the url. I changed the form to this:

    <form action='viewjob.php?jobid=".$getid."' method='post'>

    And now it works!

  5. I'm trying to add a simple comments, or notes, system to the job/client manager app I've been working on.

     

    I have a viewjob.php page that display a particular job's details based on the jobid in the url. So,

    http://localhost/job-manager/viewjob.php?jobid=10000

    This page displays all the relevant information for the job with id 10,000. And each note that is submitted, needs to be linked with the job it is being submitted to. I have made a new table, "notes". This has the following fields: noteid (primary key), notebody, noteuser, notetime. The ID uniquely id's each individual note, notebody is the body of text that makes up the note itself, noteuser is a foreign key to my "users" table that indicates who wrote the note, and notetime is a current_timestamp to show when the note was posted.

     

    I started writing out my prepared statements, placeholders, insert queries and form, but then realized I have a problem. Whether I run the "posting script" on the same page or on something like "insertNote.php", how do I connect the note to the current jobid within "viewjob.php"?

     

    Hopefully that makes sense.

  6. So on my "viewjob.php" page, you would do something like this:

    				echo '<div class="row">';					echo '<div class="large-3 medium-3 columns">';						echo '<div class="panel jobText--panel">';							echo '<p><strong>Client</strong><br>';							echo '<a href="viewclient.php?clientid='.$id.'">'.$name.'</a></p>';							echo '<p><strong>Job Date</strong><br>';							echo $dates.'</p>';						echo '</div>'; // close panel					echo '</div>'; // close large-3 column					echo '<div class="large-9 medium-9 columns">';					echo '<div class="jobText">';						echo '<h2>Job '.$jobid.'</h2>';						echo '<h3>Description</h3>';						echo '<p>'.htmlspecialchars($description).'</p>';						echo '<h3>Notes & Conversation</h3>';					echo '</div>'; // close jobText					echo '</div>'; // close large-7 column				echo '</div>'; // close row

    But couldn't someone make an argument that it'd be best to not allow unwanted characters inside the database to begin with? I don't have any idea, really, which way is best, I've just read some people who make that argument.

  7. So, let's say I want to use strip_tags(). My big question is where do I put it?

     

    Would I do something like this?

    	// Check for a description entry	if (empty($_POST['description'])) {		$errors[] = 'You forgot to enter a description';	} else {		$description = strip_tags($_POST['description']);	}
  8. After my crash course in PHP/SQL, my brain is a bit fried. I am sure I am missing some security methods in my scripts, and would appreciate the help of some trained eyes.

     

    On my "formJobs.php" page, there are three inputs: "Client", "Date", and "Description". The first two inputs are a dropdown list and a datepicker widget, so the user (I'm assuming?) doesn't really have any option or way to submit any invalid data between those first two inputs. They can only select clients already in the "Clients" table, or pick a valid date from a valid calendar pop-out. So I'm not worried about validating and sanitizing those entries, as they should be valid, in theory, because the user has no ability to tinker with it.

     

    But, with the "Description" input, which is a simple textbox that allows the user to give a brief description of the job, is wide open right now. The only thing I have in place is a snippet that makes sure a description is filled out.

     

    Here's my "formJobs.php" page:

    <?php require('includes/config.php'); ?><!doctype html><html lang="en"><head>  <meta charset="utf-8">  <title>Modern Office | Management System</title>  <link rel="stylesheet" href="css/style.css">  <link rel="stylesheet" href="css/foundation.css">  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>  <script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>  <script type="text/javascript" src="js/formhint.js"></script>    <script type="text/javascript">        $(document).ready(function(){            //  Focus auto-focus fields            $('.auto-focus:first').focus();            //  Initialize focus-glow fields            $('INPUT.focus-glow, TEXTAREA.focus-glow').focus(function(){                if($(this).val() == $(this).attr('title')){                    $(this).val('');                    $(this).removeClass('focus-glow');                }            });            $('INPUT.focus-glow, TEXTAREA.focus-glow').blur(function(){                if($(this).val() == '' && $(this).attr('title') != ''){                    $(this).val($(this).attr('title'));                    $(this).addClass('focus-glow');                }            });            $('INPUT.focus-glow, TEXTAREA.focus-glow').each(function(){                if($(this).attr('title') == ''){ return; }                if($(this).val() == ''){ $(this).val($(this).attr('title')); }                else { $(this).removeClass('focus-glow'); }            });        });    </script>    <script type="text/javascript">    // The following script adds auto-complete functionality    // to the client name field, pulling clients from the DB        $(function() {            $(".auto").autocomplete({                source: "search.php",                minLength: 1            });        });    </script>    <script type="text/javascript">    // This script allows the jQuery Datepicker    // widget to be used for the three date fields        $(function() {            $( ".datepicker" ).datepicker({                dateFormat: 'yy-mm-dd'            });        });    </script></head><body><div class="row"><div class="large-12 columns">    <?php include ('includes/header.php'); ?>    <?php include ('includes/navigation.php'); ?></div> <!-- / columns --></div> <!-- / row --><div class="row"><div class="large-12 columns">    <h2>Add a new job</h2></div> <!-- / columns --></div> <!-- / row --><div class="row"><div class="large-8 columns large-centered">    <div class="panel">            <?php// Check for form submissionif ($_SERVER['REQUEST_METHOD'] == 'POST') {    // Initialize an error array    $errors = array();    // Check for a client entry    if (empty($_POST['clientid'])) {        $errors[] = 'You forgot to enter a client';    } else {        $clientid = ($_POST['clientid']);    }    // Check for a date entry    if (empty($_POST['datein'])) {        $errors[] = 'You forgot to enter the date';    } else {        $datein = ($_POST['datein']);    }    // Check for a description entry    if (empty($_POST['description'])) {        $errors[] = 'You forgot to enter a description';    } else {        $description = trim($_POST['description']);    }    // If it's all good...    if (empty($errors)) {        // ...send form to the database        // Make the query        $q = 'INSERT INTO jobs (clientid, datein, description) VALUES (?,?,?)';        // Prepare the statement        $stmt = mysqli_prepare($con, $q);        // Asign the values to variables        $clientid = $_POST['clientid'];        $datein = $_POST['datein'];        $description = $_POST['description'];        // Bind the variables        mysqli_stmt_bind_param($stmt, 'iss', $clientid, $datein, $description);        // Execute        mysqli_stmt_execute($stmt);        // Close the statement        mysqli_stmt_close($stmt);        if ($q) { // if $r ran with no errors            echo "<h3>Thank you!</h3>";            echo "<p>The job has been successfully recorded.</p>";        } else { // if $r ran with errors            echo "<h3>Oh, bother...</h3>";            echo "<p>Something goofed. Sorry about that.</p>";            // Debugging message            echo "<p>".mysqli_error($con)."</p>";            echo "<p>Query: ".$q."</p>";        } // end of $r IF    } else { // Report the errors        echo "<div class='error'>";            echo "<h3>Error!</h3>            <p>The following error(s) occurred:<br>";            foreach ($errors as $msg) { // Print each error                echo " - $msg<br> ";            }            echo "</p><p>Please try again.</p>";        echo "</div>"; // close error div    } // end of (empty($errors)) IF} // end of the main Submit conditional?><!-- FORM!! -->    <form action="formJobs.php" method="post">    <p>        <label>Client:</label>        <?php            // prepare statement            if ($stmt = mysqli_prepare($con, "SELECT * FROM clients")) {                mysqli_stmt_execute($stmt);                // bind variables to prepared statement                // list all* columns in order of tables selected!                mysqli_stmt_bind_result($stmt, $id, $name);                // fetch values                echo "<select name='clientid'>";                    while (mysqli_stmt_fetch($stmt)) {                        echo "<option value='".$id."'>".$name."</option>";                    }                echo "</select>";            }    ?>    <br>        <label>Date Received:</label>        <input type="date" name="datein" class="focus-glow datepicker job--dateinInput" size="23">    <span class="job--dateinHint">Date placed</span><br>                <label>Description:</label>        <textarea type="text" maxlength="600" name="description" class="focus-glow"  size="28"></textarea>        <input type="submit" label="Submit">    </form>    <p class="viewResults"><a href="resultsJobs.php">View results</a></p>    </div> <!-- / panel --></div> <!-- / columns --></div> <!-- / row --></body></html>

    Thanks!

  9. I'm sure,

    // prepare statementif ($stmt = mysqli_prepare($con, "SELECT jobs.*, clients.* FROM jobs JOIN clients WHERE clientid=id ORDER BY jobs.jobid DESC")) {	mysqli_stmt_execute($stmt);	// bind variables to prepared statement	// list all* columns in order of tables selected!	mysqli_stmt_bind_result($stmt, $clientid, $jobid, $datein, $description, $id, $name);	// fetch values	while (mysqli_stmt_fetch($stmt)) {		echo "<tr>";		echo '<td><a href="viewjob.php?jobid='.$jobid.'">'.$jobid.'</a></td>';		echo "<td>$clientid</td>";		echo '<td><a href="viewclient.php?clientid='.$clientid.'">'.$name.'</a></td>';		echo "<td>$datein</td>";		echo "<td>$description</td>";		echo "</tr>";	}	echo "</table>";	// close statement	mysqli_stmt_close($stmt);}

    Returns what is in the attached image.

     

    (and yes, this particular page doesn't have the placeholder in the prepared statement yet, haven't updated all the pages yet)

     

    But the SQL works, I was just hoping one of you would have an easy answer as to why it isn't working in the PHP.

     

    (and all those entries that have "0000-00-00" are from when I was doing a bunch of tests and I had the date set as an integer and not a string)

    post-12664-0-63145700-1396035024_thumb.jpg

  10. After some fiddling I tweaked it like this:

    		$getid = $_GET['jobid'];		// prepare statement		if ($stmt = mysqli_prepare($con, "SELECT j.*, c.*, date_format(datein, '%M %d, %Y') AS dates FROM jobs AS j INNER JOIN clients AS c ON j.clientid = c.id WHERE j.jobid = ? ")) {			mysqli_stmt_execute($stmt);			// bind param			mysqli_stmt_bind_param($stmt, 'i', $getid);			// execute			mysqli_stmt_execute($stmt);			// bind result			mysqli_stmt_bind_result($stmt, $clientid, $jobid, $datein, $description, $id, $name, $dates);			while (mysqli_stmt_fetch($stmt)) {				echo '<h2><span class="fontweight500">Job-'.$jobid.'</span> — '.$name.'</h2>';				echo '<p>Ordered: '.$dates.'</p>';				echo '<p>Notes: '.$description.'</p>';			}			// close stmt			mysqli_stmt_close($stmt);		}

    The placeholder seems to be working. Thanks.

  11. What does this do?

    "SELECT * FROM jobs j, clients c WHERE j.clientid = c.id AND j.jobid = $id"

     

    What it does, is pulls data from two tables: Jobs and Clients. The $id variable comes from a GET, which is pulling the job id from the url. The page this is being used on is a viewjob page, that displays a single job (from the jobs table) and all the details of that job.

     

    Here is a bigger picture of the code:

    <?php	$id = $_GET['jobid'];	// prepare statement	if ($stmt = mysqli_prepare($con, "SELECT j.*, c.*, DATE_FORMAT(datein, '%M %d, %Y') AS datein FROM jobs AS j INNER JOIN clients AS c ON j.clientid = c.id WHERE j.jobid = $id")) {		mysqli_stmt_execute($stmt);		// bind variables to prepared statement		// list all* columns in order of tables selected!		mysqli_stmt_bind_result($stmt, $clientid, $jobid, $datein, $description, $id, $name);		// fetch values		while (mysqli_stmt_fetch($stmt)) {			echo '<h2><span class="fontweight500">Job-'.$jobid.'</span> — '.$name.'</h2>';			echo '<p>Ordered: '.$datein.'</p>';			echo '<p>Notes: '.$description.'</p>';		}	// close statement		mysqli_stmt_close($stmt);	}?>

    "datein" is a column from the jobs table. Here are all the columns:

     

    "Jobs" Table: clientid, jobid, datein, description

    "Client" Table: id, name

×
×
  • Create New...