Solved

Error inserting data into mysql database

Posted on 2016-10-31
16
60 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
ID: 41867589
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
ID: 41867594
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 43

Expert Comment

by:Chris Stanyon
ID: 41867637
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
Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

 

Author Comment

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

Accepted Solution

by:
Chris Stanyon earned 400 total points (awarded by participants)
ID: 41868142
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
ID: 41870405
@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
ID: 41870406
@chrisstanyon thanks for the code but there is nowhere you put my script in the code..which was an essential part.
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41870425
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
ID: 41870570
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 43

Expert Comment

by:Chris Stanyon
ID: 41870593
Not without seeing the code :)
1
 

Author Comment

by:sanchit gupta
ID: 41870616
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 43

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 400 total points (awarded by participants)
ID: 41870646
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
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 100 total points (awarded by participants)
ID: 41871224
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 109

Expert Comment

by:Ray Paseur
ID: 41871238
@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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
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.

840 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