从php脚本发送到mySQL的双重条目

Even though I execute the the script once(one mysql_query), I get duplicate entries for some reason in the mySQL table.

These entries are not the same - the 'duplicate' entry will always have the same fields for the columns Timestamp and Picture, but the rest of the columns empty.

This is my script:

<?php

 session_start();

 $con = mysql_connect("Fruity.mysql.anyhost.com", "apples", "password");

 mysql_select_db("IAN_1");


 $username = $_SESSION['username'];
 $image = $_POST['image'];
 $post = $_POST['postdescription'];
 $idcolor = $_POST['idcolor'];
 $idbgcolor = $_POST['idbgcolor'];
 $timestamp = date("jS \of F Y h:i:s A P");



 $user_uploadposts = 
 "INSERT INTO $username (Timestamp, Image, Description, ID_color, ID_backgroundcolor)  
  VALUES ('$timestamp','$image', '$post','$idcolor','$idbgcolor')";


  mysql_query($user_uploadposts);


  mysql_close($con)

 ?> 

a screenshot of the problem http://i.imgur.com/DaPiRYm.jpg

This is too long for a comment.

Firstly, $_POST['image'] suggests that we are dealing with files and if so, your form requires a valid enctype, a POST method, plus you would need to use $_FILES rather than $_POST if that is the case.

We also don't know if the session array has been set (no idea why you're using it here), and if your form elements contain matching name attributes.

I.e.: <input type="text" name="postdescription">

and your form should contain method="post" enctype="multipart/form-data".

If your form and PHP/MySQL are inside the same file, you will need to use isset() or !empty() for your variables. You may be getting undefined index notices, but they're not being displayed.

  • Error reporting will tell you that.

I.e.: if(!empty($_POST['postdescription'])){...} same for the others.

What you also need to do is to have a primary key; that usually fixes things.

You also have a missing semi-colon for mysql_close($con) add it mysql_close($con);.

Replace your current code with:

mysql_query($user_uploadposts) or die(mysql_error());

in order to find errors and error reporting.

Plus, you are also using the MySQL reserved word Timestamp, and it should be wrapped in ticks.

INSERT INTO $username (`Timestamp`, Image, ...

If that still doesn't work, then your incoming data may contain characters that MySQL will complain about.

  • Escape your data.
  • I.e.: $post = mysql_real_escape_string($_POST['postdescription']);

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: Displaying errors should only be done in staging, and never production.


Your present code is open to SQL injection.

Use mysqli with prepared statements, or PDO with prepared statements.