Error inserting data into mysql database

I have created four input field where user types in the details for a entry and below that a preview is generated for that. the process till preview goes fine. But as soon as i click Continue button to proceed to payment.php it should save all the details along with the image to database table "productad". But nothing happens in the table when i click continue button only payment.php gets opened but no data entries are entered. Here is the code:

 
<?php include( "./inc/companyheader.inc.php");
     require( "./inc/connect.inc.php");

    if (isset($_POST['productad'])) {
        $name = $_POST['nameInput'];
        $desc = $_POST['descInput'];
        $price = $_POST['priceInput'];
        $brand = $_POST['brandInput'];
    if (!empty($name) || ($desc) || ($price) || ($brand)) {

    $insert = "INSERT INTO productad ($nameInput, $descInput, $price, $brand)  VALUES ('$_POST[nameInput]','$_POST[descInput]','$_POST[priceInput]','$_POST[brandInput]')";
     //  mysql_query("UPDATE productad SET file_md5='$md5_file' WHERE video_id='$video_id'");
    }
    else
    {
       die('Empty Fields');
    }
    }
    ?>
    <html  >
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script type="text/javascript">
            function KeyHandler() {
                var name = document.getElementById('name');
                name.innerHTML=document.getElementById('nameInput').value;
                //var image = document.getElementById('image');
                //image.innerHTML=document.getElementById('prodimage').value;
                var desc = document.getElementById('desc');
                desc.innerHTML=document.getElementById('descInput').value;
                var price = document.getElementById('price');
                price.innerHTML=document.getElementById('priceInput').value;
                var brand = document.getElementById('brand');
                brand.innerHTML=document.getElementById('brandInput').value;
            }

    </script>
    <script type='text/javascript'>
    function preview_image(event)
    {
     var reader = new FileReader();
     reader.onload = function()
     {
      var output = document.getElementById('output_image');
      output.src = reader.result;
     }
     reader.readAsDataURL(event.target.files[0]);
    }

    </script>
    <style>
    #wrappr
    {
     text-align: left;
     margin:0 auto;
     padding:0px;
     width:995px;
    }
    #output_image
    {
     max-width:300px;
    }
    </style>
    </head>
    <body >
    <h2>Create A new entry</h2>
    <br />

    Name
    <input type='text' id='nameInput' name='nameInput' onkeyup="KeyHandler()" />
    <br/>
    <br/>
    Product Image
    <input type="file" accept="image/*" onchange="preview_image(event)" />
    <br/>
    <br/>
    Description
    <input type='text' id='descInput'onkeyup="KeyHandler()" />
    <br/>
    Price
    <input type='text' id='priceInput'onkeyup="KeyHandler()" />
    <br/>
    Brand/Store
    <input type='text' id='brandInput'onkeyup="KeyHandler()" />
    <br/>
    <br/>
    <span>
    <strong>Preview:</strong></span>
    <div style="background: #fff; border: 1px solid #ccc; padding: 7px 5px; margin: 0; width: 310px;">
    <div id="name" style="color:#004d49; font-weight:bold; font-size:140%;"></div><br>
    <div><img id="output_image" align="center"/></div><br>
    <div id="desc" style="font-weight:bold; font-size:110%;"></div><br>
    <div id="price" style="font-weight:bold; font-size:110%;"></div>
    <div id="brand" style="font-weight:bold; font-size:110%;"></div>
    </div>
    </span>
    <form action="payment.php" method="POST" align="right">
    <input type="submit" name="productad" value="Continue">
    </form>
    </body>
    </html>

Open in new window

sanchit guptaAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Terry WoodsIT GuruCommented:
In the insert query, you've got the column names as PHP variables eg $nameInput... is that correct? If so, then the variables should contain database column names.
0
Terry WoodsIT GuruCommented:
Array values in the insert query should also be wrapped in curly braces:

    $insert = 
"INSERT INTO productad ($nameInput, $descInput, $price, $brand)  
VALUES (
'{$_POST['nameInput']}',
'{$_POST['descInput']}',
'{$_POST['priceInput']}',
'{$_POST['brandInput']}'
)";

Open in new window


Really you should also be sanitising your database inputs, or a single quote will not only cause queries to break, but it also opens your database to being hacked. Put each value through the mysql_real_escape_string function to do that.
0
Chris StanyonWebDevCommented:
Unfortunately, the code you currently have is a disaster waiting to happen. Firstly, you should NEVER pass user data directly to your DB. Secondly, the MySQL extensions in PHP are deprecated, so you should use the newer mysqli or PDO. There's also a couple of logic errors in there.

Here's a general look at doing it with mySQLi. Have a look and see if it makes sense.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_STRICT);
 
// Connect to your DB
try {
     $db = new mysqli('hostName', 'userName', 'password', 'yourDb');
} catch (Exception $e ) {
     echo "DB Error: " . $e->getMessage();
     exit;
}


// Do we have a Form Submission
if (isset($_POST['productad'])) {

    // Check that all your fields have values
    if (
        (!isset($_POST['nameInput']) || empty($_POST['nameInput'])) ||
        (!isset($_POST['descInput']) || empty($_POST['descInput'])) ||
        (!isset($_POST['priceInput']) || empty($_POST['priceInput'])) ||
        (!isset($_POST['brandInput']) || empty($_POST['brandInput']))
    ) {
        die("Your fields are empty");
    }        

    // Prepare your Query and bind the parameters
    $stmt = $db->prepare("INSERT INTO productad (name, description, price, brand)  VALUES (?, ?, ?, ?)";
    $stmt->bind_param("ssss", $_POST['nameInput'], $_POST['descInput'], $_POST['priceInput'], $_POST['brandInput']);

    // Execute your query
    try {
        $stmt->execute();
        echo "Your record was created.";
    } catch (Exception $e) {
        echo "There was a problem!";
        echo $e->getMessage();            
    }
}

Open in new window

1
IT Pros Agree: AI and Machine Learning Key

We’d all like to think our company’s data is well protected, but when you ask IT professionals they admit the data probably is not as safe as it could be.

sanchit guptaAuthor Commented:
@chrisstayon could you please provide me with full code for my question with mysqli as i am not familiar with this..
0
Chris StanyonWebDevCommented:
Sure Sanchit.

Have a read through this, and ask if there's anything you don't understand:

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Connect to your DB
try {
     $db = new mysqli('localhost', 'username', 'password', 'database');
} catch (Exception $e ) {
     echo "DB Error: " . $e->getMessage();
     exit;
}

?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Chris Stanyon | EE [Q:28980074]</title>
        <style type="text/css">
            label { display: block; width: 150px; }
            div { margin-bottom: 10px; }
            .msg { font-weight: bold; }
            .success { color: #00aa00; }
            .error { color: #aa0000; }
        </style> 

    </head>

    <body>

        <?php
        // Do we have a Form Submission
        if (isset($_POST['submit'])) {

            try {
                // Check that all your fields have values
                if (
                    (!isset($_POST['name']) || empty($_POST['name'])) ||
                    (!isset($_POST['desc']) || empty($_POST['desc'])) ||
                    (!isset($_POST['price']) || empty($_POST['price'])) ||
                    (!isset($_POST['brand']) || empty($_POST['brand']))
                ) {
                    throw new Exception('Some of your fields are empty.');;
                }        

                // Prepare your Query and bind the parameters to the POST array
                $stmt = $db->prepare("INSERT INTO yourTable (name, description, price, brand)  VALUES (?, ?, ?, ?)");
                $stmt->bind_param("ssss", $_POST['name'], $_POST['desc'], $_POST['price'], $_POST['brand']);

                // Execute your query
                $stmt->execute();

                // Success!
                printf("<p class='msg success'>%s</p>", "Your record was created.");

            } catch (Exception $e) {

                // There was a problem
                printf("<p class='msg error'>%s</p>", $e->getMessage());            

            }
        }
        ?>

        <form method="post">
            <div>
                <label for="name">Name</label>
                <input type="text" name="name" id="name">
            </div>

            <div>
                <label for="desc">Description</label>
                <input type="text" name="desc" id="desc">
            </div>

            <div>
                <label for="price">Price</label>
                <input type="text" name="price" id="price">
            </div>

            <div>
                <label for="brand">Brand</label>
                <input type="text" name="brand" id="brand">
            </div>

            <div>
                <input type="submit" name="submit" value="Submit">
            </div>
        </form>

    </body>

</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sanchit guptaAuthor Commented:
@chrisstanyon thanks for the code but there is nowhere you put my script in the code..which was an essential part.
0
sanchit guptaAuthor Commented:
@chrisstanyon thanks for the code but there is nowhere you put my script in the code..which was an essential part.
0
Chris StanyonWebDevCommented:
Hey Sanchit,

The code I've provided isn't a finished product - it's just the HTML and the SQL which is ehat you asked about. Can you not just drop your scripts back in and update the HTML as needed?
0
sanchit guptaAuthor Commented:
fine thanks
i have included the scripts and "preview" goes fine but the "Product image" in my original code does not
comes in the "Preview".

do you have any idea abut that?
0
Chris StanyonWebDevCommented:
Not without seeing the code :)
1
sanchit guptaAuthor Commented:
Chris i did that by myself! :)

just wanted to know how can i save that image to database..like its path or it in any other way?
0
Chris StanyonWebDevCommented:
Generally, it always make sense to save the Image to your server, and then save the path to that image to your database.

Firstly, you'd need to change your <form> tags so the file gets sent:

<form method="post" enctype="multipart/form-data">

Then you need to add a <file> input to your form:

<input type="file" name="fileToUpload" id="fileToUpload">

Now, when your form is submitted, you will need to run any security/logic checks  (is it a jpg / what's the filesize etc.), before moving the file to it's final destination on your server (/uploads for example). The file sent along with the form can be accessed with this variable:

$_FILES["fileToUpload"]["name"]

Once you've done your checks and moved the file, you will have to store the name in a variable if you haven't already ($imageName for example).

Then, update the SQL Query to INSERT the filename into the DB along with all your other data:

$stmt = $db->prepare("INSERT INTO yourTable (name, description, price, brand, image)  VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $_POST['name'], $_POST['desc'], $_POST['price'], $_POST['brand'], $imageName);
1
Ray PaseurCommented:
Here's why and how to get off the MySQL extension.  Seriously, you need to do this right now.  There is no currently supported version of PHP that has not deprecated MySQL.  The extension is completely gone in the most current versions of PHP.
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

If you're new to PHP and want to learn the language, this article can help.  Just skip over any of the parts you already know from your experience in other programming languages.  The article gives links to structured learning resources, which will serve you much, much better than copy/paste learning!
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
0
Ray PaseurCommented:
@Chris: Just a sidebar note...  I believe that empty() covers all of the conditions included in !isset().  You might save a few keystrokes because you can omit the test for not-isset().  Loosely-typed comparison rules apply.

;-)

Cheers, ~Ray
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server

From novice to tech pro — start learning today.