How do I insert data to a MySQL table?

July 7, 2015 1.1k views
PHP MySQL LAMP Stack Miscellaneous Ubuntu

I installed phpMyAdmin on a LAMP server and using it to create and modify databases.

I have a database named 'download' which has a table 'table1'.
table1 has three columns namely 'name','path1','id'.

I'm trying to make a upload/download web app. This is my upload.php code. Upload works fine(without the sql code). But I'm unable to insert data to table. What am I doing wrong?

Thanks in advance!


DEFINE ('DB_USER', 'root');
DEFINE ('DB_PSWD', '*********');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'download');

$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
$type = $_FILES['file']['type'];
$tmp_name = $_FILES['file']['tmp_name'];

$dbcon = mysql_connect(DB_HOST, DB_USER, DB_PSWD,DB_NAME);

if(!$dbcon) {
    die('Error conncting to database');

$length = 5;
$randomString = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);

$trial = "trial upload!";

echo "Upload a file. ";

if (isset($name)) {
     if (!empty($name)) {
        $location = 'uploads/';
        if (move_uploaded_file($tmp_name, $location.$name))
            $sqlinsert = "INSERT INTO table1 (name, path1, id) VALUES ('$name','$trial' '$randomString')";
            if(!mysql_query($dbcon, $sqlinsert)) {
                die('Error inserting new record');

            $success = "File uploaded!";

        } else {
            echo "There was an error. Please try again";
     } else {
        echo "Please choose a file.";

<form action="upload.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="file"><br><br>
    <input type="submit" value="Submit">

    echo $success;
1 Answer

First of all, disregard all of your SQL code and rewrite it using either PDO or the improved extension of MySQL: MySQLi. The original MySQL extension is deprecated as of PHP 5.5.0, see choosing an API.

Then look into prepared statements, what you are doing in your code is rather foolish and should never be used in the first place (search for SQL injections). You don't sanitize the user input and fully trust it, therefore using prepared statements is a better option for you.

Lastly, if you're so foolish and only wish for a "fix" of your code: you need to provide an error or some kind of additional information when posting a thread like this.

if(!mysql_query($dbcon, $sqlinsert)) {
    die('Error inserting new record');

Rewrite to:

if(!mysql_query($dbcon, $sqlinsert)) {
    die('Error inserting new record. ' . mysql_errno($dbcon) . ': ' . mysql_error($dbcon));
Have another answer? Share your knowledge.