Problem with $_POST - php

This wont work. All the fields are correct etc and I have a db connection.
To the problem
I use this script to insert a post into the db:
<?php
if (isset($_POST['msg'])) {
$title = mysql_real_escape_string($_POST['title']);
$msg = mysql_real_escape_string($_POST['msg']);
// kolla efter tomma fält
if (empty($title) || empty($msg)) {
$reg_error[] = 1;
}
if (!isset($reg_error)) {
mysql_query("INSERT INTO messages (title, message, date, user_id)
VALUES('$title', '$msg', '".time()."', '2')");
header('location: /');
exit;
}
}
?>
The Form:
<form action="post_msg.php" method="post">
<b>Title:</b>
<input type="text" name="title" size="40" />
<b>Message:</b>
<textarea rows="15" cols="75" name="msg"></textarea>
<input type="submit" value="Post Message" />
</form>
Worked fine the other day. Not today. No errors. The "post stuff" shows up in the url. I thought it only did when using $_GET which i dont.
http://localhost/post_msg.php?title=fdsg&msg=sdfg
i dont get any errors the page just reloads
messages db
CREATE TABLE IF NOT EXISTS `messages` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(140) COLLATE utf8_unicode_ci DEFAULT NULL,
`message` text COLLATE utf8_unicode_ci
`date` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `title` (`title`,`message`)

Sounds like your form isn't set to use POST
<form action="post_msg.php" method="post">

A few comments that might help:
Please provide log output, error messages
Print the SQL and run it manually on the server, what errors occur?
Your SQL construction using string concatenation is really grim and probably a security hazard.
Look at the documentation for PDO. The API in PHP, although inconsistently named is fairly stable. So it is most likely that you did something wrong, in which case an error should ensue.

If everything works fine you get a result. But if anything "fails" you get nothing, no message what so ever. It leaves you in the dark, clueless. And that's bad.
Turn on the error reporting. Don't just have an if-block, add an else-block, too.
<?php
error_reporting(E_ALL); ini_set('display_errors', true);
if (isset($_POST['msg'])) {
$title = mysql_real_escape_string($_POST['title'])
or die('escape_string title failed');
$msg = mysql_real_escape_string($_POST['msg'])
or die('escape_string msg failed');
// kolla efter tomma fält
if (empty($title) || empty($msg)) {
$reg_error[] = 1;
}
if (!isset($reg_error)) {
mysql_query("INSERT INTO messages (title, message, date, user_id)
VALUES('$title', '$msg', '".time()."', '2')")
or die(mysql_error());
header('location: /');
exit;
}
else {
print_r($reg_error);
}
}
else {
echo 'post parameter "msg" missing';
}
?>

echo what the query result
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
did the script enter to the line that doing the query ?

Remove the redirect header and type this at the end of the script for debugging:
var_dump($_POST);
echo mysql_error();

I just noticed something weird...
$reg_error is an array the way you wrote it.
$reg_error[] = 1;
So.. assign a key to that array, like $reg_error[0] or whatever.. and then
if(count($reg_error) > 0) { /* your code */ }
..or just remove the [] brackets from $reg_error and leave the if/else as is.

With the code provided, reg_error is only used to determine whether or not perform the SQL. Instead of setting a variable (since its only set dependent upon a conditional statement), why not just change your code to do:
<?php
if (isset($_POST['msg'])) {
$title = mysql_real_escape_string($_POST['title']);
$msg = mysql_real_escape_string($_POST['msg']);
// kolla efter tomma fält
if (!empty($title) && !empty($msg)) {
mysql_query("INSERT INTO messages (title, message, date, user_id)
VALUES('$title', '$msg', '".time()."', '2')");
header('location: /');
exit;
}
else {
echo "There was an error";
}
}
?>
This would simply the code. The else statement would obviously, eventually be modified, but for now would give you a fall back way of showing you if it even attempted the SQL query. If its not, the condition is failing and you arent getting values from the post for some reason.
The only way your URL would change is if the method of the form tag was changed. If it's set to post, it shouldnt show in the URL.

I found the problem! i checked my header.php file and guess what? there was a form i hadent closed :/ sorry for bothering you guys

Related

Code won't insert into database

I have the following code that should collect the filled values from a former page and insert them in a MySQLi database. This does not work and I only get a blank page as a result, without any messages. I can't figure out what I'm doing wrong.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$welcome_text = $_POST['welcome_text'];
$thanks_message = $_POST['thanks_message'];
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
$logo = getimagesize($_FILES['image']['tmp_name']);
$image_type = $logo['mime'];
$q = "INSERT INTO project VALUES('','$company_name','$description','$image','$image_type','$welcome_text','$thanks_message')";
$r = mysqli_query($mysqli,$q);
if($r)
{
echo "<h1>Projektet är skapat!</h1><br>
Tryck på knappen nedan för att ta dig till Dashboard.<br><br>
<a href='dashboardadmin.php'><button id='projectbutton'>Dashboard</button></a>";
}
else
{
echo mysqli_errno($mysqli) . ": " . mysqli_error($mysqli) . "\n";
}
?>
Correct syntax of INSERT is:
INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...);
Please try entering column names before your values first. Also check your $_POST values, whether $_FILES['image'] is available and confirm your mysqli connection.
Edits:
Is the first value (empty one) your primary key? If so, can you omit that bit in your code and try again? (Assuming pid is integer and auto incrementing value.)
INSERT INTO project (project_name, description, image, image_type, welcome_text, thanks_message) VALUES('$company_name','$description','$image','$image_type','$welcome_text',‌​'$thanks_message')
Somehow I don't think this would be Azure specific issue as per your comment.
Can you see any errors in logs etc? Also try echoing the query before you run it and check if you run it directly on your phpmyadmin etc to see if it'd work.
Please also try using echo mysqli_errno($mysqli) . ": " . mysqli_error($mysqli) . "\n";
at if($r){..} else { //here } to see if you get an error.
Latest Update:
$q = "INSERT INTO project (project_name, description, image, image_type, welcome_text, thanks_message) VALUES('".$company_name."','".$description."','".$image."','".$image_type."','".$welcome_text."','".$thanks_message."')";
Try this, because your primary key value is auto incremented.
$q = "INSERT INTO project VALUES('$company_name','$description','$image','$image_type','$welcome_text','$thanks_message')";

Row is inserted into database everytime I refresh the page

Every time I try to refresh the page I get a new row. I tried to read many posts regarding to this problem, but I couldn't do anything since I'm new in database programming.
I don't know where the value come from, because the same value is repeated over and over.
My code.
<?php
require('connect.php');
$sql="CREATE TABLE test(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
user VARCHAR(25),message LONGTEXT)";
if($sql==true){
$res=mysql_query( $sql);
}
?>
<?php
$user=null;
$message=null;
if(isset($_POST['user'])){
$user=$_POST['user'];
}
if(isset($_POST['message'])){
$message=$_POST['message'];
}
if(!empty($_POST)){
if($user&&$message){
$insert=mysql_query("INSERT INTO test(user,message)VALUES('$user','$message')");
}
else{
echo "please fill out the fields";
}
}
?>
<html>
<body>
<form action="database.php" method="post">
<p><label for="user">Name:</label><br/>
<input type="text" name="user" id="user"/></p>
<p><label for="message">Message:</label><br/>
<textarea ="message" name="message"> </textarea></p>
<button type="submit" name="submit" value="send">Send Message:</button>
</form>
<br/><br/><tr><td>The Users Comments:</td><td><br/><br/>
</html>
<?php
$query=mysql_query("SELECT * FROM test ORDER BY id DESC");
while($row=mysql_fetch_ASSOC($query)){
$name=$row["user"];
$message=$row["message"];
echo "username:",$name,'<br/>'," Messages: ",$message,'<br/>','<br/>';
}
?>
Problem is that everytime you refresh the page your browser is re-posting the same data. To workaround it you should consider implementing the Post, Redirect, Get pattern in your page.
Fundamentally this means that upon a successful POST (i.e. row was inserted) you should redirect to another page. This effectively stops the user from having the ability to re-post the same data.
The link above has a good overview of how to implement...
I don't find a problem in your code. Probably when you post data first time and then refresh the page, data is posted again. Most of the browsers like firefox gets confirmation if browser is re-posting data.
Edit:
To avoid this you must use redirect to GET method. see this
try to edit this
Blockquote
if(!isset($_POST)){
if($user && $message){
$insert=mysql_query("INSERT INTO test(user,message)VALUES($user,$message)");
}
and be sure ctrl+f5 then refresh page
Before insert check database if those values are present in database or not
like
if(!empty($_POST)) {
if($user && $message) {
//check if this user and message in present database or not
$query = mysql_query("SELECT * FROM test WHERE user='".$user."' AND message='".$message."'");
$count = mysql_num_rows($query);
if ($count > 0 ){ // if $count is greater than 0 means values exists in database then
echo "Data exists";
}
else {
// insert
$insert=mysql_query("INSERT INTO test(user, message) VALUES ('$user','$message')");
}
}
else {
echo "please fill out the fields";
}
it is just a example you can modified it with your requirement :)

Null Values in DB

I am trying to make a VERY simple PHP form that posts a form to MySQL Database, however I am having some issues, and would welcome a simple fix for this if possible:
My PHP:
<?php
$con=mysqli_connect("serveraddress","db","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (email, type, cats)
VALUES
('$_POST[email]','$_POST[type]','$_POST[cats]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
My HTML:
<form action="personuploader.php" method="post">
<table class="#">
<tr>
<th colspan="2">Test</th>
</tr>
<tr>
<td>Email Address:</td>
<td><input type="text" name="email"> </td>
</tr>
<tr>
<td>Type:</td>
<td><input type="text" name="type"> </td>
</tr>
<tr>
<td>Cats:</td>
<td><input type="text" name="cats"> </td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="upload" name="upload">
</tr>
</table>
</form>
My SQL Configuration:
Even though I have not null set in the DB I am getting empty results, is it possible to stop the form resubmitting on refresh causing null results be entered into the DB. I will enter some form validation to stop null results passing into the post script in the future but refreshing the page still sends over null results.
Edit:
Your column names have mixed-case letters (Cats and cats are not the same)
I edited my answer, where I changed it from:
$sql="INSERT INTO `Persons` (`email`, `type`, `cats`)
to
$sql="INSERT INTO `Persons` (`Email`, `Type`, `Cats`)
I also made a mistake with a missing ) for if(empty($_POST['email'] which has been fixed.
Please make sure also, that your column names are indeed called Email Type Cats and not email type cats Change it to the letter-case that is in your DB.
Your table's original structure: (larger image)
You should have talked to me first, instead of posting a new question with my code
See the rest below in the code.
As I stated in my comments under your original question, have put this together for you.
Don't use this method VALUES ('$_POST[email]','$_POST[type]','$_POST[cats]') you're open to SQL injection
To avoid re-submissions causing an empty entry, you can use a header() to redirect to another page, or use AJAX
However, I am sure there are other ways of doing this in the query itself, I just don't remember how right now.
I.e.: In place of where you have echo "1 record added";
you can do header("Location: added.php"); exit();
You can also use a conditional statement:
if(empty($_POST['variable'])){ die("Fill this in.");}
Try the following. It will check for empty fields, as well as check if the upload submit-type button is set.
Plus, I modified the way your query was done, replacing POST variables with mysqli_real_escape_string()
<?php
$con=mysqli_connect("serveraddress","db","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['upload'])){
// You can replace the || with && if required
// depending on what you want to check for.
if(empty($_POST['email']) || empty($_POST['type']) || empty($_POST['cats']))
{
die("You need to fill in all the fields.");
}
$email = mysqli_real_escape_string($con, $_POST['email']);
$type = mysqli_real_escape_string($con, $_POST['type']);
$cats = mysqli_real_escape_string($con, $_POST['cats']);
$sql="INSERT INTO `Persons` (`Email`, `Type`, `Cats`)
VALUES ('$email','$type','$cats')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
// Uncomment out if you're going to use echo, but not with header.
// echo "1 record added";
header("Location: redirect_to_other_page.php");
exit();
} // end of if(isset($_POST['upload']
// else conditional statement for if(isset($_POST['upload']
else{ echo "You cannot do this operation from here."; }
mysqli_close($con);
?>
Footnotes:
Just saying, the following:
('$_POST[email]','$_POST[type]','$_POST[cats]')
should have been:
('$_POST['email']','$_POST['type']','$_POST['cats']')
However, using this method is highly discouraged, as I already mentioned.
You need to check if a submit actually occured:
if ($_SERVER["REQUEST_METHOD"] == 'POST') {
... submit occured, do DB stuff
}
And note that an empty string is NOT the same as an SQL null. Empty string is just that - a string which happens to be empty/zero-length. An SQL null is quite literally "unknown". Your code cannot insert an actual null - it can only ever insert empty strings.
You should check whether the Upload button has been clicked on the "personuploader.php" file.
// Initializing Variables
$email = '';
$type = '';
$error = false;
if ( isset ( $_POST['upload'] ) ) {
// Then capture the POST Variables
$email = $_POST['email'];
// Do Some Validations
if ($email == '') {
$error = true;
}
// Process the Form if NO Errors
if ($error == false) {
// Insert The Data into DB
}
}

Insert Into - php mysql

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.

How to handle error for duplicate entries?

I have a PHP form that enters data into my MySQL database. My primary key is one of the user-entered values. When the user enters a value that already exists in the table, the MySQL error "Duplicate entry 'entered value' for key 1" is returned.
Instead of that error, I would like to alert the user that they need to enter a different value. Just an echoed message or something.
How to turn a specific MySQL error into a PHP message?
To check for this specific error, you need to find the error code. It is 1062 for duplicate key. Then use the result from errno() to compare with:
mysqli_query('INSERT INTO ...');
if (mysqli_errno() == 1062) {
print 'no way!';
}
A note on programming style
You should always seek to avoid the use of magic numbers (I know, I was the one to introduce it in this answer). Instead, you could assign the known error code (1062) to a constant (e.g. MYSQLI_CODE_DUPLICATE_KEY). This will make your code easier to maintain as the condition in the if statement is still readable in a few months when the meaning of 1062 has faded from memory :)
You can check the return value from mysql_query when you do the insert.
$result = mysql_query("INSERT INTO mytable VALUES ('dupe')");
if (!$result) {
echo "Enter a different value";
} else {
echo "Save successful.";
}
try this code to handle duplicate entries and show echo message:
$query = "INSERT INTO ".$table_name." ".$insertdata;
if(mysqli_query($conn,$query)){
echo "data inserted into DB<br>";
}else{
if(mysqli_errno($conn) == 1062)
echo "duplicate entry no need to insert into DB<br>";
else
echo "db insertion error:".$query."<br>";
}//else end
With mysql_error() function
http://php.net/manual/en/function.mysql-error.php
Use mysql_errno() function, it returns the error numbers. The error number for duplicate keys is 1062.
for example
$query = mysql_query("INSERT INTO table_name SET ...);
if (mysql_errno() == 1062){
echo 'Duplicate key';
}
This is my full code that I used and works perfect. Its PDO friendly, and can handle your error easily, (once you have used die to discover what that is. Then you can copy the error message from there, and enclose it in an if. This came from a signup page, where I wanted to redirect to the login page, if the primary key (email) was found, and produced an error.
function insertUserDetails($email, $conn){
try {
$query = $conn->prepare ("INSERT INTO users (emailaddress) VALUES (:email)");
$query ->bindValue('email', $email);
$query->execute();
}
catch (PDOException $e) {
if(str_contains($e, '1062 Duplicate entry')) {
header("Location: login.php");
}
die("Error inserting user details into database: " . $e->getMessage());
}
}

Categories