Empty posts when refresh page [ Double Submission ] ( PHP/MYSQL ) - php

Im new in MYSQL & PHP so don't mind me about my stolen code XD
I want to publish simple posts by using PHP/HTML & saving on Database.
Ayway here is the file that i've created to post stuff on home.php
admin.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dblogin";
$newsTitle = null;
$newsShortDescription = null;
$newsFullContent = null;
$newsColor = null;
$newsIcon = null;
$users_website = null;
$users_comment = null;
if(isset($_POST['btn-post']))
{
$newsTitle = $_POST['news_title'];
$newsShortDescription = $_POST['news_short_description'];
$newsFullContent = $_POST['news_full_content'];
$newsColor = $_POST['news_color'];
$newsIcon = $_POST['news_author'];
}
$newsTitle = mysql_real_escape_string($newsTitle);
$newsShortDescription = mysql_real_escape_string($newsShortDescription);
$users_website = mysql_real_escape_string($users_website);
$users_comment = mysql_real_escape_string($users_comment);
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info_news (news_title, news_short_description, news_full_content, news_author, news_color)
VALUES ('$newsTitle', '$newsShortDescription', '$newsFullContent', '$newsIcon', '$newsColor')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
$conn = null;
?>
<form method="post">
<div class="form-group">
<input type="text" class="form-control" name="news_title" placeholder="Title" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="news_short_description" placeholder="Description" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="news_full_content" placeholder="Full Content" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="news_color" placeholder="Color" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="news_author" placeholder="Icon" required />
</div>
<div class="clearfix"></div>
<div class="form-group">
<button type="submit" name="btn-post" class="btn btn-block btn-primary">
Post
</button>
</div>
<br />
</form>
Thank you :)
I want to make kind of a simple blog, only Title, Short Description and so... It works while i make new posts, but when i refresh it shows an empty post. Here is a pic: Here is the Image also i've tried to edit the admin.php ( By looking other questions on SOF )
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dblogin";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO info_news (news_title, news_short_description, news_full_content, news_author, news_color) VALUES (:news_title, :news_short_description, :news_full_content, :news_author, :news_color)");
$stmt->bindParam(':news_title', $news_title);
$stmt->bindParam(':news_short_description', $news_short_description);
$stmt->bindParam(':news_full_content', $news_full_content);
$stmt->bindParam(':news_author', $news_author);
$stmt->bindParam(':news_color', $news_color);
$stmt->execute($_POST);
?>
<form method="post">
<div class="form-group">
<input type="text" class="form-control" name="news_title" placeholder="Title" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="news_short_description" placeholder="Description" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="news_full_content" placeholder="Full Content" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="news_color" placeholder="Color" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="news_author" placeholder="Icon" required />
</div>
<div class="clearfix"></div>
<div class="form-group">
<button type="submit" name="btn-post" class="btn btn-block btn-primary">
Post
</button>
</div>
<br />
</form>
By looking some other questions on stackoverflow but still no luck ;/

it's not an empty post what makes the empty row inserted, try this:
if(isset($_POST['btn-post']))
{
$newsTitle = $_POST['news_title'];
$newsShortDescription = $_POST['news_short_description'];
$newsFullContent = $_POST['news_full_content'];
$newsColor = $_POST['news_color'];
$newsIcon = $_POST['news_author'];
$newsTitle = mysql_real_escape_string($newsTitle);
$newsShortDescription = mysql_real_escape_string($newsShortDescription);
$users_website = mysql_real_escape_string($users_website);
$users_comment = mysql_real_escape_string($users_comment);
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info_news (news_title, news_short_description, news_full_content, news_author, news_color)
VALUES ('$newsTitle', '$newsShortDescription', '$newsFullContent', '$newsIcon', '$newsColor')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
$conn = null;
}
I moved the "}" after $conn = null; ;)
And BTW, you should redirect after each POST. So POST is not sent once more on page refresh.
And you can't redirect while the content was "echoed" already. It will work for a while thanks to buffer, but when the header will grow in its size (like 4kB, depends on server settings) it will fail one day. (saw it few times in github you posted)

Related

Updating records in database using a pre populated form

Looks like I have 1 last issue that I can't solve due to the fact of being too unexperienced with this matter. This last issue that I can't get to work or basically I don't understand the order in how to do this.
Been able to do the following:
Form that writes records to database
Page that shows database records in a table
Added an edit button to the table that takes you to an edit.php page with a form that has all values pre filled.
What I'm trying to get to work now is to edit one of the inputs on the form so it get's updated in the database.
So far I have this on the edit.php page:
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, email, age FROM members WHERE id =" .$_GET['id'];
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$id = $row['id'];
$name = $row['name'];
$email = $row['email'];
$age = $row['age'];
?>
<form action=" <?=$_SERVER['PHP_SELF']?> " method="POST">
<div align="center">
<div class="container">
<div class="row">
<div class="col-25">
<label for="#"></label>
</div>
<div class="col-75">
<h2>ID: <?php echo $row['id']; ?></h2>
</div>
</div>
<br>
<div class="row">
<div class="col-25">
<label for="name">Name:</label>
</div>
<div class="col-75">
<input type="text" name="name" value="<?php echo $row['name']; ?>" id="my-input" class="input-res">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="email">Email:</label>
</div>
<div class="col-75">
<input type="text" name="email" value="<?php echo $row['email']; ?>" class="input-res">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="age">Age:</label>
</div>
<div class="col-75">
<input type="text" name="age" value="<?php echo $row['age']; ?>" class="input-res">
</div>
</div>
<div class="row"><br>
<input type="submit" name="submit" value="Save updates" class="button">
</div>
</div>
</div>
</form>
</body>
</html>
Have tried adding this code below the form:
<?php
if(isset($_POST['Submit'])){//if the submit button is clicked
$sql="UPDATE name, email, age SET name, email, age WHERE name = ".$name.", email = ".$email.", age = ".$age.";
$conn->query($sql) or die("Cannot update");//update or error
}
?>
But the the page doesn't work anymore, tried changing from single quotes to double qoutes etc. but no success and a few other solutions (that unfortunatelly didn't work).
Need $_POST to get posted value
Use prepare for security
note: die is a wrong idea here
Correct code will be:
<?php
if (isset($_POST['Submit'],$_POST['name'],$_POST['email'],$_POST['age'],$_GET['id'])) { //if the submit button is clicked
$stmt = $conn->prepare('UPDATE name, email, age SET name = ?, email = ?, age = ? WHERE id=?');
$stmt->bind_param('ssii', $_POST['name'], $_POST['email'], $_POST['age'], $_GET['id']);
$stmt->execute();
echo "Updated successfully"; // Updated Successfully
}

Inserting Form Data into SQL table

I've been trying to figure this out for hours and it seems like there are multiple ways of doing it but for some reason I can't seem to get it to work correctly. For some reason my table is being updated and I am only seeing new rows with a new auto increment integer but the remaining columns are left blank. There is a bit more to that form but I left it off to keep this as short as possible. Thanks for the help!
File: dbh.inc.php
$dbServername = "localhost";
$dbUsername = "username";
$dbPassword = "password";
$dnName = "database_name";
$conn = mysqli_connect($dbServername, $dbUsername,
$dbPassword, $dnName);
if(!$conn)
// creation of the connection object failed
die("connection object not created: ".mysqli_error($conn));
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
File with form:
$name7 = $_POST['name7'];
$email7 = $_POST['email7'];
$phone7 = $_POST['phone7'];
$message7 = $_POST['message7'];
$sql = "INSERT INTO user_contacts (name7, email7, phone7, message7) VALUES ('".$_POST["name7"]."','".$_POST["email7"]."','".$_POST["phone7"]."','".$_POST["message7"]."')";
mysqli_query($conn, $sql);
?>
<div class="form-group">
<form action="dbh.inc.php" method="POST">
<input type="text" class="form-control" name="name7" id="name7" placeholder="<?php esc_html_e('Name:','listingpro'); ?>">
<span id="name7"></span>
</div>
<div class="form-group form-group-icon">
<i class="fa fa-envelope" aria-hidden="true"></i>
<input type="email" class="form-control" name="email7" id="email7" placeholder="<?php esc_html_e('Email:','listingpro'); ?>">
</div>
<div class="form-group">
<input type="text" class="form-control" name="phone7" id="phone7" placeholder="<?php esc_html_e('Phone','listingpro'); ?>">
<span id="phone7"></span>
</div>
<div class="form-group">
<textarea class="form-control" rows="5" name="message7" id="message7" placeholder="<?php esc_html_e('Message:','listingpro'); ?>"></textarea>
</div>
I have Just Edited your sql a little bit. Try It
$sql = "INSERT INTO user_contacts (name7, email7, phone7, message7) VALUES ('".
$name7. "','" . $email7 . "','". $phone7 ."','". $message ."')";

PHP SQL Form Insert Creation

I am trying to create a simple form that will insert the given data received by my HTML form, into my SQL table named 'Vendors', however I am struggling to work with its functionality.
There are 7 text fields that I am wanting to add to my Vendors table, and these are so named:
vendorName
addressL1 (Line 1)
addressL2
postcode
email
telephone
description
The HTML for this form can be found below:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form action="" method="post">
<ul class="form-style-1">
<li>
<label style="color:#4D4D4D;" >Vendor Name <span class="required">*
</span></label>
<center> <input type="text" name="vendorName" class="field-long"
required="required" placeholder="Vendor Name" /> </center>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Address <span class="required">*
</span></label>
<center> <input type="text" name="addressL1" required="required"
class="field-long" placeholder="Address Line 1" /> </center>
</br>
<center> <input type="text" name="addressL2" required="required"
class="field-long" placeholder="Address Line 2" /> </center>
</br>
<center> <input type="text" name="postcode" required="required"
class="field-short" placeholder="Postcode" /> </center>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Contact Details <span
class="required">*</span></label>
<center> <input type="text" name="email" required="required"
class="field-long" placeholder="Email Address" /> </center>
</br>
<center> <input type="text" name="telephone" required="required"
class="field-long" placeholder="Phone Number" /> </center>
</select>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Description </label>
<center> <textarea name="description" id="field5" class="field-long
field-textarea" placeholder="Description"></textarea> </center>
</li>
<li>
<center> <input type="submit" class="AddButton" value="POST"></input>
</center>
</li>
</ul>
</form>
</body>
</html>
And the PHP I have used is:
<?php
date_default_timezone_set('Europe/London');
$server = "";
$connectionInfo = array( "Database"=>"");
$conn = sqlsrv_connect($server,$connectionInfo);
if (!$conn)
{
die("Connection failed");
}
$_SERVER['REQUEST_METHOD'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$VendorName = $_POST['vendorName'];
$AddressLine1 = $_POST['addressL1'];
$AddressLine2 = $_POST['addressL2'];
$Postcode = $_POST['postcode'];
$VendorEmail = $_POST['email'];
$VendorNumber = $_POST['telephone'];
$VendorDes = $_POST['description'];
$time = time();
$timestamp = date("Y-m-d H:i:s", $time);
$describeQuery = ("INSERT INTO Vendors (VendorName, VendorAL1,
VendorAL2, VendorPost, VendorEmail, VendorNumber, VendorDes,
Added)
VALUES ('".$VendorName."', '".$AddressLine1."',
'".$AddressLine2."', '".$Postcode."',
'".$VendorEmail."', '".$VendorNumber."',
'".$VendorDes."', '".$timestamp."')");
$results = sqlsrv_query($conn, $describeQuery);
if(sqlsrv_query($conn, $describeQuery))
{
$alert = "Vendor Successfully Added";
echo "<script type='text/javascript'>alert('$alert');
</script>";
}
else
{
echo 'Information not inserted';
}
}
sqlsrv_close($conn);
?>
Each time I submit the form, it goes straight to the 'Information not inserted' ELSE statement and doesn't import the data into my database.
I have removed my server name and database name for precautionary reasons, however I can assure you they are correct as I have worked on a previous project and used the same method of connecting.
Any help on this would be greatly appreciated, and if there are any formatting mistakes, apologies in advance, I am not an avid user of stack overflow.
Use Mysqli Please, I have updated the script.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Vendors (VendorName, VendorAL1,
VendorAL2, VendorPost, VendorEmail, VendorNumber, VendorDes,
Added)
VALUES ($VendorName, $AddressLine1, $AddressLine2,$Postcode,$VendorEmail,$VendorNumber,$VendorDes,$timestamp)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>

Fatal error: Function name must be a string in line 12

Edited: This is the error I got.
$categoryName = $_POST['category_name'] ;
$categoryDesc = $_POST['category_desc'] ;
$sql = "INSERT INTO category (category_title, category_desc) VALUES ('$categoryName','$categoryDesc')";
if (mysqli_query($con,$sql))
{
echo 'Inserted successfully';
}
else
{
echo 'Inserted Failed';
}
mysqli_close($con);
?>
The error I got is Fatal error: Function name must be a string in line 12
line 12 : $categoryName = $_POST['category_name'] ;
[EDITED]
dbconnect.php (I am not sure that I am right or wrong because I am using virtual host, that's why my servername is my virtual host name)
<?php
$servername = "wp-one";
$username = "root";
$password = "";
$dbName = "personality_test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
html code
<div class="col-lg-6">
<form role="form" action="../controller/AddCategory&Question.php?create=true" method="post">
<div class="form-group">
<label>Category Name</label>
<input class="form-control" type="text" placeholder="CategoryName" name="category_name" />
</div>
<div class="form-group">
<label>Category Description</label>
<input class="form-control" type="text" placeholder="CategoryDesc" name="category_desc" />
</div>
<div class="form-group input_fields_wrap">
<button class="add_field_button btn btn-default" style="margin-bottom:10px;">Add New Question</button>
<div class="form-group">
<div class="row">
<div class="col-lg-2"><input type="text" placeholder="Number" class="form-control" name="criteria[]"></div>
<div class="col-lg-5"><input type="text" placeholder="Question" class="form-control" name="grade[]"></div>
</div>
</div>
</div>
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
Please help me, Thank You so much
$conn = new mysqli(...);
so you must use $conn instead of $con
if (mysqli_query($conn,$sql))
{
echo 'Inserted successfully';
}
else
{
echo 'Inserted Failed';
}
mysqli_close($conn);
whats your data type for category_title in database?
Your Error in connection
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
you use $conn and in insert file you use $can instead of $conn...

How to add variables into a mysql table from php

Okay so my objective is to have people able to select there schedule. her is the code so far
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "jesuitschedule";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'INSERT INTO schedule (Saturdaymorning, Saturdayafternoon, Sundaymorning, Sundayafternoon, weekday) VALUES (:Saturdaymorning, :Saturdayafternoon, :Sundaymorning, :Sundayafternoon, :weekday)';
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
//define page title
$title = 'schedule';
//include header template
require('layout/header.php');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>schedule</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="post" action="" autocomplete="off">
<h2>Please Select your schedule</h2>
<hr>
<div class="form-group">
<input type="checkbox" name="Saturdamorning" id="Satmor" class="form-control input-lg" placeholder="User Name" value="yes" tabindex="1">Saturday Morning <br>
</div>
<div class="form-group">
<input type="checkbox" name="Saturdayafternoon" id="Sataft" class="form-control input-lg" placeholder="S" value="yes" tabindex="2">Saturday Afternoon <br>
</div>
<div class="form-group">
<input type="checkbox" name="Sundaymorning" id="Sunmor" class="form-control input-lg" placeholder="S" value="yes" tabindex="3">Sunday afternoon <br>
</div>
<div class="form-group">
<input type="checkbox" name="Sundayafternoon" id="Sataft" class="form-control input-lg" placeholder="S" value="yes" tabindex="4">Sunday Morning <br>
</div>
<div class="form-group">
<input type="checkbox" name="weekday" id="email" class="form-control input-lg" placeholder="S" value="yes" tabindex="5">weekday <br>
</div>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Register" class="btn btn-primary btn-block btn-lg" tabindex="6"></div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
When I run my code all it works no errors but I when I check the table all I get is blank rows. The code adds a new sets of rows just doesn't add the data to them. I am trying to add either Yes, or to keep it blank if they do not select it. Any help would be great thanks.
As pointed out by Fred -ii-, you've not bound anything to your statement. Here's you code using a prepared statement. I've also commented the code as well to explain my position
if(isset($_POST['submit'])){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "jesuitschedule";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// You have a sql statement, but attempting to insert non-existant values. So you'll either
// wind up with an error, those values given in the statement inserted into the table,
// or just empty values.
//$sql = 'INSERT INTO schedule (Saturdaymorning, Saturdayafternoon, Sundaymorning, Sundayafternoon, weekday) VALUES (:Saturdaymorning, :Saturdayafternoon, :Sundaymorning, :Sundayafternoon, :weekday)';
// Create a prepared statement, let's you easily bind parameters
$stmt = $con->prepare(
'INSERT INTO schedule (
Saturdaymorning, Saturdayafternoon, Sundaymorning, Sundayafternoon, weekday
) VALUES (
:Saturdaymorning, :Saturdayafternoon, :Sundaymorning, :Sundayafternoon, :weekday
)';
);
// use exec() because no results are returned
//$conn->exec($sql); // You're executing a statement with no bound parameters
// You can use bindParam, but I find this method a tad easier
// Take the stmt created above, and bind the values to the parameters given
// in the statement, BUT, also execute. :)
$stmt->execute(array(
':Saturdaymorning' => 'value',
':Saturdayafternoon' => 'value',
':Sundaymorning' => 'value',
':Sundayafternoon' => 'value',
':weekday' => 'value'
));
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
If you'd like more info on this, take a look at the PDO page from the PHP site, which is where I pulled your fix: PHP: PDO - Manual

Categories