Solved

Error inserting data into mysql database

Posted on 2016-10-31
16
39 Views
Last Modified: 2016-11-21
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

0
Comment
Question by:sanchit gupta
  • 5
  • 5
  • 2
  • +1
16 Comments
 
LVL 35

Expert Comment

by:Terry Woods
Comment Utility
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
 
LVL 35

Expert Comment

by:Terry Woods
Comment Utility
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
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
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

0
 

Author Comment

by:sanchit gupta
Comment Utility
@chrisstayon could you please provide me with full code for my question with mysqli as i am not familiar with this..
0
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 400 total points (awarded by participants)
Comment Utility
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
 

Author Comment

by:sanchit gupta
Comment Utility
@chrisstanyon thanks for the code but there is nowhere you put my script in the code..which was an essential part.
0
 

Author Comment

by:sanchit gupta
Comment Utility
@chrisstanyon thanks for the code but there is nowhere you put my script in the code..which was an essential part.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
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
 

Author Comment

by:sanchit gupta
Comment Utility
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
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
Not without seeing the code :)
0
 

Author Comment

by:sanchit gupta
Comment Utility
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
 
LVL 42

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 400 total points (awarded by participants)
Comment Utility
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);
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 100 total points (awarded by participants)
Comment Utility
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
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
@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

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Creating and Managing Databases with phpMyAdmin in cPanel.
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now