PrinceTaz Posted August 31, 2014 Share Posted August 31, 2014 So I started a blog project just to help me out with learning php.This is my post form <form action="insert.php" method="post"> Title: <input type="text" name="title"> <br> Post: <input type="text" name="post"> <br> Author: <input type="text" name="author"> <br> <input type="submit"> </form> Insert.php<?php $con = mysqli_connect("localhost","test","","test"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // escape variables for security $title = mysqli_real_escape_string($con, $_POST['title']); $content = mysqli_real_escape_string($con, $_POST['post']); $author = mysqli_real_escape_string($con, $_POST['author']); $sql="INSERT INTO article (title, content, author) VALUES ('$title', '$content', '$author')"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } echo "1 record added"; mysqli_close($con); ?> But when I try to display that information here:<h1>Title: </h1> <?php echo $title; ?> <h2>Content: </h1> <?php echo $content; ?> <h3>Posted by: </h1> <?php echo $author; ?>It doesn't work and I get this:( ! ) Notice: Undefined variable: title in C:\wamp\www\test\index.php on line 33 Call Stack # Time Memory Function Location 1 0.0000 239144 {main}( ) ..\index.php:0 Content: ( ! ) Notice: Undefined variable: content in C:\wamp\www\test\index.php on line 34 Call Stack # Time Memory Function Location 1 0.0000 239144 {main}( ) ..\index.php:0 Posted by: ( ! ) Notice: Undefined variable: author in C:\wamp\www\test\index.php on line 35 Call Stack # Time Memory Function Location 1 0.0000 239144 {main}( ) ..\index.php:0 The form works because when I looked at the database, the information was there. The problem is getting that information and displaying it in the right place, how can i fix that?Just in case, this is my index: <?php include ('connect.php'); include ('header.php'); ?> <div id="container"> <div id="rightcol"> <form action="insert.php" method="post"> Title: <input type="text" name="title"> <br> Post: <input type="text" name="post"> <br> Author: <input type="text" name="author"> <br> <input type="submit"> </form> </div> <div id="content"> <h1>Title: </h1> <?php echo $title; ?> <h2>Content: </h1> <?php echo $content; ?> <h3>Posted by: </h1> <?php echo $author; ?> </div> </div> <?php include "footer.php"; ?> </div> Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/ Share on other sites More sharing options...
PrinceTaz Posted August 31, 2014 Author Share Posted August 31, 2014 New error ( ! ) Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\wamp\www\test\index.php on line 14 Call Stack # Time Memory Function Location 1 0.0000 240560 {main}( ) ..\index.php:0 2 0.0590 251064 mysqli_query ( ) ..\index.php:14 ( ! ) Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\wamp\www\test\index.php on line 16 Call Stack # Time Memory Function Location 1 0.0000 240560 {main}( ) ..\index.php:0 2 0.0620 251232 mysqli_query ( ) ..\index.php:16 ( ! ) Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\wamp\www\test\index.php on line 18 Call Stack # Time Memory Function Location 1 0.0000 240560 {main}( ) ..\index.php:0 2 0.0660 251496 mysqli_query ( ) ..\index.php:18 Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489440 Share on other sites More sharing options...
adam_bray Posted August 31, 2014 Share Posted August 31, 2014 Where is your select query and where do you define $title, etc.. for use on index.php ? Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489441 Share on other sites More sharing options...
lawless Posted August 31, 2014 Share Posted August 31, 2014 (edited) The variables you are calling to display data are merely temporary. Each time your script gets called, those variable will be brand new. So if you want to display data, you will have to request it from your database. The only time you may re-use your POST variables are within the same instance of the script you were running. So for example: - Form -- Write to database --- Show contents of variables (All procedural on one page) If the script is called again, all temporary data in your variables will be gone. That's exactly why you are writing into your database - to keep this data alive. Also make sure you work with IDs. You may set the ID column in your database to UNIQUE so no double entry is possible and A_I (auto increment), which will count up itself whenever new data arrives in the database. So you just have to know which ID you want to request out of the database, instead of align your request on titles or other stuff. // Set the request with the data you want to have // from your database. // SELECT // Select the following... // * // this means all data, you may // // just select a row too, in that // // case change it to 'title' or // // another column-name // FROM // Specify what table the data will // // be requested from // WHERE // Select only data, where the // // following statement is true $query = "SELECT * FROM test WHERE id = '$id' "; // Do the actual database request // In testphase you may also want to activate // mysql_errors, read up on that $result = mysqli_query($query); // Now the data that we gathered from the // database will be channeled towards an // array, which we can use to display. while ($db_data = mysql_fetch_assoc($result)) { echo $db_data['title']; echo "<br>"; echo $db_data['post']; echo "<br>"; echo $db_data['author']; } Edited August 31, 2014 by lawless Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489447 Share on other sites More sharing options...
Strider64 Posted August 31, 2014 Share Posted August 31, 2014 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> Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489454 Share on other sites More sharing options...
Strider64 Posted August 31, 2014 Share Posted August 31, 2014 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> Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489460 Share on other sites More sharing options...
PrinceTaz Posted August 31, 2014 Author Share Posted August 31, 2014 Wow thanks for the explanations. I attempted this as people said it would help me out. In the database you said make an auto increment. I didn't do that. My tutor wasn't on so all I did in mysql was make a table and 3 columns. The table being 'article', and the three columns, 'title', 'content', and 'author'. But its not a registration based. I'm not advanced so I want everybody to be able to post blogs and see it on the home page. How do I make it auto increment? Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489470 Share on other sites More sharing options...
lawless Posted August 31, 2014 Share Posted August 31, 2014 If you are using phpMyAdmin (as i suppose you do), simply go to the structure of your table. (Select table on the left, the structure-tab is on the top of the page). Use the 'OK' button on the bottom of the table structure to add a new column. Set the column name to 'id', the index-setting to UNIQUE and check on the A_I box. You can then save the new structure. Every time a new entry is made into the database, the field 'id' will now be updated correctly. Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489472 Share on other sites More sharing options...
PrinceTaz Posted August 31, 2014 Author Share Posted August 31, 2014 Ok I have made the database. So how should I go about doing this? I currently have a "include "connect.php"", where do I put the variables? On the index.php or on the connect page. Basically, where do I request the database information and where do I post it? Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489475 Share on other sites More sharing options...
PrinceTaz Posted August 31, 2014 Author Share Posted August 31, 2014 (edited) Oh my gosh it worked. Thanks a lot. But if its no trouble, can you explain to me why you used the "stmt" stuff? I have never seen it before. Basically the script you wrote to grab information, I need to know how and why it works, please. Test it here: http://mybbdevelopers.net/test/ Edited August 31, 2014 by PrinceTaz Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489477 Share on other sites More sharing options...
lawless Posted August 31, 2014 Share Posted August 31, 2014 (edited) [...]So how should I go about doing this? I currently have a "include "connect.php"", where do I put the variables? [...] You should divide your files by usefulness in the project. How much you divide those files is up to you (how many files you make). There are simple approaches with procedural (top-down) programming, some more advanced procedural with functions and the object oriented approach with classes. For the beginning, I would start with procedural with functions. First of, write down a scheme pen & paper style, what you want and what the different files will do. Let's start from the most important to the less important - RIGHT to LEFT. 1) The database is where all my data is stored. It's the most important thing, because where there is no data, there is no script to write for. (Alternative text files) 2) In order to access the data, I need some kind of database connection. I name it database.php, which contains the connection 3) I have the connection, but I still need to read / write data. Therefore i have functions that allow me to do so. 4) The data i have to write in order to put it into the database AND the retrieved data which will be shown on the index For easier understanding: // index.php <?PHP require("database.php"); require("inputOutput.php"); writestuff("MyStuff"); readstuff("DBStuff"); ?> // inputOutput.php <?PHP function writeStuff() {} function readStuff() {} ?> // database.php <?PHP function connectDB() {} ?> You may use this procedural / function based style to widen your skillset, until you are ready for object oriented programming. This style i showed you still works fine and is used throughout the internet. Of course, bigger software will be very hard to accomplish without objects, but you are learning at the moment, start at the beginning. With this style you can simply add new functions (and new files) as you wish without too much hard work and change a bit here and there without searching through thousands of lines of source code. Remember: Pen & paper and most of the work is done. Edited August 31, 2014 by lawless Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489480 Share on other sites More sharing options...
PrinceTaz Posted August 31, 2014 Author Share Posted August 31, 2014 So let me get this straight, when I am writing the code to grab the data from the database, within the same script, I can display that data? Well the way you say makes it really simple, but going to my code, its like a hot mess. Somehow the script executes successfully, but modifying is hard because there is a bunch of code everywhere. Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489481 Share on other sites More sharing options...
lawless Posted August 31, 2014 Share Posted August 31, 2014 If you have a code without functions (which is called procedural programming), which you have right now, the program goes like that: connect db write contents to db get contents from db In that case you can connect to the database within the whole script, as long as the connection to the database comes first. If you are going to structure it (without classes) you will have to pass in the connection to the specific functions, which need the connection in order to work. // This gets executed first in your script $connection = mysqli_connect(data); // your function declaration function read_stuff($connection, $data) { // query } // use the function (i.e. in index.php) read_stuff($connection, "data"); Without passing on the connection to the functions, the function will fail to execute with "no database access" error. Yes, there are better ways to do it, where we would ask about classes again Pass in the connection and it will work. The messy code you have right now is simply because it is not well organized. With time and practice you will understand what component does what and you will be better and structuring your code. The good thing is: you already started outsourcing your code with the use of your 'connect.php', 'header.php' and so on. That's the first step towards an organized structure. Keep it up! Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489483 Share on other sites More sharing options...
PrinceTaz Posted August 31, 2014 Author Share Posted August 31, 2014 Thanks a lot!! Ok so instead of this: // This gets executed first in your script $connection = mysqli_connect(data); // your function declaration function read_stuff($connection, $data) { // query } // use the function (i.e. in index.php) read_stuff($connection, "data"); can I do this instead: // This gets executed first in your script require "connect.php"; // your function declaration function read_stuff($connection, $data) { // query } // use the function (i.e. in index.php) read_stuff($connection, "data"); And the above script, I'm guessing that its in the index? So let me ask this, lets say I use a script to grab information in a different file like this: //information grabber, grabber.php <?php //grabs informaition $title = *SELECT FROM 'article', 'title'; $content = *SELECT FROM 'article', 'content'; $author = *SELECT FROM 'article', 'author'; ?> //displays data <?php include "grabber.php' echo "<p>$title</p>"; ?> Basically Im asking if I can share variables within different files. Also the script to SELECT FROM is probably wrong because I guessed it from looking at your code. Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489487 Share on other sites More sharing options...
lawless Posted August 31, 2014 Share Posted August 31, 2014 Basically yes. The system will run your code like that: // index-file include("grabber.php"); // runs the file "grabber" here, variables are set now echo $title; // works, because the title variable has been set already And yes the syntax is quite wrong, I just made it a scheme for better understanding. The correct way would be to do a single query instead of three different ones, and to manipulate the result given so you may use it in array-form. $id = "1"; $query = "SELECT * FROM table WHERE id = '$id'; $result = mysqli_query($query); while($data = mysql_fetch_assoc($result)) { echo $data['title']; echo $data['content']; echo $data['author']; } You may use this script (or the one that works for you) everywhere in your file you want, just make sure the code for the DB connection comes first. Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489489 Share on other sites More sharing options...
PrinceTaz Posted August 31, 2014 Author Share Posted August 31, 2014 (edited) So i am going recode this from scratch and test out just how much I've learned from you. EDIT: How can I add a date to when the author posts. Edited August 31, 2014 by PrinceTaz Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489491 Share on other sites More sharing options...
lawless Posted August 31, 2014 Share Posted August 31, 2014 (edited) You can store the date as timestamp in your database, then when you read it out, use the date() function to convert it to the format you need to display. I'd recommend another column with TIMESTAMP (timestamp type), and the setting STANDARD to CURRENT_TIMESTAMP. Like the ID, this field will then be automatically filled, so you don't have to worry about manually saving the time into your database. When you get the data from your database, simply convert it: $date = date("d.m.Y, H:i", $timestamp); For the complete set of options how you can convert timestamps into readable dates, there is a list on the php manual page. http://php.net/manual/en/function.date.php You can also group the day, month and year together and use another variable for hours and minutes. That's up to your preference. Edited August 31, 2014 by lawless Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489492 Share on other sites More sharing options...
PrinceTaz Posted August 31, 2014 Author Share Posted August 31, 2014 I see, I can make that work. So how can I style the $title in css? It is currently echo "<h1>" . $title . "</h1>\n"; echo "<p>" . $content . "</p>\n"; echo "<p>By:" . $author . "</p>\n"; }, how can I style it. Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489493 Share on other sites More sharing options...
PrinceTaz Posted August 31, 2014 Author Share Posted August 31, 2014 (edited) I see, I can make that work. So how can I style the $title in css? It is currently echo "<h1>" . $title . "</h1>\n"; echo "<p>" . $content . "</p>\n"; echo "<p>By:" . $author . "</p>\n"; } , how can I style it. EDIT: I am having trouble displaying the date. I have this: $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); $date = filter_input(INPUT_POST, 'date', FILTER_SANITIZE_SPECIAL_CHARS); //index.php while (mysqli_stmt_fetch($stmt)) { echo "<h1>" . $title . "</h1>\n"; echo "<p>" . $content . "</p>\n"; echo "<p>By:" . $author . "</p>\n"; echo "<p>By:" . $date . "</p>\n"; } //but I get this error Notice: Undefined variable: timestamp in C:\wamp\www\test\index.php on line 35 Edited August 31, 2014 by PrinceTaz Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489496 Share on other sites More sharing options...
adam_bray Posted August 31, 2014 Share Posted August 31, 2014 (edited) $id = "1"; $query = "SELECT * FROM table WHERE id = '$id'; $result = mysqli_query($query); while($data = mysql_fetch_assoc($result)) { echo $data['title']; echo $data['content']; echo $data['author']; } You need to be careful following this code as it's not very secure. The code Strider posted is better as it uses prepared statements. Assuming you go down the same route most beginners go with, you'll next want to show individual posts on each page, meaning you'll end up with this - $id = $_GET['id']; // Here's the problem $query = "SELECT * FROM table WHERE id = '$id'; $result = mysqli_query($query); while($data = mysql_fetch_assoc($result)) { echo $data['title']; echo $data['content']; echo $data['author']; } This will leave your code open to SQL injections which isn't a good idea. The idea being that if the user passed the following string to your code where you're searching for the ID, you could lose a lot of data. ' or 1=1 UNION DROP TABLE table; Strider's code uses prepared statements which is a much safer way of passing variables to your query.This: $sql="INSERT INTO article (title, content, author) VALUES ('$title', '$content', '$author')"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } Becomes this: /* 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); Have a look at the following, try typing in the functions you don't understand into PHP.net and you'll find good examples of what's happening. <?php // Connect to MySQL DB $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); // Check connection if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } // Look for the post ID $id = $_GET['id']; // Create a prepared statement if($stmt = $mysqli->prepare("SELECT title, content, author, date FROM table WHERE id=?")) { // Bind parameters for markers $stmt->bind_param("s", $id); // Run query $stmt->execute(); // Loop through the results while ($obj = $stmt->fetch_object()) { $results = '<h1>'.$obj->title.'</h1> <p>'.$obj->content.'</p> <p><em>Posted by '.$obj->author.'</em> on '.date("d F Y",$obj->date).'</p>'; } // Close statement $stmt->close(); } // Close connection $mysqli->close(); ?> <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Untitled Document</title> </head> <body> <?php if( count($results) > 0 ) { echo $results; } else { echo '<p>There are no posts to display</p>'; } ?> </body> </html> Edited August 31, 2014 by adam_bray Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489502 Share on other sites More sharing options...
PrinceTaz Posted September 1, 2014 Author Share Posted September 1, 2014 Thanks everybody. I will attempt to build this from scratch again and will post back if I have issues, feel free to post tips that will help me out. I don't want to start off with bad habits. Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489512 Share on other sites More sharing options...
PrinceTaz Posted September 1, 2014 Author Share Posted September 1, 2014 Do you have any examples of a very simple blog script which I can look at? I don't want anything too advanced. Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489514 Share on other sites More sharing options...
mac_gyver Posted September 1, 2014 Share Posted September 1, 2014 it would be up to you to find code examples at your level of understanding. all a blog is, are - forms, form processing code (that stores submitted data in appropriate database tables), navigation/search/sort code to list or limit entries and pick display order, and code to retrieve/display the correct contents from those database tables in the correct order. you would also need a log-in system with access permissions, to control who can access the forms and the form processing code, a lot of validation and security to prevent nefarious visitors from doing things they shouldn't or to tell legitimate visitors what was wrong with what they did so that they can correct it, and error checking logic on everything so that your code will let the visitor know when the site isn't going to produce any result and to log (or display during development) all the information about each error so that you can find and fix problems. Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489545 Share on other sites More sharing options...
PrinceTaz Posted September 2, 2014 Author Share Posted September 2, 2014 I have a full understanding of what a blog does, the problem is knowing how to do it. For example, I have all the ingredients but I don't have the recipe to put it all together. I know that programming doesnt exactly have a recipe and you can code all types of ways but the basic recipe. Like how to retrieve information from a database and that sort of stuff. Quote Link to comment https://forums.phpfreaks.com/topic/290764-php-blog-help/#findComment-1489633 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.