#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    24
    Rep Power
    0

    Error Message For Duplicate Entry


    This is my first post and I have only been working with PHP for a month now. My professor doesn't even know PHP too well, he used COBOL back in the 70s for banks he worked at and the college asked him to teach PHP a couple years ago and he took it on but doesn't have the best concepts of teaching to us. This brings me to my question. I know to have a UNIQUE key in the MySQL db and this prevents duplicates, however he has asked us to come up with a way to not allow duplicates and to have an error message pop up telling the user the product code already exists. We have been trying for over a week, no one has figured it out. He said he thinks it has to do with the version of PHP we are using as well as the structure of the DB. I have gotten really close with some code I've found on the forums here and I really want to figure this out. It's super frustrating. I will attach the code so you guys can check it out, it's simple stuff but like I said I've been doing it for a month and have a professor who doesn't know it well.

    THIS IF FROM THE ADD_PRODUCT form which is where I initially tried to us an if (error 1062) statement but nothing worked.

    <?php
    // Get the product data
    $category_id = $_POST['category_id'];
    $code = $_POST['code'];
    $name = $_POST['name'];
    $price = $_POST['price'];

    // Validate inputs
    if (empty($code) || empty($name) || empty($price) ) {
    $error = "Invalid product data. Check all fields and try again.";
    include('error.php');
    } else {
    // If valid, add the product to the database
    require_once('database.php');
    $query = "INSERT INTO products
    (categoryID, productCode, productName, listPrice)
    VALUES
    ('$category_id', '$code', '$name', '$price')";
    $db->exec($query);

    // Display the Product List page
    include('index.php');
    }
    ?>

    I think this is all you need to tell me where to put an error code but if it's not I apologize for my ignorance. I really like PHP but I'm struggling due to the way I'm being taught.
  2. #2
  3. Jealous Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,303
    Rep Power
    9400
    Do a SELECT to see if there's matching data first, and if you don't find it then do the INSERT.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    24
    Rep Power
    0
    I need a little more detail if anyone can help. I still don't understand what exactly I need to code in order to display an error message. Again, sorry for the ignorance but PHP is still new to me. I just need for an error message to display either a new form or a messagebox (whichever is simplest) when duplicate entries are entered.
  6. #4
  7. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6352
    Do an INSERT IGNORE (just add IGNORE after the INSERT).

    After the query, check the affected rows (there must be a function for it on the $db object, it's a standard query). If it's 0, there was already a row in there, so it's a duplicate. If it's 1, the row was inserted successfully.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    24
    Rep Power
    0
    Will that display an error?
  10. #6
  11. Jealous Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,303
    Rep Power
    9400
    Originally Posted by bradmartin0924
    I still don't understand what exactly I need to code in order to display an error message.
    What about the code you already have in place?
    PHP Code:
    if (empty($code) || empty($name) || empty($price) ) {
    $error "Invalid product data. Check all fields and try again.";
    include(
    'error.php'); 
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    24
    Rep Power
    0
    that displays error message properly for missing data, but I need an error to display when a duplicate $code is entered. I just tried
    Code:
    if ( mysql_errno() == 1022) 
        { 
    		$error2 = "Product code already exists.";
    		include('error2.php'); 
        } 	else
    However, it's not working properly. I also tried to
    Code:
    echo "Product already exists."
    but it would just return a blank screen.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    24
    Rep Power
    0
    This is what I currently have. The error for missing data works properly, but the mysql error 1022 does not echo duplicate data.

    [PHPNET]<?php
    // Get the product data
    $category_id = $_POST['category_id'];
    $code = $_POST['code'];
    $name = $_POST['name'];
    $price = $_POST['price'];

    // Validate inputs
    if (empty($code) || empty($name) || empty($price) ) {
    $error = "Invalid product data. Check all fields and try again.";
    include('error.php');
    } else {
    if (mysql_errno() == 1022 ) {
    echo "Product code already exists.";
    } else {

    // If valid, add the product to the database
    require_once('database.php');
    $query = "INSERT INTO products
    (categoryID, productCode, productName, listPrice)
    VALUES
    ('$category_id', '$code', '$name', '$price')";

    $db->exec($query);

    // Display the Product List page
    include('index.php');
    }
    }
    ?>[/PHPNET]
  16. #9
  17. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6352
    You can't mix whatever database tech you're using with standard mysql features, for all you know $db uses mysqli or PDO. You have to find out how to get $db to give you back error codes (or number of affected rows if you want to use my solution)
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  18. #10
  19. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,316
    Rep Power
    7171
    If you post the code for database.php it would probably make it possible to answer your question. PDO has an exec method, so there's a pretty strong chance that that's what you're using.

    The code you have is probably pretty close, although with two issues; first as ManiacDan mentioned you can't mix database libraries, and second the error wouldn't be returned until after your query is run.

    PHP Code:
    <?PHP
        
    require_once('database.php');

        
    // If valid, add the product to the database
        
    $query "INSERT INTO products
        (categoryID, productCode, productName, listPrice)
        VALUES
        ('
    $category_id', '$code', '$name', '$price')";

        
    $db->exec($query);
        
        
    $err $db->errorInfo();
        if(!empty(
    $err[1]) && $err[1] === 1022) {
            echo 
    "Product code already exists.";
        } else {
            
    // Display the Product List page
            
    include('index.php');
        }
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    24
    Rep Power
    0
    Here is the database.php file. I have worked on this for over 8 hours the past two days, researching and trying everything I come across and I just can't nail it. I know it has to be simple but I don't have such a good grip on PHP yet. Thanks for the replies and help guys.

    PHP Code:
    <?php
        $dsn 
    'mysql:host=localhost;dbname=my_guitar_shop1';
        
    $username 'mgs_user';
        
    $password 'pa55word';

        try {
            
    $db = new PDO($dsn$username$password);
        } catch (
    PDOException $e) {
            
    $error_message $e->getMessage();
            include(
    'database_error.php');
            exit();
        }
    ?>
  22. #12
  23. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6352
    Change your password right now, you've posted it in public.

    As Oreo and I suspected, you're using PDO, not the mysql library. You can't mix and match, you need to use the PDO functions to fetch the error codes or affected rows.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    24
    Rep Power
    0
    this is all based off a textbook's database files, downloaded from the books website so I'm not concerned about the password. We use XAMPP. This isn't personal use of anything I own. I'm just working through the exercises and our professor assigned this to us, when he doesn't even know how to get it to work. He was writing logic on the board the other day about error trapping and he kept trying and trying and he assigned it to us anyhow. With that said, we have barely even mentioned PDO in class, which makes this even more ridiculous. Thanks for all the help guys, at least now I have something to inform him about. Just to clarify, since it's using PDO, is what I was trying at all possible or would it be possible to do what I want without having to use some PDO function? Just trying to get a better understanding.
  26. #14
  27. No Profile Picture
    Permanently Banned
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    4
    Rep Power
    0
    Originally Posted by ManiacDan
    Change your password right now, you've posted it in public.

    As Oreo and I suspected, you're using PDO, not the mysql library. You can't mix and match, you need to use the PDO functions to fetch the error codes or affected rows.

    I aslo agree with you Maniac... you need to use PDO function for fetching the error codes.
    Last edited by ManiacDan; October 5th, 2012 at 09:18 AM.

IMN logo majestic logo threadwatch logo seochat tools logo