Jump to content

php NOT words?


emcy

Recommended Posts

Hi, I am working on a simple login for just 1 person.. me .. to be able to update my blog online.

I would like to have the login button on the blog page itself.  I currently have it set up as a modal. 

I have the database setup for 4 columns - ID, date, title, content and signedby

I have the form page set up as well (blog.php), and the database access dbconfig.php file is written also.

1.  - wrote up the modal button so that when I click on the login/submit button it should call up pswchecking.php to verify that the username and password are me only, and that if it is true, then it will pop up the blog entry page which then enters the new entries into the database in mysqli.  (how do I write pswchecking.php? - I looked at Mysqli code in w3schools, and php and ajax.  I could maybe do it as a php/ajax file but then the text file can be found by a search on google, how do I hide it? So then I thought maybe to do a database with just one user in it.. me that felt like overkill.. not sure.. ideas?

After that, I want to automatically be able to  post the new blog entries from the database to the blog.php page automatically.  I would also like it sorted by year and month links so they don't get all the records downloaded, and it only shows the latest post.  To say the least, I would not be posting if it worked like a charm :) .  It doesn't work and I get error messages...

current code I have is as such:

1. blog.php page with a login modal button .   

<!-- Modal Content -->
	
<?php	  
//keep this in here to display all the errors on debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// SECTION A
// define the connection info
// got this info from 1and1.com directly
include('blogdbConfig.php');
     // where blogdbConfig.php is
	//<?php
	// got this info from 1and1.com directly
	//$host_name = "dbnumber.db.1and1.com";
	// $user_name = "dbonumber";
	// $password = "password";
	// $database = "dbnumber";

	// Create connection using the mysqli procedural format
	//$connect = mysqli_connect($host_name, $user_name, $password, $database);

	// Check connection
	// if (!$connect) {
    // die("Connection failed: " . mysqli_connect_error());
	// }
	// ?>

//***********NOW THAT IT'S CONNECTED TO THE DATABASE I WANT IT TO POP UP A PAGE CALLED blogentriespage.php SO I CAN MAKE A NEW DATABASE ENTRY.
//DO I USE AN INCLUDE STATMENT HERE? SUCH AS THE FOLLOWING, AND HOW DO I PUT IT ON A POP-UP PAGE?
//<?php
//include('blogentriespage.php');
//?>
 	// where blogentries.php is:
	// <?php	  
		//keep this in here to display all the errors on debugging
		// ini_set('display_errors', 1);
		// error_reporting(E_ALL);
		// include('blogdbConfig.php');
		// $connect = mysqli_connect($host_name, $user_name, $password, $database);
		// if (!$connect) {
    	// die("Connection failed: " . mysqli_connect_error());
 		// }

 		// function test_input($data) {
  		// $data = trim($data);
  		// $data = stripslashes($data);
  		// $data = htmlspecialchars($data);
  		// return $data;
 		// }	
	
		// $dateErr = $titleErr = $contentErr = $signedbyErr = "";
		// $date = $title = $content = $signedby = "";
	
 		// if ($_SERVER["REQUEST_METHOD"] == "POST") { 
		// $passed = true;

  		// if (empty($_POST["date"])) {
    	// $dateErr = "Please enter a date in the format of monthname date, full year";
	    // $passed = false;
  		// } else {
    	// $date = test_input($_POST["date"]);
 		// }
  
 		// if (empty($_POST["title"])) {
   		// $titleErr = "Title is required";
	    // $passed = false;
  		// } else {
    	// $title = test_input($_POST["title"]);
    	// if (!preg_match("/^[a-zA-Z ]*$/",$title)) {
		// $passed = false;
    	// $titleErr = "Only letters and white space allowed";
 		// }
 		// }
 
  		// if (empty($_POST["content"])) {
	  	// $contentErr = "Content is required";
	  	// $passed = false;
  		// } else {
   		// $content = test_input($_POST["content"]);
 		// }
   
		// if (empty($_POST["signedby"])) {
   		// $signedbyErr = "Signed by is required";
	    // $passed = false;
  		// } else {
    	// $signedby = test_input($_POST["signedby"]);
    	// if (!preg_match("/^[a-zA-Z ]*$/",$signedby)) {
		// $passed = false;
    	// $signedbyErr = "Only letters and white space allowed";
 		// }
 		// }

		// if ($passed) {

 		// $mysqli = "INSERT INTO xmasblogentries (date, title, content, signedby)
 VALUES ('$date','$title','$content','$signedby')";
		// if (mysqli_query($connect, $mysqli)) {
   		//  echo "New record created successfully";
 		// } else {
    	// echo "Error: " . $mysqli . "<br>" . mysqli_error($connect);
 		// }

 		// $email = "info@me.com";
 		// $emailSubject = "A new blog entry was just received in the database";

 		// $headers = "From:$signedby\r\n";
 		// $headers = "Content-type: text/html\r\n";

 		// $body = <<<EOD
 		// <br><hr><br>
 		// Date : $date <br>
 		// Title : $title <br>
 		// Content : $content <br>
 		// Signed By : $signedby <br>
		//  EOD;

 		// $success = mail($email, $emailSubject, $body, $headers);
 
 		// echo "<h2>Thank you your new blog entry was received successfully. Here is a copy of what you wrote:</h2>";
 		// echo "Date: " . $date . "<br>";
 		// echo "Title: " . $title . "<br>";
 		// echo "Content: " . $content . "<br>";
 		// echo "Signed By: " . $signedby . "<br>";
 
  		//  $date = $title = $content = $signedby = "";
        //    }
        //	}
		// ?>  
		// <p><span class="error">* required field.</span></p>
        // <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="application/x-www-form-urlencoded">
        // Date:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Date" name="date" value="<?php echo $date; ?>"><span class="error">* <?php echo $dateErr; ?></span><br>
		// Title:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Title" required name="title" value="<?php echo $title; ?>"><span class="error">* <?php echo $titleErr; ?></span><br>
		// Content:<textarea  placeholder="Content" required name="content" rows="30" cols="40" value="<?php echo $content; ?>"></textarea><span class="error">* <?php echo $contentErr; ?></span><br>
		// Signed By:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Signed By" required name="signedby" value="<?php echo $signedby; ?>"><span class="error">* <?php echo $signedbyErr; ?></span><br>
		// <input class="w3-input w3-padding-16 w3-border" type="datetime-local" required name="date" value="2017-11-16T20:00">
      	// <br>
       	// <button class="w3-button w3-black"><input type="submit" name="submit" value="Submit"></button>
       	// </form>
	 	// <?php
     	// mysqli_close($connect);
		// ?>
		// </div>
//SECTION C
// Define the connection and then connect
$connect = mysqli_connect($host_name, $user_name, $password, $database);
// this is where the debugging portion ends

// set all the fields on the new database record to empty initially to reset it from the previous entry 
// SECTION B
// check the connection
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
 }

// SECTION C
 //This tells the server what to do with the entry info when it gets to the SECTION D of this php page 
// test again and strip the user info of characters I don't want
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
 }	
	
// set all the fields on the new database record to empty initially to reset it from the previous user (do I need to autoincrement here somewhere? Maybe my database settings are wrong?)
$dateErr = $titleErr = $contentErr = $signedbyErr = "";
$date = $title = $content = $signedby = "";

	
 if ($_SERVER["REQUEST_METHOD"] == "POST") { 
// if connected to the server successfully and it requests info or is ready to receive the info....
$passed = true;
 // } else { $passed = false; }
    
// then start working on the user's info to clean it up and make sure all the fields have been filled in
  
  if (empty($_POST["date"])) {
    $dateErr = "Please enter a date in the format of monthname date, full year";
	      $passed = false;
  } else {
    $date = test_input($_POST["date"]);
 }
  
 if (empty($_POST["title"])) {
   $titleErr = "Title is required";
	     $passed = false;
  } else {
    $title = test_input($_POST["title"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$title)) {
		    $passed = false;
    $titleErr = "Only letters and white space allowed";
 	}
 }
 
  if (empty($_POST["content"])) {
	  $contentErr = "Content is required";
	  $passed = false;
  } else {
   $content = test_input($_POST["content"]);
 }
   
if (empty($_POST["signedby"])) {
   $signedbyErr = "Signed by is required";
	     $passed = false;
  } else {
    $signedby = test_input($_POST["signedby"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$signedby)) {
		    $passed = false;
    $signedbyErr = "Only letters and white space allowed";
 	}
 }

if ($passed) {

//SECTION E
 // define what $mysqli is made up of (taken from the fields in the html form code above)
 $stmt = $mysqli->prepare("INSERT INTO xmasblogentries (date, title, content, signedby)
 VALUES (':date',':title',':content',':signedby')");
$stmt->bindParam(':date', $txtdate);
$stmt->bindParam(':title', $txttitle);
$stmt->bindParam(':content', $txtcontent);
$stmt->bindParam(':signedby', $txtsignedby);
$stmt->execute();
	
//SECTION F
 // Checking the connection and verifying the user's information/$mysqli (which was defined above) has been entered into the new record in the database, then it gives a success message 
 if (mysqli_query($connect, $mysqli)) {
    echo "New record created successfully";
 } else {
    echo "Error: " . $mysqli . "<br>" . mysqli_error($connect);
 }

// SECTION G
 // define what $email, and $email Subject is made up of for when it sends an email to me to let me know someone just posted something.
 $email = "info@me.com";
 $emailSubject = "A new blog entry was just received in the database";

 // define what the headers of the email should say
 $headers = "From:$signedby\r\n";
 $headers = "Content-type: text/html\r\n";

 // define what the body of the email should say and look like
 $body = <<<EOD
 <br><hr><br>
 Date : $date <br>
 Title : $title <br>
 Content : $content <br>
 Signed By : $signedby <br>
EOD;

 $success = mail($email, $emailSubject, $body, $headers);
 
// SECTION I
 // on this same user's page on his computer in the browser window, next, print on screen a copy of what the user entered above
 echo "<h2>Thank you your new blog entry was received successfully. Here is a copy of what you wrote:</h2>";
 echo "Date: " . $date . "<br>";
 echo "Title: " . $title . "<br>";
 echo "Content: " . $content . "<br>";
 echo "Signed By: " . $signedby . "<br>";
 
 $date = $title = $content = $signedby = "";
            }
        }
?>  
  <form class="modal-content animate" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="application/x-www-form-urlencoded">>
    <div class="imgcontainer">
      <img src="http://www.me.com/pagepieces/images/me.png" alt="Avatar" width="150" height="100" class="avatar">
    </div>

    <div class="container">
      <label for="uname"><b>Username</b></label>
      <input type="text" placeholder="Enter Username" name="uname" required>

      <label for="psw"><b>Password</b></label>
      <input type="password" placeholder="Enter Password" name="psw" required>

		<button type="submit" name="submit" value="Submit">Login</button>
    </div>

    <div class="container" style="background-color:#f1f1f1">
      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
    </div>
        </form>
	<?php
        mysqli_close($connect);
?>
</div>
	 	  
<script>
// Get the modal
var modal = document.getElementById('id01');

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>	

2. I would like to make it so that when I click on the "submit" button, that it first checks to see if I have entered the correct user name and password info (do I need to make a php file such as pswchecking.php or do this in a new database for only 1 user name?) and that if it isn't me, then it sends an error message - This is what I have written up from my mixed limited understanding of javascript, php, html, etc... (note I am also getting an error in Dreamweaver on the "die("you are NOT Me You cannot access this database"; line - why? Also.. where to place the "include" for this php page?  Does it go on the modal before or after the submit button?

<?php
$user_name = "me";
$password = "mysetpasword";

// Check connection
if (!$user_name . !$password) {
    die("You are NOT Me You cannot access this database";
}
?>

3. Then, if it is me, to give a success message 

<?php
$user_name = "myword";
$password = "mypasword";

// Check connection
if (!$user_name, !$password) {
    die("You are NOT Me! You cannot access this database " . mysqli_connect_error());
}
} else {
    echo "Hi Me! Welcome Back! ";
 }
?>

4. And to pop up the blog.php page to enter a new blog entry on (how do I make it be a pop window? if its in the middle of the coding?)

<?php
$user_name = "myword";
$password = "mypasword";

// Check connection
if (!$user_name, !$password) {
    die("You are NOT Me! You cannot access this database " . mysqli_connect_error());
}
} else {
    echo "Hi Me! Welcome Back! " . include('blogentrypage.php');
 }

?>

5. This is the blog entry page

<?php	  
//keep this in here to display all the errors on debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// SECTION A
// define the connection info
// got this info from 1and1.com directly
include('blogdbConfig.php');
	
// Define the connection and then connect
$connect = mysqli_connect($host_name, $user_name, $password, $database);
// this is where the debugging portion ends

// SECTION B
// check the connection
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
 }

// SECTION C
// test again and strip the user info of characters I don't want
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
 }	
	
// set all the fields on the new database record to empty initially to reset it from the previous entry 
$dateErr = $titleErr = $contentErr = $signedbyErr = "";
$date = $title = $content = $signedby = "";

 if ($_SERVER["REQUEST_METHOD"] == "POST") { 
// if connected to the server successfully and it requests info or is ready to receive the info....
$passed = true;
 // } else { $passed = false; }
    
// then start working on the entry info to clean it up and make sure all the fields have been filled in
  
  if (empty($_POST["date"])) {
    $dateErr = "Please enter a date in the format of monthname date, full year";
	      $passed = false;
  } else {
    $date = test_input($_POST["date"]);
 }
  
 if (empty($_POST["title"])) {
   $titleErr = "Title is required";
	     $passed = false;
  } else {
    $title = test_input($_POST["title"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$title)) {
		    $passed = false;
    $titleErr = "Only letters and white space allowed";
 	}
 }
 
  if (empty($_POST["content"])) {
	  $contentErr = "Content is required";
	  $passed = false;
  } else {
   $content = test_input($_POST["content"]);
 }
   
if (empty($_POST["signedby"])) {
   $signedbyErr = "Signed by is required";
	     $passed = false;
  } else {
    $signedby = test_input($_POST["signedby"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$signedby)) {
		    $passed = false;
    $signedbyErr = "Only letters and white space allowed";
 	}
 }

if ($passed) {


//SECTION E
 // define what $mysqli is made up of (taken from the fields in the html form code below)
 $mysqli = "INSERT INTO blogentries (date, title, content, signedby)
 VALUES ('$date','$title','$content','$signedby')";

//SECTION F
 // Checking the connection and verifying the user's information/$mysqli (which was defined above) has been entered into the new record in the database, then it gives a success message 
 if (mysqli_query($connect, $mysqli)) {
    echo "New record created successfully";
 } else {
    echo "Error: " . $mysqli . "<br>" . mysqli_error($connect);
 }

// SECTION G
 // define what $email, and $email Subject is made up of for when it sends an email to me to let me know I just posted something.
 $email = "info@me.com";
 $emailSubject = "A new blog entry was just received in the database";

 // define what the headers of the email should say
 $headers = "From:$signedby\r\n";
 $headers = "Content-type: text/html\r\n";

 // define what the body of the email should say and look like
 $body = <<<EOD
 <br><hr><br>
 Date : $date <br>
 Title : $title <br>
 Content : $content <br>
 Signed By : $signedby <br>
EOD;

// SECTION H
 // define the action to take upon success of a new record having been created - i.e. mail it with the email info, email subject, body, and headers from the above definitions, to my email address
 $success = mail($email, $emailSubject, $body, $headers);

// SECTION I
 // on this same page on the computer in the browser window, next, print on screen a copy of what was entered
 echo "<h2>Thank you your new blog entry was received successfully. Here is a copy of what you wrote:</h2>";
 echo "Date: " . $date . "<br>";
 echo "Title: " . $title . "<br>";
 echo "Content: " . $content . "<br>";
 echo "Signed By: " . $signedby . "<br>";
 
// SECTION J
 // when everything has been done, close the database connection
    $date = $title = $content = $signedby = "";
            }
        }
	?>  
<p><span class="error">* required field.</span></p>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="application/x-www-form-urlencoded">
            Date:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Date" name="date" value="<?php echo $date; ?>"><span class="error">* <?php echo $dateErr; ?></span><br>

            Title:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Title" required name="title" value="<?php echo $title; ?>"><span class="error">* <?php echo $titleErr; ?></span><br>
					
            Content:<textarea  placeholder="Content" required name="content" rows="30" cols="40" value="<?php echo $content; ?>"></textarea><span class="error">* <?php echo $contentErr; ?></span><br>

            Signed By:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Signed By" required name="signedby" value="<?php echo $signedby; ?>"><span class="error">* <?php echo $signedbyErr; ?></span><br>

            <input class="w3-input w3-padding-16 w3-border" type="datetime-local" required name="date" value="2017-11-16T20:00">
            <!--- PLACEHOLDER Not allowed on this type ABOVE-->
            <br>
            <button class="w3-button w3-black"><input type="submit" name="submit" value="Submit"></button>
        </form>
	<?php
        mysqli_close($connect);
?>

6. Next, when I have finished entering the information for the new entry, and click submit - it goes to a Config.php file to access the database and put the info into it

<?php
// got this info from 1and1.com directly
$host_name = "me.db.1and1.com";
$user_name = "medatabaseusername";
$password = "mydatabasepsassword";
$database = "mydatabase";

// Create connection using the mysqli procedural format
$connect = mysqli_connect($host_name, $user_name, $password, $database);

// Check connection
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
}
?>

I have the entry page setup to send me a confirmation email with the new entry info. The final step is to add the information for the new posting only, on the blog.php page, as well as links to years and months for all the other postings , so not all the entries are shown at once.

<?php	  
//keep this in here to display all the errors on debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// SECTION A
// define the connection info
// got this info from 1and1.com directly
include('blogdbConfig.php');
	
// Define the connection and then connect
$connect = mysqli_connect($host_name, $user_name, $password, $database);
// this is where the debugging portion ends

// SECTION B
// check the connection
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
 }

// SECTION C
// test again and strip the user info of characters I don't want
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
 }	
	
// set all the fields on the new database record to empty initially to reset it from the previous entry 
$dateErr = $titleErr = $contentErr = $signedbyErr = "";
$date = $title = $content = $signedby = "";

 if ($_SERVER["REQUEST_METHOD"] == "POST") { 
// if connected to the server successfully and it requests info or is ready to receive the info....
$passed = true;
 // } else { $passed = false; }
    
// then start working on the entry info to clean it up and make sure all the fields have been filled in
  
  if (empty($_POST["date"])) {
    $dateErr = "Please enter a date in the format of monthname date, full year";
	      $passed = false;
  } else {
    $date = test_input($_POST["date"]);
 }
  
 if (empty($_POST["title"])) {
   $titleErr = "Title is required";
	     $passed = false;
  } else {
    $title = test_input($_POST["title"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$title)) {
		    $passed = false;
    $titleErr = "Only letters and white space allowed";
 	}
 }
 
  if (empty($_POST["content"])) {
	  $contentErr = "Content is required";
	  $passed = false;
  } else {
   $content = test_input($_POST["content"]);
 }
   
if (empty($_POST["signedby"])) {
   $signedbyErr = "Signed by is required";
	     $passed = false;
  } else {
    $signedby = test_input($_POST["signedby"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$signedby)) {
		    $passed = false;
    $signedbyErr = "Only letters and white space allowed";
 	}
 }

if ($passed) {


//SECTION E
 // define what $mysqli is made up of (taken from the fields in the html form code below)
 $mysqli = "INSERT INTO blogentries (date, title, content, signedby)
 VALUES ('$date','$title','$content','$signedby')";

//SECTION F
 // Checking the connection and verifying the user's information/$mysqli (which was defined above) has been entered into the new record in the database, then it gives a success message 
 if (mysqli_query($connect, $mysqli)) {
    echo "New record created successfully";
 } else {
    echo "Error: " . $mysqli . "<br>" . mysqli_error($connect);
 }

// SECTION G
 // define what $email, and $email Subject is made up of for when it sends an email to me to let me know I just posted something.
 $email = "info@me.com";
 $emailSubject = "A new blog entry was just received in the database";

 // define what the headers of the email should say
 $headers = "From:$signedby\r\n";
 $headers = "Content-type: text/html\r\n";

 // define what the body of the email should say and look like
 $body = <<<EOD
 <br><hr><br>
 Date : $date <br>
 Title : $title <br>
 Content : $content <br>
 Signed By : $signedby <br>
EOD;

// SECTION H
 // define the action to take upon success of a new record having been created - i.e. mail it with the email info, email subject, body, and headers from the above definitions, to my email address
 $success = mail($email, $emailSubject, $body, $headers);

// SECTION I
 // setup a new link on the blog page for the category under which it falls (i.e. year/month/date)
//i.e if a new database record was created, then post the new link on the blog page by category under year and month and date ( so it needs to be sorted in order), and show only the fresh content via an "echo" command?
  //HOW!?!?!???!

  
  
  
  
 
// SECTION J
 // when everything has been done, close the database connection
    $date = $title = $content = $signedby = "";
            }
        }
	?>  
<p><span class="error">* required field.</span></p>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="application/x-www-form-urlencoded">
            Date:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Date" name="date" value="<?php echo $date; ?>"><span class="error">* <?php echo $dateErr; ?></span><br>

            Title:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Title" required name="title" value="<?php echo $title; ?>"><span class="error">* <?php echo $titleErr; ?></span><br>
					
            Content:<textarea  placeholder="Content" required name="content" rows="30" cols="40" value="<?php echo $content; ?>"></textarea><span class="error">* <?php echo $contentErr; ?></span><br>

            Signed By:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Signed By" required name="signedby" value="<?php echo $signedby; ?>"><span class="error">* <?php echo $signedbyErr; ?></span><br>

            <input class="w3-input w3-padding-16 w3-border" type="datetime-local" required name="date" value="2017-11-16T20:00">
            <!--- PLACEHOLDER Not allowed on this type ABOVE-->
            <br>
            <button class="w3-button w3-black"><input type="submit" name="submit" value="Submit"></button>
        </form>
	<?php
        mysqli_close($connect);
?>

where blogsortedlinks.php is used to sort the information before posting it on the blog.php page: 

<?php 	  
//keep this in here to display all the errors on debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// SECTION A
// define the connection info
// got this info from 1and1.com directly
include('blogdbConfig.php');
	
// Define the connection and then connect
$connect = mysqli_connect($host_name, $user_name, $password, $database);
// this is where the debugging portion ends


/// set all the fields on the new database record to empty initially to reset it from the previous user (do I need to autoincrement here somewhere? Maybe my database settings are wrong?)
// SECTION B
// check the connection
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
 }

// SECTION C
 //This tells the server what to do with the user's info when it gets to the SECTION D of this php page (I suspect this should be after the  SECTION D but then SECTION E of defining mysqli will have to be moved down further as well)
// test again and strip the user info of characters I don't want
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
 }	
	
// set all the fields on the new database record to empty initially to reset it from the previous user (do I need to autoincrement here somewhere? Maybe my database settings are wrong?)
$dateErr = $titleErr = $contentErr = $signedbyErr = "";
$date = $title = $content = $signedby = "";

	
 if ($_SERVER["REQUEST_METHOD"] == "POST") { // if connected to the server successfully and it requests info or is ready to receive the info....
$passed = true;
 // } else { $passed = false; }
    

if ($passed) {
	
// I have a MySQL database with which I'm dynamically populating a web page. I'm building a MySQL query that fetches some dates stored in a table called blogentries that I can later echo out on the blog page with PHP. The columns in that table are id, date, title, content, and signedby. I want the user to be able to sort dates and titles alphabetically, by date (low-high) etc by clicking the relevant links on the page. This is what I've written so far:
// Run a SELECT query to get all the dates that are stored in the database
// By default, if no sorting URL variable is fed onto the page, then the SQL query becomes order by id.
// The first time you land on the blog page as plain blog.php, not blog.php?=variable, this is the query that's used

$mysqli = mysqli_query($connect,"SELECT * FROM blogentries ORDER BY date DESC");
        
// If the user chooses to sort the dates in a different way, then an HTML link will set a PHP variable onto this blog page
// We will check for that variable and change the SQL query to sort the dates in a different way
if (isset($_GET['sortby'])) {
  // Capture that in a variable by that name
  $sortby == $_GET['sortby'];
  // Now to change the SQL query based on the sorting the user chose (date high to low, low to high, alphabetical and latest first)
  if ($sortby == 'datehilo') {
    $mysqli = mysqli_query($connect,"SELECT * FROM date ORDER BY title DESC");
  }
  elseif ($sortby = 'datelohi') {
    $mysqli == mysqli_query($connect,"SELECT * FROM date ORDER BY title ASC");
  }
  elseif ($sortby = 'title') {
    $mysqli == mysqli_query($connect,"SELECT * FROM date ORDER BY title");
  }
}
	
<p><a href="blog.php?sortby=datehilo">Date (Highest-Lowest)</a></p>
<p><a href="blog.php?sortby=datelohi">Date (Lowest-Highest)</a></p>
<p><a href="blog.php?sortby=title">Alphabetical</a></p>
?>

sortedlinks.php is:

<?php 	  
ini_set('display_errors', 1);
error_reporting(E_ALL);

include('blogdbConfig.php');
	

$connect = mysqli_connect($host_name, $user_name, $password, $database);

if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
 }

 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
 }	
	

$dateErr = $titleErr = $contentErr = $signedbyErr = "";
$date = $title = $content = $signedby = "";

	
 if ($_SERVER["REQUEST_METHOD"] == "POST") { 
$passed = true;
 // } else { $passed = false; }
    

if ($passed) {
	
	
$mysqli = mysqli_query($connect,"SELECT * FROM blogentries ORDER BY date DESC");
 // I copied the folowing code from somewhere else and am wondering if I need to make abother php page or something that identifies the variables sortby, datehilo, datelohi, title - seems to me this coudl just be done on the mysqli database itself ?      
// If the user chooses to sort the dates in a different way, then an HTML link will set a PHP variable onto this blog page
// We will check for that variable and change the SQL query to sort the dates in a different way
if (isset($_GET['sortby'])) {
  // Capture that in a variable by that name
  $sortby == $_GET['sortby'];
  // Now to change the SQL query based on the sorting the user chose (date high to low, low to high, alphabetical and latest first)
  if ($sortby == 'datehilo') {
    $mysqli = mysqli_query($connect,"SELECT * FROM date ORDER BY title DESC");
  }
  elseif ($sortby = 'datelohi') {
    $mysqli == mysqli_query($connect,"SELECT * FROM date ORDER BY title ASC");
  }
  elseif ($sortby = 'title') {
    $mysqli == mysqli_query($connect,"SELECT * FROM date ORDER BY title");
  }
}
include('blogentryretrieval.php');	
<p><a href="blog.php?sortby=datehilo">Date (Highest-Lowest)</a></p>
<p><a href="blog.php?sortby=datelohi">Date (Lowest-Highest)</a></p>
<p><a href="blog.php?sortby=title">Alphabetical</a></p>
?>

and finally blogentryretrieval.php

<?php
// got this info from 1and1.com directly
$host_name = "dbnumber.db.1and1.com";
$user_name = "dbonumber";
$password = "password";
$database = "dbnumber";

// Create connection using the mysqli procedural format
$connect = mysqli_connect($host_name, $user_name, $password, $database);

// Check connection
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
}

$mysqli = "SELECT date, title, content, signedby FROM blogentries";
$result = $connect->query($mysqli);

if ($result->num_rows > 0) {
	echo "<table><tr><th>Date</th><th>Title</th><th>Content</th><th>Written by:</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["date"]. "</td><td>" . $row["title"]. "</td><td> " . $row["content"]. "</td><td>" . $row["signedby"]. "</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}

$connect->close();
?> 

The error messages I am getting are as follows:

on the blog.php page when I call it up initially it says this: 

Warning: include(blogsortedlinks): failed to open stream: No such file or directory in /homepages/42/htdocs/blog.php on line 375
Warning: include(): Failed opening 'blogsortedlinks' for inclusion (include_path='.:/usr/lib/php5.6') in /homepages/42/htdocs/blog.php on line 375
Date: Notice: Undefined index: date in /homepages/42/htdocs/blog.php on line 378
Title: Notice: Undefined index: title in /homepages/42/htdocs/blog.php on line 379
Content: Notice: Undefined index: content in /homepages/42/htdocs/blog.php on line 380
Author: Notice: Undefined index: signedby in /homepages/42/htdocs/blog.php on line 381

When I click on the login button.. it calls up the modal fine....but.. it disappears when I click on submit and doesn't do anything.... I also don't know where to put my username and password in a database or on a separate php file to sore it permanently so the modal can call on it to verify I am the right person ....ideas?

Thanks

B

Edited by emcy
Link to comment
Share on other sites

If you want to check the username and password, send it to PHP (it doesn't matter if you use ajax or not), and authenticate it using however you want.  You can look up details in a file (it doesn't have to web-accessible), you can look it up in a database, or just hard-code the username and password and check for that.  Return a response indicating whether it was successful or not, and save it in the session so you can check that on later requests.

note I am also getting an error in Dreamweaver on the "die("you are NOT Me You cannot access this database"; line - why?

You have a syntax error, you're missing a parenthesis.  That's also not the way to check a username and password, you need to get the one you typed into the form first.  Your if statement isn't going to work either, you're using string concatenation to concatenate 2 boolean values.  I'm not even sure what that's going to do, but it's similar to checking the text "falsefalse", as in if("falsefalse").

if (!$user_name, !$password) {

I'm not sure what that's going to do either, where are you getting this syntax from?  Where did you see to separate things in an if statement with a comma?

And to pop up the blog.php page to enter a new blog entry on (how do I make it be a pop window? if its in the middle of the coding?)

That's not PHP, that's Javascript.  Anything that happens on the page after it's loaded is Javascript, CSS, HTML, etc.  PHP runs on the server, not inside the browser.  Things like animation, popups, etc happen on the client side in the browser, not on the server.  PHP runs when the browser sends a request to the server, and the server sends the response back to the browser.

Warning: include(blogsortedlinks): failed to open stream: No such file or directory

That means it can't find the file you're trying to include.

Date: Notice: Undefined index: date

Undefined index errors happen when you try to access an array index that hasn't been defined.  If you try to access, for example, $_POST['date'], but that doesn't exist, you get that error.

Link to comment
Share on other sites

HI Thanks!.. ok

 

Here is what I did.... This first part (blog.php) is for:

1. create  the modal button on the page

2.when a user clicks on the button it opens up a modal asking for user ID and password

3.when the user enters his info and clicks submit.. it calls up the "include" file named blogpswdefineandcheck.php (see below blog.php)

blog.php

<!-- Button to open the modal login form -->
<button onclick="document.getElementById('id01').style.display='block'">Login</button>

<!-- The Modal -->
<div id="id01" class="modal">
  <span onclick="document.getElementById('id01').style.display='none'" 
class="close" title="Close Modal">×</span>

  <!-- Modal Content -->
<?php>
  ini_set('display_errors', 1);
error_reporting(E_ALL);

include('blogpswdefineandcheck.php');

  function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
 }	
 ?>
  <form class="modal-content animate" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="application/x-www-form-urlencoded">>
    <div class="imgcontainer">
      <img src="../pagepieces/images/me.png" alt="Avatar" width="150" height="100" class="avatar">
    </div>

    <div class="container">
      <label for="uname"><b>Username</b></label>
      <input type="text" placeholder="Enter Username" name="uname" required>

      <label for="psw"><b>Password</b></label>
      <input type="password" placeholder="Enter Password" name="psw" required>

		<button type="submit" name="submit" value="Submit">Login</button>
    </div>

    <div class="container" style="background-color:#f1f1f1">
      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
    </div>
        </form>
  </div>
	 	  
<script>
// Get the modal
var modal = document.getElementById('id01');

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>	  
  

4. It checks the users input against the hardcoded username and password

5. If the user name and password match, then it shows a link for the blogentriespage.php

blogpswdefineandcheck.php

<?php
define("uname", "me" . "psw", "mypsw");
function myTest($uname, $psw) { //this $uname and $psw will come from the user's input in the form
	if ($uname == me and $psw == mypsw) {
    echo "Hi Me! Welcome Back!";
	echo '<a href="http://www.me.com/xmas/blongentriespage.php">Click here to access the blog entries page</a>';
	} else {
    echo "Have a good night! You are NOT me!";
}
}
myTest();

?>

7. The next part is for the bottom part of the blog.php page where it shows all the other entries by linked categories (i.e. Year, Month, Title) for the user to select

a. first it connects to the database via an included (blogdbConfig.php)

b. then it seeks  the columns of year, month and title

c. then it creates the links to those column's on the blog.php page (right in that section of the page), for the user to choose from

d. when the user clicks on year, month or title.. it returns the list of all the entries in that column, in a pretty way on the screen in that same section area

<?php	  
//keep this in here to display all the errors on debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// SECTION A
// define the connection info
// got this info from 1and1.com directly
include('blogdbConfig.php');
	
// Define the connection and then connect
$connect = mysqli_connect($host_name, $user_name, $password, $database);
// this is where the debugging portion ends

// Check connection
if ($connect->connect_error) {
    die("Connection failed: " . myseqli_connect_error());
} 

$mysqli = "SELECT id, date, title, content FROM myblog";
$result = $connect->query($mysqli);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<br> id: ". $row["id"]. "Date: ". $row["date"]. "Title " . $row["Title"] . "<br>";
		echo "Content: " . $row["content"] . "<br>";
    }
} else {
    echo "0 results";
}

$connect->close();
?> 

8. On the blogentriespage.php

I used my code from my contact page on this (also used my blogdbConfig.php).....

<?php	  
//keep this in here to display all the errors on debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// SECTION A
// define the connection info
// got this info from 1and1.com directly
include('blogdbConfig.php');
	
// Define the connection and then connect
$connect = mysqli_connect($host_name, $user_name, $password, $database);

// SECTION B
// check the connection
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
 }

// SECTION C
 //This tells the server what to do with the user's info when it gets to the SECTION D of this php page 
// test again and strip the user info of characters I don't want
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
 }	
	
// set all the fields on the new database record to empty initially to reset it from the previous user 
$dateErr = $titleErr = $contentErr = $signedbyErr = "";
$date = $title = $content = $signedby = "";

 if ($_SERVER["REQUEST_METHOD"] == "POST") { // if connected to the server successfully and it requests info or is ready to receive the info....
$passed = true;
 // } else { $passed = false; }
    
// then start working on the user's info to clean it up and make sure all the fields have been filled in
  
  if (empty($_POST["date"])) {
    $dateErr = "Please enter a date in the format of monthname date, full year";
	      $passed = false;
  } else {
    $date = test_input($_POST["date"]);
 }
  
 if (empty($_POST["title"])) {
   $titleErr = "Title is required";
	     $passed = false;
  } else {
    $title = test_input($_POST["title"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$title)) {
		    $passed = false;
    $titleErr = "Only letters and white space allowed";
 	}
 }
 
  if (empty($_POST["content"])) {
	  $contentErr = "Content is required";
	  $passed = false;
  } else {
   $content = test_input($_POST["content"]);
 }
   
if (empty($_POST["signedby"])) {
   $signedbyErr = "Signed by is required";
	     $passed = false;
  } else {
    $signedby = test_input($_POST["signedby"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$signedby)) {
		    $passed = false;
    $signedbyErr = "Only letters and white space allowed";
 	}
 }

if ($passed) {


//SECTION E
 // define what $mysqli is made up of (taken from the fields in the html form code above)
 $mysqli = "INSERT INTO blogentries (date, title, content, signedby)
 VALUES ('$date','$title','$content','$signedby')";

//SECTION F
 // Checking the connection and verifying the user's information/$mysqli (which was defined above) has been entered into the new record in the database, then it gives a success message 
 if (mysqli_query($connect, $mysqli)) {
    echo "New record created successfully";
 } else {
    echo "Error: " . $mysqli . "<br>" . mysqli_error($connect);
 }

// SECTION G
 // define what $email, and $email Subject is made up of for when it sends an email to me to let me know someone just posted something.
 $email = "info@me.com";
 $emailSubject = "A new blog entry was just received in the database";

 // define what the headers of the email should say
 $headers = "From:$signedby\r\n";
 $headers = "Content-type: text/html\r\n";

 // define what the body of the email should say and look like
 $body = <<<EOD
 <br><hr><br>
 Date : $date <br>
 Title : $title <br>
 Content : $content <br>
 Signed By : $signedby <br>
EOD;

// SECTION H
 // define the action to take upon success of a new record having been created - i.e. mail it with the email info, email subject, body, and headers from the above definitions, to my email address
 $success = mail($email, $emailSubject, $body, $headers);
 
// SECTION I
 // on this same user's page on his computer in the browser window, next, print on screen a copy of what the user entered above
 echo "<h2>Thank you your new blog entry was received successfully. Here is a copy of what you wrote:</h2>";
 echo "Date: " . $date . "<br>";
 echo "Title: " . $title . "<br>";
 echo "Content: " . $content . "<br>";
 echo "Signed By: " . $signedby . "<br>";
 
// SECTION J
 // when everything has been done, close the database connection
   $date = $title = $content = $signedby = "";
            }
        }
	?>  
<p><span class="error">* required field.</span></p>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="application/x-www-form-urlencoded">
            Date:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Date" name="date" value="<?php echo $date; ?>"><span class="error">* <?php echo $dateErr; ?></span><br>

            Title:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Title" required name="title" value="<?php echo $title; ?>"><span class="error">* <?php echo $titleErr; ?></span><br>
					
            Content:<textarea  placeholder="Content" required name="content" rows="30" cols="40" value="<?php echo $content; ?>"></textarea><span class="error">* <?php echo $contentErr; ?></span><br>

            Signed By:<input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Signed By" required name="signedby" value="<?php echo $signedby; ?>"><span class="error">* <?php echo $signedbyErr; ?></span><br>

            <input class="w3-input w3-padding-16 w3-border" type="datetime-local" required name="date" value="2017-11-16T20:00">
            <!--- PLACEHOLDER Not allowed on this type ABOVE-->
            <br>
            <button class="w3-button w3-black"><input type="submit" name="submit" value="Submit"></button>
        </form>
	<?php
        mysqli_close($connect);
?>
 

I think that's all I need?.. but it still sort of doesn't work.. ideas?  What I now get is:

1. The pop up window /modal for entering a username and password comes up , and I enter my information but then when I click on submit, it disappears and does not open the blogentries page

2. I get this error message: 

Notice: Trying to get property of non-object in /homepages/42//htdocs/xmas/blog.php on line 223
0 results


Search the blog for particular dates and entries

 

3. There are no links above as you can see... only the title"Search the blog for particular dates and entries".

hmm.  ideas?

Here is what line 223 is in blog.php

<?php	  
//keep this in here to display all the errors on debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// SECTION A
// define the connection info
// got this info from 1and1.com directly
include('blogdbConfig.php');
	
// Define the connection and then connect
$connect = mysqli_connect($host_name, $user_name, $password, $database);
// this is where the debugging portion ends

// Check connection
if ($connect->connect_error) {
    die("Connection failed: " . myseqli_connect_error());
} 

$mysqli = "SELECT id, date, title, content FROM myblog";
$result = $connect->query($mysqli);

//line 223
if ($result->num_rows > 0) { 
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<br> id: ". $row["id"]. "Date: ". $row["date"]. "Title " . $row["Title"] . "<br>";
		echo "Content: " . $row["content"] . "<br>";
    }
} else {
    echo "0 results";
}

$connect->close();
?> 
		<hr>
		<p>Search the blog for particular dates and entries</p>

Thanks

B

Edited by emcy
updated and found some solutions but...
Link to comment
Share on other sites

First off, when you're doing any kind of login system you need to use the session to keep track of who is logged in, and check that on any page that requires authorization.  You're not checking if you're logged in on the page where you add an entry, so anyone who knows the URL can use that without logging in.  That's bad.  Trying to keep a URL hidden as the only means of security is not protection.

Try to limit the code you post to only what you have questions about, giving too much information can be just as unhelpful as not enough information.

The pop up window /modal for entering a username and password comes up , and I enter my information but then when I click on submit, it disappears and does not open the blogentries page

Well, that's what you're telling it to do.  You have a form that submits to itself and not much else.  That file does not get included only when the form gets submitted, you always include it.  And since for some reason you put the block of PHP code which includes that file inside the HTML where you define the content of the hidden form, anything that the file outputs is going to be inside the hidden HTML when the page reloads.  So even if that worked to print the link to the next page, it's going to be inside the hidden HTML when the page reloads.

You also have this:

function myTest($uname, $psw) { //this $uname and $psw will come from the user's input in the form
	if ($uname == me and $psw == mypsw) {
    echo "Hi Me! Welcome Back!";
	echo '<a href="http://www.me.com/xmas/blongentriespage.php">Click here to access the blog entries page</a>';
	} else {
    echo "Have a good night! You are NOT me!";
}
}
myTest();

You define the function to take 2 parameters, but then you call it with no parameters.  You're not passing the username and password to the function.

define("uname", "me" . "psw", "mypsw");

That's not right either.  Look at the documentation for define:

http://php.net/manual/en/function.define.php

It takes 2 required parameters and an optional third one.  In your line of code above you're passing 3 parameters: the text "uname", the text "mepsw", and the text "mypsw".  So you're telling it to define a constant called "uname" with the value "mepsw", and even though the third parameter is supposed to be a boolean and you pass a string, it's going to end up making that constant case-insensitive.

I'm not sure where you got the idea that you can use a dot to define 2 constants at once, but whoever told you that didn't know what they were talking about.

I get this error message:

First, you're mixing object-oriented and procedural mysqli code.  Pick one and stick with it.  If you want to use object-oriented then don't use mysqli_connect, create a new mysqli object instead.  Second, that error probably means that your query failed but you're not checking for errors with the query.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...