I've searched on the Internet to get my answer, but I couldn't find a helpful one. I've got a page called 'post.php' with a form where I can add an image and submit it to the database.
The big problem is when I go to mysite.com/post.php a new empty row is created automatically in the database, which I clearly don't want. I want only to update the database after clicking on the submit button my code:
the part of INSERT:
<?php
// POST.PHP POSTING NEW CONTENT
include 'config.php';
// values from form
$id=$_POST['id'];
$title=$_POST['title'];
$pic=$_POST['pic'];
$youtube=$_POST['youtube'];
$cat=$_POST['cat'];
// insert data to mysql
$sql = "INSERT INTO post(id, title, pic, youtube, cat)VALUES('$id', '$title', '$pic', '$youtube', '$cat')";
$result=mysql_query($sql);
// succes added
if(!$result){
echo "Something went wrong!";
}
else {
echo "Yeah, buddy! Your content is added.";
}
// end of post script ^^
?>
// end of insert
//POST IMAGE PAGE
if(isset($_GET['pic'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
title: <input name="title" type="text" id="title"><br />
Add url of image;<br />
<input type="text" name="pic" id="pic"/><br />
<?php
echo '
Category game:
<select name="cat"> ';
$query2 = mysql_query("SELECT * FROM `category`");
while($row=mysql_fetch_array($query2)){
echo '
<option value="'.$row["nameID"].'">'.$row["name"].'</option> ';
}
?>
</select>
<input type="submit" onclick="this.disabled = true" name="submit" value="submit">
</form>
<?php
// end script of posting picture
}
?>
You need to add some conditional code around the part that inserts into the database, checking for if any values has been received (if($myvar){ // do stuff }).
Add the rest of your code, specifically the part that adds stuff to the database as that is what's causing you problems, not the code you posted.
You need to wrap the whole block of database insertion code in an if statement. That way, it will not execute until the form has been submitted and $_POST['submit'] has a value:
include 'config.php';
if (isset($_POST['submit'])){
// values from form
$id=$_POST['id'];
// etc... code stays the same down to:
echo "Yeah, buddy! Your content is added.";
}
}//end if (don't forget to add this last bracket)
Also, you should switch to mysqli or PDO, and use parameterized queries. Otherwise, your site is open to a variety of gnarly attacks via SQL injection. It's not that hard to switch, and very, very important.
Check if the post have been set on the file that handles the database input.
if(isset($_POST['pic'])){
//do something
}
else{ // handle the exeption}
Also, you should not use mysql_* functions anymore. they are unsafe and deprecated as-of php 5.5
Related
I have created a drop down list as well a input type for for category and name but in both the case as i click next it directs me to another page but nothing saves in my database.
company_account is the table name in which data has to be inserted it has four rows id, category, cname, about
<?php include( "./inc/header.inc.php");
require( "./inc/connect.inc.php"); ?>
<div>
<form action = "payment.php" method= "POST">
<select id="category" name="category" class="old_ui_selector">
<option value="0" selected="1">Choose your category</option>
<option value="">Accounting Firm</option>
<option value="">Agriculture</option>
<option value="">Automotive</option>
<option value="">Aerospace/Defence</option>
<option value="">Building Material</option>
</select>
</div>
<br>
<input type = "text" name="cname" placeholder= "Name"/>
<br><br>
By clicking Next you agree to the Terms and Conditions.
<br>
<input type = "submit" name="comp" value="Next"/>
</form>
<?php
if(isset($_POST['comp']))
{
$category=$_GET['category'];
$cname = $_POST['cname'];
$ins=mysql_query("insert into company_account (category) values ('$category')");
$insert = mysql_query("INSERT INTO company_account VALUES ('','$category','$cname','$about')");
if($ins)
if($insert)
{
echo "<br>".$category."inserted";
}
else
{
echo mysql_error();
}
}
?>
You have a few issues there, the first is you are using mysql, either update it to mysqli or better still PDO.
Second your form is submitting using POST and yet you try to collect the category using GET.
You also need to supply the contents of your connect.inc.php WITHOUT THE IP AND PASSWORD so people can have a look at the config.
I would suggest before going any further you have read here and get a better understanding before you proceed.
https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Best of luck.
Note: mysql: This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
You have provided with the form action and that will redirect after clicking the submit button.
You have written the INSERT STATEMENT in the same page itself and that will not even work for you.
First Remove up the action="" and then you redirect it based on the data saved.
HTML:
<form action = "" method= "POST">
</form>
And you Option value is missing out values and after the form is submitted the values will not be entered into the DB. Hence you need to do the following.
Replace:
<option value="">Accounting Firm</option>
With:
<option value="Accounting Firm">Accounting Firm</option>
PHP Code for Insert:
You Insert Code will not work since you have not provided with the table values for insert operations.
Syntax:
INSERT INTO TABLENAME(`columnname1`,`columnname2`,.....) VALUES(VALUE1,VALUE1,....)
Hence you are advised to use the correct table structure for the Operations and then insert the data.
INSERT QUERY:
$insert = mysql_query("INSERT INTO company_account(`category`,`name`,`about`) VALUES ('$category','$cname','$about')");
You can insert all in the single query itself and then redirect using the header location.
Use header Location for redirection to particular page after the data has been saved.
header('location : http://www.google.co.in');
PHP PART:
<?php
if(isset($_POST['comp']))
{
$category=$_POST['category'];
$cname = $_POST['cname'];
$insert = mysql_query("INSERT INTO company_account(`category`,`name`,`about`) VALUES ('$category','$cname','$about')");
$rows = mysql_affected_rows();
if($rows=0)
{
echo mysql_error();
}
else
{
ob_start(); // Refresh the Output Buffer
header('location: http://www.google.co.in');
exit;
}
}
?>
Note: $about you are using in the Insert Statement but no values are provided over to the Insert Statement. Please check to that.
So here is my dilemna that I've been reviewing and trying to break through for the last few days. I've created a basic login/register PHP system, which works fine. I've implemented a blog system that displays posts. I've written an add post function which does not post to the database, and it doesn't throw back an error function either.
I don't really understand because my register system works and adds new users, but the 'add blog post' does nothing. I can add from the database and it displays fine, but nothing here.
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: login.php');
die();
}
if ($_POST['submit']) {
$title = strip_tags($_POST['title']);
$subtitle = strip_tags($_POST['subtitle']);
$content = strip_tags($_POST['content']);
mysqli_query($dbCon, $userREQ3);
$userREQ3 = " INSERT INTO `logindb`.`blog`
(`title`, `subtitle`, `content`) VALUES ('$title','$subtitle','$content')";
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Welcome, <?php echo $username; ?>, You are logged in. Your user id is <?php echo $userId; ?>.
Index
<form action="logout.php">
<input type="submit" value="Log me out!">
</form>
<form method="post" action="admin.php">
Title: <input type="text" name="title"/><br>
Subtitle: <input type="text" name="subtitle"/><br>
<br>
<br>
Content: <textarea name="content"></textarea>
<input type="submit" value="Write Post"/>
</form>
</body>
</html>
Your code is failing for two reasons.
Your conditional statement is looking for a named element called "submit"
You're trying to execute before the statement. Place your query (mysqli_query())"below" the values and do mysqli_query($dbCon, $userREQ3) or die(mysqli_error($dbCon));
Sidenote: Change if ($_POST['submit']) { to if (isset($_POST['submit'])) { it's better.
and <input type="submit" value="Write Post"/>
to <input type="submit" name="submit" value="Write Post"/>
SQL injection:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
Also, you have variables in the body of your code, which may throw undefined variable x on initial page load.
Use a ternary operator for this
http://php.net/manual/en/language.operators.comparison.php
Use this for all your inputs/variables
As stated (in comments below): Make sure that you have connected to your database and using a mysqli method and not another API.
https://secure.php.net/mysqlinfo.api.choosing
Different MySQL APIs do not intermix with each other. Use the same MySQL API from connection to query.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Successful query or not:
To see if the query was indeed successful, or failed, check for errors and use affected_rows.
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.affected-rows.php
PHP Not Inserting Content in mySQL Database: Text, Images, Anything
If you were trying to use images, then a valid enctype is required to be included in the form tags.
Depending on how/what you wanted to insert for the images, than that could be a factor.
If you're wanting to insert the image as a path is one thing, but using it "as an image", say a BLOB then that has limitations in size; use LONGBLOB and you must escape that data before going in the database.
Consult:
https://dev.mysql.com/doc/refman/5.0/en/blob.html
http://php.net/manual/en/features.file-upload.post-method.php
Try to generate the query first, then execute it...
$userREQ3 = " INSERT INTO `logindb`.`blog`
(`title`, `subtitle`, `content`) VALUES ('$title', '$subtitle','$content')";
mysqli_query($dbCon, $userREQ3);
I am developing a web application where I want to restrict update or insert more than once by navigating back to referring page. Let me present you three model files in the order of flow so that I can raise the zone where I am stuck.
register.html
<html>
...
<form id="form1" name="form1" method="post" action="process.php">
<label for="textfield">Name</label>
<input type="text" name="name" id="name" />
<input type="submit" name="Submit" value="Submit" />
</form>
...
</html>
process.php
<?php
echo "Welcome ".$_GET['para'];
?>
success.php
<?php
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
// some database update here ...
echo "<a href='success.php?para=$name'>Done. Click to go next</a>";
unset($_POST['Submit']);
}else{
echo "Error in submission";
}
?>
The above three files are very simple. Here the update part has nothing to do when the user hits the back button after landing on page success.php because of unset($_POST['Submit']);. But when the user goes back further by hitting the back button again it reaches register.html and can again come up with the $_POST['Submit'] set and may do the update part which is sometimes vulnerable. I know there is Post/Redirect/Get to solve this issue, but I want some other alternatives so that the part gatekeepering the update part may be made so efficient that it would not allow the same anymore by clicking the back button.
If you are getting duplicate records inserted.
You may try INSERT IGNORE
ADD UNIQUE INDEX to your table to prevent this happening
you may choose any one of INSERT IGNORE and REPLACE according to the duplicate-handling behavior
Refer https://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html
Lastly you may like simple php with mysqli_num_rows()
$sql = "SELECT id FROM table-name WHERE column-name1 = ? AND column-name2 = ? ;
$mq = mysqli_query($sql);
if (mysqli_num_rows($mq) < 1) {
$sql = "UPDATE table-name SET (colum-names) VALUES (...)";
mysqli_query($sql);
else {
echo "Record already updated";
}
}
I just start coding in PHP,
i wrote my first php + mysql program for inserting data through web form. it works fine, but whenever i refresh the page, it automatically saves null record to my database.
i know the solution in .NET is ispostback, but not in php?
can somebody give me some idea in PHP.
Code is here:
<body>
<form action="mySQLTest.php" method="post">
First Name :<input type="text" name ="txtFirstName"/> <br/>
Last Name: <input type="text" name ="txtLastName"/> <br/>
Age : <input type="text" name= "txtAge" /> <br/>
<input type="submit"/>
</form>
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die('Could not Connect:' .mysql_error());
}
mysql_select_db("test", $con);
if($_REQUEST[])
{
$sql1 = "Insert into info(FirstName, LastName, Age) Values('$_POST[txtFirstName]','$_POST[txtLastName]','$_POST[txtAge]')";
}
if(!mysql_query($sql1, $con))
{
die('Error: '.mysql_error());
}
else
{
echo "1 Record Added";
}
mysql_close($con)
?>
</body>
Have you tried if ($_SERVER['REQUEST_METHOD']=='POST')
updated answer:
if ($_SERVER['REQUEST_METHOD']=='POST') {
[insert...]
header('Location: added_record.php');
}
When you use the POST-method, it's better (imho) to use $_POST rather than $_REQUEST. To check whether you have data, you could use isset($_POST['txtFirstName']);. If you need all data, it's best to do this for all input fields, resulting in
if(isset($_POST['txtFirstName']) && isset($_POST['txtLastName']) && isset($_POST['txtAge'])) {
// do stuff
}
If you want to know if there was any field submitted using post, you could use if(!empty($_POST)) {.
On a side note: I know you are just starting PHP, it could be quite dangerous to use user-generated code in queries. When you are building stuff online, for everyone to reach, please read a bit about SQL injection. This will also prevent your code from breaking when someone enters an apostrophe (').
HTML
<form action="inc/q/prof.php?pID=<?php echo $the_pID; ?>" method="post">
<select id="courseInfoDD" name="courseInfoDD" tabindex="1"><?php while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }echo "</select>"; ?>
<input type="text" id="addComment" name="addComment" tabindex="3" value="Enter comment" />
<input type="hidden" name="pID" value="<?php echo $the_pID; ?>">
<input type="submit" name="submit" id="submit" />
</form>
PHP
$connect = mysql_connect("##", $username, $password) or die ("Error , check your server connection.");
mysql_select_db("###");
//Get data in local variable
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
if(!empty($_POST['addComment']))
$course_info=mysql_real_escape_string($_POST['addComment']);
if(!empty($_POST['pID']))
$the_pID=mysql_real_escape_string($_POST['pID']);
print_r($_POST);
echo $the_pID;
// check for null values
if (isset($_POST['submit'])) {
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
else if(!isset($_POST['submit'])){echo "No blank entries";}
else{echo "Error!";}
?>
?>
Table
commId int(11)
info text
date timestamp
reported char(1)
degree char(1)
pID int(11)
cID int(11)
It gives me "Error!" now, I try the db credentials and they are fine... ?? And the r_post() is still giving an error of Array()
Why isn't Array() accepting values? Anyone???
Like #user551841 said, you will want to limit your possibility of sql injection with his code.
You are seeing that error because you're code told it to echo that error if nothing was entered, which is the case upon first page load. You shouldn't need that until submit is done.
Edit: Sorry, I was assuming you are directly entering the page which needs the $_POST data without going through the form submit.
You also should do something along the lines of if(!isset($variable)) before trying to assign it to something less your server will spit out error of undefined variables.
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
do that to all of them.
Then you can check
if (!isset($user_submitted) && !isset($the_comment) && !isset($course_info) && !isset($the_pID) ){
echo "All fields must be entered, hit back button and re-enter information";
}
else{
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
Check that the hidden field "pID" has a value set from value=<?php echo $the_pID; ?>
Make sure that your data is valid before checking it.
For instance do
print_r($_POST);
and check if the keys and their data match up.
Also, as a side note, NEVER do what you're doing with :
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
This is how mysql injection happens, either use prepared statements or
$course_info= mysql_real_escape_string($_POST['courseInfoDD']);
To answer to your question what is wrong here
you've got a huge gaping SQL-injection hole!!
Change this code
//Get data in local variable
$course_info=$_POST['courseInfoDD'];
$the_comment=$_POST['addComment'];
$the_pID=$_POST['pID'];
To this
//Get data in local variable
$course_info = mysql_real_escape_string($_POST['courseInfoDD']);
$the_comment = mysql_real_escape_string($_POST['addComment']);
$the_pID = mysql_real_escape_string($_POST['pID']);
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For more info on SQL-injection.
i would change this line
if (isset($_POST['submit'])) {
to
if ($_POST) {
the sumbit button field will not always be posted, for example if you press return on keyboard instead of clicking on the submit button with the mouse.
Cleaner:
$submit = isset($_POST['submit']) ? true : false;
$comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
if ($submit && $comment) {
$query = 'INSERT INTO comments (comment) values("' . mysql_real_escape_string($comment) . '")';
//...
}
As you can see I place the escaping inside the query. And this is a good idea because sometimes you loose track of the complete code and this won't happen inside a query.