Ashlee
Ashlee

Reputation: 3

PHP: Running mysql_query if data from $_POST matches data in table

I hope my title isn't completely confusing. I'd like to start by saying I am in now way a programmer and am an amateur with PHP and MySQL, which I use for online gaming. I have been tirelessly working at this for a few days, with no success. I've been toying with the idea of asking for help here, hoping folks go easy on me and don't completely rip apart my code! Like I said, I'm an amateur.

Basically, what I'm trying to do is match the $horsename data from my $_POST array with name in my table called horses. If they do not match it will add a horse with that name into the horses table. If they do match, it will simply continue on and add the data from the $_POST array into the results table for each line.

The issue I'm getting, (and I've toyed with this multiple times, with a different issue arising each time) is even if the $horsename matches name in the horses table, it tries to add a new horse into the horses table. It also is not moving onto the next line of data and will try to add the same horse over and over again. (Hope that makes sense!)

I'm pasting most of my code from this page below, just in case it's something earlier in my code causing this issue. Please note, a portion of this code is not my own and I am working on it for someone else, so if things are not completely uniform in a couple of spots, that is why. The portion I'm working on is what I've mentioned above.

function stripslashes_deep($value) {
    $value = is_array($value) ?
        array_map('stripslashes_deep', $value) :
        stripslashes($value);
    return $value;
}

$results = str_replace("\r", '', trim($_POST['news'])); 
$data = array();
$lines = explode("\n", $results);
foreach ($lines as $place) {

    if (!empty($place)) {
        $data = array();
        $detail = explode(",", $place);
        if (!empty($detail)) {               
            $id = '';
            $show = $_POST['show'];
            $year = $_POST['year'];
            $association = $_POST['association'];
            $chpoints = $_POST['chpoints'];
            $rchpoints = $_POST['rchpoints'];
            $ttpoints = $_POST['ttpoints'];
            $chearnings = $_POST['chearnings'];
            $rchearnings = $_POST['rchearnings'];
            $ttearnings = $_POST['ttearnings'];
            $horsename = stripslashes(trim($detail[0]));
            $placement = stripslashes(trim($detail[1]));
            $class = stripslashes(trim($detail[2]));

            if($placement === 'CH'){
                $points = $chpoints;
            }
            else if ($placement === 'RCH') {
                $points = $rchpoints;
            }
            else {
                $points = $ttpoints;
            }
            if ($placement === 'CH') {
                $earnings = $chearnings;
            }
            else if ($placement === 'RCH') {
                $earnings = $rchearnings;
            }
            else {
                $earnings = $ttearnings;
            }

            $horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
            while($row = mysql_fetch_array($horses)) {

                $storedname = addslashes(trim($row['name']));

                if ($storedname == $horsename) {
                    echo "The names do match for $horsename";
                } 
                else {
                    echo "The names do not match for $horsename";
                    $addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
                                        VALUES ('','25','$horsename','','','','','','','','','')";
                    mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
                    echo 'Added '. $horsename .' to Archive.';
                }
            }

            if (isset($_POST['news'])) {
                $query="INSERT INTO `results` (`id`, `show`, `year`, `place`, `name`, `class`, `points`)
                                        VALUES ('$id','$show','$year','$placement','$horsename','$class','$points')";
                mysql_query($query) or die ('Error updating database: ' . mysql_error());
                echo "Result successfully added!" ;
            }


        }; 
    };
};

To take a snip-it from above, this is the place I'm having the issues:

$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
while($row = mysql_fetch_array($horses)) {

    $storedname = addslashes(trim($row['name']));

    if ($storedname == $horsename) {
        echo "The names do match for $horsename";
    } 
    else {
        echo "The names do not match for $horsename";
        $addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
                                        VALUES ('','25','$horsename','','','','','','','','','')";
        mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
        echo 'Added '. $horsename .' to Archive.';
    }
}

If anything from the page where news is coming from is needed, please let me know. Thanks in advance!

Upvotes: 0

Views: 746

Answers (2)

Anid Monsur
Anid Monsur

Reputation: 4538

The problem is that you are querying the database for a list of every horse name. You're iterating through that list and each time the names don't match, you're inserting the new name. What you need to do instead is to query for the specific name.

SELECT * FROM horses WHERE name = '$horsename'

If this returns a row, then you know the horse is already in the database. If it returns no rows, then you can safely insert once. By the way, you'll want to properly escape your input to prevent SQL injections so don't use my code verbatim.

Upvotes: 2

wipindipy10
wipindipy10

Reputation: 150

Try this:

    $horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
    $i = 0;
    $horsename = "";

    while($row = mysql_fetch_array($horses)) {

        $storedname = addslashes(trim($row['name']));

        if ($storedname == $horsename) {
            $i = 1;
        }
    }

    if($i == 1) {
        echo "The names do match for $horsename";
    }
    else {
        echo "The names do not match for $horsename";
        $addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
            VALUES ('','25','$horsename','','','','','','','','','')";
            mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
         echo 'Added '. $horsename .' to Archive.';
    }

Upvotes: 0

Related Questions