I'm very new to PHP- and am trying to teach myself a bit of web programming with hands-on learning. I've stumbled upon this: https://www.youtube.com/watch?v=CS45YAqCgX8 video series on how to build a comment section, but am stuck.
My First PHP file looks as such:
<?php
require('connect.php');
If(isset($_POST['submit']))
{
$name=$_POST['name'];
$comment=$_POST['comment'];
If(name&&comment)
{
$insert=mysqli_query("INSERT INTO comment (name,comment) VALUES ('$name','$comment')");
}
}
/*else
echo "Please fill out your name and leave a comment.*/
?>
<html>
<br/>
<br/>
<body>
<form action = "CommentForm.php" method = "post">
<table>
<br/>
<tr><td>Name: </td><td><input type = "text" name = "name" size = "30"/></td></tr>
<tr><td colspan="2">Comment:</td></tr>
<tr><td colspan="2"><textarea name = "comment"></textarea></td></tr>
<tr><td colspan="2"><input type = "submit" name = "submit" value = "Comment"/></td></tr>
</table>
</form>
</body>
</html>
The connection file is:
<?php
mysqli_connect("My Host", "My Username","My Password");
mysqli_select_db("My Database");
?>
-and the HTML I want to attach it to is as such
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Pokemon</title>
<link rel = "stylesheet" type = "text/css"
href = "stylishandviewtiful.css">
</head>
<body>
<br/>
<br/>
<br/>
<br/>
<h3>Competitive Meta and Community</h3>
<h3>In-Game Story Ideas and Opinions</h3>
</body>
<?php include 'CommentForm.php'; ?>
</html>
I'll suppose I can't just use an include function? Would I see a better return to separate the HTML in the first PHP application into its own file?
I may generally need a tutorial for this specific instance that starts slow enough for any layman to follow.
You forgot to put the connection inside the mysqli_query($con,"insert ...")
otherwise your insert will be linked to $link. second try making connection like this $con=mysqli_connect("localhost","my_user","my_password","my_db"); pass your $con to your mysqli_query
see http://www.w3schools.com/php/func_mysqli_query.asp
and if your form still does not appear you need to look at your include file. If there is something wrong it will abort
Related
first time posting on here so I apologise for any bad habits.
I recently started an online youtube tutorial on php and how to create a blog.
I ended up getting occupied with other things and have come back to try an finish what I started and 2 things have happened. 1: my tutorials have been deleted off youtube(must of been a copyrright issue) and second I've completely forgot the method used. I assume if I was a seasoned coder this would be easy to decipher but I'm having no luck after trying for days now.
This code is for the submission form for my blog. The blog is working in the sense of if I manually input my HTML into the SQL database but all I seem to get if I use this form is a refresh of the submission page with all the information gone. No information is added to the database.
Anybody have an idea?I had a good search around the site but I ran into a dead end due to my lack of knowledge on what I was actually searching for (lots of solutions regarding javascript)
All help will be appreciated.
Sincerely
SGT Noob
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if (isset($_SESSION['username'])) {
$username = ($_SESSION['username']);
}
else {
header('Location: ../index.php');
die();
}
if (isset($_POST['submit']))
if ($_POST['submit']) {
$title = $_POST['Post_Title'];
$content = $_POST['Post_Content'];
$date = $_POST['Post_Date'];
include_once("../admin/connection.php");
$sql = "INSERT INTO `posts` (Post_Title, Post_Content, Post_Date)
VALUES ('$title','$content','$date')";
mysqli_query($dbcon,$sql);
echo "Post has been added to the database";
}
else {
header('Location: index.php');
die();
}
?>
<html>
<div>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//cdn.ckeditor.com/4.5.9/standard/ckeditor.js"></script>
<title> Insert Post </title>
</head>
<div>
<body>
<div id= 'cmssubmissionform'>
<form action="" method="post">
<p>
<h1> Post Title</h1>
<input type="text" name= "Post_Title"/>
</p>
<h1> Post Date</h1>
<input type="text" name= "Post_Date"/>
</p>
<p>
<h1>Post Content </h1>
<textarea name="Post_Content"></textarea>
<script>
CKEDITOR.replace( 'Post_Content' );
</script>
</p>
<p>
<input type = "submit" value="submit" />
</p>
</form>
</div>
</div>
</div>
</body>
try this
in your from change to
<input type = "submit" value="submit" name="submit"/>
You forgot to put the name attribute
The php
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
include_once("../admin/connection.php");
if (isset($_SESSION['username'])) {
$username = ($_SESSION['username']);
}
else {
header('Location: ../index.php');
die();
}
if (isset($_POST['submit'])){
$title = $_POST['Post_Title'];
$content = $_POST['Post_Content'];
$date = $_POST['Post_Date'];
$sql = "INSERT INTO `posts` (`Post_Title`, `Post_Content`, `Post_Date`)
VALUES ('$title','$content','$date')";
if(mysqli_query($dbcon,$sql)){
echo "Post has been added to the database";
}else{
header('Location: index.php');
die();
}
}
?>
Note I also changed your SQL statement to
INSERT INTO `posts` (`Post_Title`, `Post_Content`, `Post_Date`)
VALUES ('$title','$content','$date
Notice the back ticks for the table fields
Replace
if (isset($_POST['submit']))
if ($_POST['submit']) {
with
if (isset($_POST['submit'])) {
and then replace
<input type = "submit" value="submit" />
with
<input type ="submit" name="submit" value="submit" />
However, at this stage I would highly suggest starting over with a different tutorial.
Also, as has been mentioned in the comments, whenever you take arguments from a user and put them into a database query, you must absolutely make sure that the strings do not manipulate the query (imagine someone wrote 0'; DROP TABLE `blog`; -- in the date field (and "blog" were the name of your blog post table). That would be quite catastrophic, wouldn't it?
So when you handle input data, either use the prepare and bind methods of the mysqli package, or pass the strings through the mysqli_real_escape_string() function first.
I have an if else statement. The code logic is that the first if statement would get all the necessary informations needed and the second if statement would print all the informations that are generated at the first if statement. The problem is that when it triggers the second if statement, it disregards all the data that are stored in the first if statement.
Can anybody help me how to solve this problem? Thank You
This is just a sample code but the process and logic of code is somehow the same.
<head>
<title>Sample PHP Web</title>
</head>
<body>
<form method = "post">
<input type = "submit" value = "submit" name = "submit">
<?php
if(isset($_POST['submit']))
{
$nn[0] = "man";
$nn[1]= "men";
echo'<input type = "submit" value = "print" name = "print">';
}
?>
</form>
<?php
if(isset($_POST['print']))
{
echo $nn[0];
echo $nn[1];
}
?>
</body>
After the initial form submission is handled the values you set into PHP variables are lost. They do not persist across page requests. If you want them to persist you need to use sessions.
<?php
session_start();
?>
<head>
<title>Sample PHP Web</title>
</head>
<body>
<form method = "post">
<input type = "submit" value = "submit" name = "submit">
<?php
if(isset($_POST['submit']))
{
$_SESSION['nn'][0] = "man";
$_SESSION['nn'][1]= "men";
echo'<input type = "submit" value = "print" name = "print">';
}
?>
</form>
<?php
if(isset($_POST['print']))
{
echo $_SESSION['nn'][0];
echo " "; // seperate words with a space
echo $_SESSION['nn'][1];
}
?>
</body>
I am assigned with creating an HTML page that accepts user input and then verifying the user input on a php script (upon clicking submit on the HTML page). Thus far, I am only trying to verify the first name variable of the HTML page onto the PHP page.
My issue is that the PHP page is not displaying the HTML variables, 'fname' I've looked around for a good solution but I am unable to find anything yet
I am using Aptana Studio 3 and I am running XAMPP. I have posted my HTML and PHP code below for you to view. Any help would be greatly appreciated :)
<!DOCTYPE html>
<html>
<head>
<title>
Assignment Four, HMTL/PHP Form
</title>
<meta charset = "UTF-8">
</head>
<body>
<!--Begin the body code-->
<h1>Assignment Four: HTML/PHP Form</h1>
<p>Watch the following video, write a brief review and then click submit!</p>
<!--Post the Scholartica Video-->
<iframe width="560" height="315" src="//www.youtube.com/embed/d_2_8n86jA8" frameborder="0"
allowfullscreen></iframe>
<h3>Complete the following information:</h3>
<form method = "post" action = "form.php">
<p><label>First Name</label>
<input type = "text" name = "fname"></p>
<p><label>Last Name</label>
<input type = "text" name = "lname"></p>
<p><label>Email:</label>
<input type = "text" name = "email"></p>
<p><label>Phone:</label>
<input type = "text" name = "phone"
placeholder = "(123) 456-7890"></p>
<h3>Write a brief review about the video here</h3>
<p><textarea rows = "4" cols="50" name = "review">What did you think?
</textarea></p>
<h3>Rate the quality of the video</h3>
<select name = "Rating">
<option>Poor</option>
<option>Average</option>
<option>Good</option>
<option>Excellent</option>
</select>
<p><input type = "submit" name ="submit" value ="Register"></p>
</form>
</body>
</html>
My PHP form looks like this
<!DOCTYPE html>
<html>
<body>
Hi <?php echo $_POST["fname"];?>
Thank you for finishing the survey
Your responses have been recorded.
</body>
</html>
I ran the code and it seems to work.
Entering name = "Bob" and clicking submit returns page with
Hi Bob Thank you for finishing the survey Your responses have been recorded.
Make sure that:
Your second page that displays the result is called "form.php"
And also have both files in the same directory
The problem goes as follows:
File 1 which has the name of: Lesson 17_Forms - Simple Form.php
and
File 2 which has the name of: Lesson 17_Forms - Process.php
The contents of file 1 are as follows:
<html>
<title>Lesson 17_Forms - Simple Form</title>
<head>
<center><h1>Lesson 17_Forms - Simple Form</h1></center>
</head>
<body>
<form action= "Lesson 17_Forms - Process.php" method="post">
Username: <input type="text" name="username" value="" />
<br />
Password: <input type="password" name="password" value="" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
The contents of file 2:
<html>
<title>Lesson 17_Forms - Process</title>
<head>
<center><h1>Lesson 17_Forms - Process</h1></center>
</head>
<body>
<?php
// Ultra-simple form processing
// Just retrieve the value and return it to the browser
$username = $_POST['username'];
$password = $_POST['password'];
echo "{$username}: {$password}";
?>
</body>
</html>
Both files are in the same directory, when i am trying to process the form by clicking the submit button, i am receiving the following error:
Object not found!
The requested URL was not found on this server. The link on the
referring page seems to be wrong or outdated. Please inform the author
of that page about the error.
If you think this is a server error, please contact the webmaster.
Error 404
localhost Sat 12 May 2012 02:40:39 PM EEST Apache/2.2.21 (Unix) DAV/2
mod_ssl/2.2.21 OpenSSL/1.0.0c PHP/5.3.8 mod_apreq2-20090110/2.7.1
mod_perl/2.0.5 Perl/v5.10.1
Any suggestions are greatly appreciated.
No spaces are allowed in url -> change the names to simple_form.php and process.php.
or if you want to keep spaces in name then replace all spaces by '%20' whenever you use it as a url.
Or the best option is to use urlencode -> it automatically replaces all non-allowed characters by their web acceptable placeholders.
<form action=<?php echo '"'.urlencode("Lesson 17_Forms - Process.php").'"'; ?> method="post">
Make sure you have both files on the same directory. Also, eliminate any spaces in file names, while valid, they will cause massive headaches. So name your files something more like: lesson17_forms_process.php.
Also, after some modifications, this is the code I get:
<?php
//Initialize variables
$fields_set = false;
$username = "";
$password = "";
//Validity check
if (isset($_POST['username']) && isset($_POST['password'])) {
$fields_set = true;
$username = $_POST["username"];
$password = $_POST["password"];
}
?>
<html>
<head>
<title>Lesson 17_Forms - Process</title>
</head>
<body>
<h1 style="text-align: center;">Lesson 17_Forms - Process</h1>
<?php
//Display results if validity passed, or error in case it didn't.
if ($fields_set) {
echo "{$username}: {$password}";
}
else {
echo "Error! username or password not set!";
}
?>
</body>
</html>
Some Points
I process all form data before I start sending HTML. Separate logic and display as much as possible.
I removed the h1 element from the head and placed it in the body (where it belongs). All page content must go in body.
I removed the presentational element <center> and replaced it with CSS.
I validate the input prior to processing.
I display an error in case the form is not valid.
I'll use your existing code, and modify it. With new file names.
I did also correct your HTML.
Create a file named: form.php, insert the code below:
<html>
<head>
<title>Submit form</title>
</head>
<body>
<center><h1>Submit form</h1></center>
<form action="process.php" method="post">
Username:<input type="text" name="username" value="" />
<br />
Password: <input type="password" name="password" value="" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Create a file named: process.php, insert the code below:
<html>
<head>
<title>Your form</title>
</head>
<body>
<center><h1>Lesson 17_Forms - Process</h1></center>
<?php
// Ultra-simple form processing
// Just retrieve the value and return it to the browser
$username = $_POST['username'];
$password = $_POST['password'];
echo "{$username}: {$password}";
?>
</body>
</html>
That should work perfectly, remember to have both files in the same folder.
I'm trying to write a program where the basic idea is I ask the user for input in a textarea, and then the text gets stored into a word file. Here is the code I'm trying to use:
<html>
<head>
<title>Simple Guestbook</title>
</head>
<body>
<h1>Simple Guestbook Comment Creator</h1>
<br>
<form method = "post"
action = "mysite.php">
<textarea name = "text"
rows = "10"
cols = "20">Write Here</textarea>
<input type = "submit"
value = "Submit Comment">
</form>
<?
if($_POST['text'] !== NULL){
$comment = $_POST['text'];
$file = fopen("texttest.txt", "a");
fputs($file, "<br>\n$comment");
fclose($file);
}
?>
</body>
</html>
I can't seem to get this to work properly. I was also thinking about somehow making the form action store the text and then reload the site, but I haven't gotten that to work (the original file is mysite.php, so the action is to just reload the page).
If anyone has any better ideas of an algorithm to use/different syntax to use, please let me know, as I just started learning basic PHP syntax.
Thanks
Check the following:
Does php have the permission to write files in that directory?
Is that php file called "myfile.php"?
Anyway, when something does not work and you want to know what's causing the arror, place error_reporting(-1); at the beginning of your php - it will output any error or warning, including the ones trown by fopen().
Also, you might want to check whether the variable has been correctly submitted: echo $comment right after you assign it.
Something like this might work.
You might want to do more with the values they are entering and all, but this will basically do what you are asking.
You will also want to make sure that you have the correct path of the file you are trying to write to and that that file has the correct permissions to allow it to be written to:
<html>
<head>
<title>Simple Guestbook</title>
</head>
<body>
<h1>Simple Guestbook Comment Creator</h1><br>
<?php
if (isset($_POST['submit'])) {
if (strlen(trim($_POST['comment']))) {
$file = fopen("texttest.txt", "a");
fputs($file, "$_POST['comment'])\n");
fclose($file);
}
} else {
?>
<form method = "post" action = "<?php echo($_SERVER['PHP_SELF']); ?>">
<label>Leave your comment
<textarea name="comment" rows="10" cols="20"></textarea>
</label>
<input type="submit" name="submit" value="Submit Comment" />
</form>
<?php
}
?>
</body>
Also, since you are returning to the same page you may want to put some kind of message letting the person know that they succeeded in entering something into your address book.