What's wrong with my data submisson system[one button, 2 fields] - php

I am setting up my custom blog's basic submission system.
This is the PHP section of it that I try to submit the inserted data into the database
<?php
session_start();
if(!isset($_SESSION['user_id'])){
header('Location: login.php');
exit();
}
include('../includes/db_connect.php');
if(isset($_POST['submit'])){
$newTitle = $_POST['newTitle'];
$newPost = $_POST['newPost'];
$my_date = date("Y-m-d H:i:s");
if(!empty($newPost))
if(!empty($newTitle)){
$sql="INSERT INTO posts (title, body)
VALUES($newTitle, $newPost)";
$query = $db->query($sql);
if($query){
echo "Post entered to database";
}else{
echo "Error Submitting the data";
}
}
}
?>
Then There is the submission form, I am pretty sure this is the faulty end for some reason, but I cannot find out why.
<form action="<?php echo $_SERVER['PHP_SELF']?>"name="newTitle" method="post">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<p>Title:</p><br><input type="text" name="newTitle">
<textarea name="newPost" cols="110" rows="25"/></textarea><br>
<label for="newPost">Add New Post</label><input type="submit" name="submit" value="submit"/>
</form>
This is the database's table:
post_id (A_I)
user_id
title
body
category_id
posted(datetime)
Bear in mind that I am a rookie in this area, so don't be too harsh :)

Use single quote for strings:
$sql="INSERT INTO posts (title, body) VALUES ('$newTitle', '$newPost')";
//^ ^ ^ ^
Notice:
Try to use PDO and param binding in your projects to prevent sql injection.
Nice Tutorial about PDO

Use single form tag only:
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<p>Title:</p><br><input type="text" name="newTitle">
<textarea name="newPost" cols="110" rows="25"/></textarea><br>
<label for="newPost">Add New Post</label>
<input type="submit" name="submit" value="submit"/>
</form>
And in your php code, you can check youe data by using isset() function
if(isset($_POST['submit'])){
if(isset($_POST['newTitle']) && ($_POST['newPost']))
$newTitle = $_POST['newTitle'];
$newPost = $_POST['newPost'];
$my_date = date("Y-m-d H:i:s");
$sql="INSERT INTO posts (title, body)
VALUES('$newTitle', '$newPost')"; //use variable in single quote.
$query = $db->query($sql);
if($query){
echo "Post entered to database";
}else{
echo "Error Submitting the data";
}
}

Related

If clause does not give update only works insertion. Why update is not working?

I want to update and insert conditionally but query always goes "Insert" data. No "update" anyway. My code is below:
<form method="post" action="">
<label>ID: </label> <input type="text" name="id">
<label>Subject: </label> <input type="text" name="subject">
<input type="submit" name="submit">
</form>
<?php
$conn = new mysqli("localhost", "root", "", "zidm");
$id=$_POST['id'];
$subject=$_POST['subject'];
if (isset($_POST['submit'])){
$sql = "UPDATE exam SET subject = '$subject' WHERE id = '$id'";
mysqli_query($conn,$sql);
echo "Data Updated";
}
else {
$sql="INSERT INTO exam (subject) VALUES ( '$subject)";
mysqli_query($conn,$sql);
echo "Data Inserted";
}
?>
The issue is that you are checking for form submission but also have an else statement which will always fire on page load. You need to wrap your entire logic in the form submission check and then check for the id parameter.
// Form was submitted
if (isset($_POST['submit'])) {
if (!empty($_POST['id'])) {
// Update
} else {
// Insert
}
}

Php form submit not working. What's wrong with it?

I am simply trying to add form data(email, date) to mysql database. Below is my code. It looks fine but for some reason, every time I submit the form, it doesn't do anything. I don't get any error messages. The only change I see after submit is this in the browser url search field at the top. "/localhost/?email=&submit=Notify+Me"
The database is connected and the table/column names match correctly. The form itself simply does not process. Can you take a look and see if there's anything wrong with it?
<?php
if(isset($_POST['submit'])) {
$email = trim($_POST['email']);
if(empty($_POST['email'])) {
$error = 'Please enter your email address.';
} else {
$newEmail = $email;
$date = date('Y-m-d H:i:s');
$insert = $db->prepare("INSERT INTO email_list(email, date) VALUES(:email, :date)");
$insert->bindParam(':email', $newEmail);
$insert->bindParam(':date', $date);
$insert->execute();
$result = $insert->execute();
if($result == false) {
$error = 'There seems to be a problem. Please try again.';
} else {
$success = 'Success.';
}
}
}
?>
<div id="error"><?php echo $error; ?></div>
<div id="success"><?php echo $success; ?></div>
<form action="" method="post">
<input type="text" name="email" placeholder="Enter email address"/>
<input type="submit" name="submit" value="Notify Me"/>
</form>
You need to have method="post" but not type.
This is what you have:
<form action="" type="post" enctype="multipart/form-data">
This is what you need:
<form action="" method="post" enctype="multipart/form-data">
The form is submitting using GET instead of POST because you have type="post" rather than method="post" on the form. Type isn't a valid attribute so id defaults to GET and then is ignored by your script since you are checking for $_POST.

Creating new rows in mysql when refreshing page, why?

I've done a php script that will create a title and a text and load it to my database(mysql). When i press submit the script runs and create 1 row right and then like 3-5 empty rows.
The same thing happens when i refresh the page(empty form), 2 new empty rows shows in my database?
How do i solve it?
<?php
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
<form method="post" onSubmit=window.location="index.php">
Rubrik: <br/><input type="text" name="rubrik"><br/>
Nyhetstext:<br/> <textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10">
</textarea><br/>
<input type="submit" value="Publicera nyhet">
</form>
Your INSERT query is executing every time when page loads, set a POST variable to check whether the form has been submitted or not and why you are using event attribute window.location for submitting form, you can simply use action attribute and set that value either blank or the file name where you want to send your data.
<form action="" method="post">
OR
<form action="index.php" method="post">
Your date variable is also wrong. To generate date into YYYY-MM-DD format write like below
$date = date('Y-m-d');
Your script may like this
if(isset($_POST['submit'])) {
your post variables and insert query goes here
}
You can also insert a hidden input field into your form tag like so
<form action="" method="post">
<input type="hidden" name="save" value="details">
other HTML code goes here
</form>
in that case you test the post variable like this
if(isset($_POST['save']) && $_POST['save'] === "details") {
your post variables and insert query goes here
}
First learn the basic concept about PHP from http://www.php.net/ and search for appropriate question over here before asking any question.
Wrap your php code around condition to check if the form is submitted or not. Like:
<?php
if(isset($_POST['submit')){
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>
Always catch form submission. You can use isset() with this:
<?php
$con = mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Y-m-d"); // put the correct format on the date
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '$date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
header('Location: index.php'); // always redirect
}
?>
<form method="post" action="">
Rubrik: <br/><input type="text" name="rubrik"><br/>
Nyhetstext:<br/><textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"></textarea><br/>
<input type="submit" name="submit" value="Publicera nyhet" />
<!-- ^^ add a name -->
</form>
You should check if $_SERVER['REQUEST_METHOD'] is POST and only then run the INSERT statement.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>

if isset($_POST issue

I have one instance of where a user on my PHP site can login, and I'm trying to make a second where administrators can post announcements.
My login works beautifully, but for some reason I can't get my announcement submission to work. Despite my input fields being named appropriately, the field is being seen as "not set" when I type in a title and announcement on my form. Here is my code:
FORM:
<form action="announce.php">
<input type="text" name="title" />
<textarea name="announce" cols="20" rows="2" ></textarea>
<input type="submit" name="submit" value="Announce" />
</form>
Here is my PHP:
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");
if (isset($_POST['title']))
{
$title = $_POST['title'];
$announce = $_POST['announce'];
$query = "INSERT INTO announcements (labname, name, author, announce)
VALUES ($lab, $title, $username, $announce)";
$insert = mysqli_query($con, $query);
mysqli_close($con);
echo "added successfully";}
else
{
echo "something went wrong";
}
My other form seems to work but this one doesn't... is my syntax wrong somewhere?
Your form is submitting as a GET request, not POST.
Change this line:
<form action="announce.php">
to this:
<form action="announce.php" method="post">
Edit: I should really refresh the page before posting. All credit to noobie-php for getting this right in their comment 30 mins before I posted this!
Php :
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");
if (isset($_POST['submit']))
{
$title = $_POST['title'];
$announce = $_POST['announce'];
$query = "INSERT INTO announcements (labname, name, author, announce)
VALUES ($lab, $title, $username, $announce)";
$insert = mysqli_query($con, $query);
mysqli_close($con);
echo "added successfully";}
else
{
echo "something went wrong";
}
i think if (isset($_POST['submit'])) this is the problem.

Getting items from a database not working as expected

I'm learning PHP and I've hit a wall.
When the user submits to the form, it adds to the database.
I am also trying to display all items in the database on the same page as the form.
However,this only works if the form has just been submitted. If the form has not been submitted (but there is still content in the database), nothing is shown.
How can I always show what is in the current database?
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
} else {
die();
}
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
mysqli_query(
$todo_db,
"INSERT INTO todo_items (item_content) VALUES ('$latest_content')"
);
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>
The die() is your problem:
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
} else {
die();
}
If $_POST is not set, you will never reach the part where you start printing your items. And since the form is not submitted, $_POST is empty.
EDIT
You could do it like this:
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
}
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>
You need to move your insert query inside your if condition and you will need not to die if the form is not submitted but print the form and your query results
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
} else {
?>
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result);
var_dump($all_todos);
}
As side note i'd say you are at high risk of mysql injection. You should use prepaed statments and not inserting $_POST data inside your database directly

Categories