Jump to content

PHP mysql query (Pulling my hair out)


iceblade

Recommended Posts

Hi all,

 

I'm just in the early stages of learning PHP so go easy on me. :-)

 

I've been searching the net for the last 3 days with no solution.

 

I've setup a HTML page which feeds the $_POST information to this PHP file.

 

The $userid is taken from the login page, but the problem I'm having is that I can't figure out how to check a table

 

too see if the $_POST[item] already exists.

 

 

 

MySQL table is setup as follows:

 

Items

 

________________________

 

|Line |  userid  | Item |

 

________________________

 

|001  |  John    |  1  |

 

|002  |  tom    |  1  |

 

|003  |  tom    |  2  |

 

|004  |  tom    |  3  |

 

|005  |  John    |  2  |

 

________________________

 

 

 

The Line field on the above table is the unique number field for the table to keep track of the number of entries.

 

 

 

Can someone please fix the script below so $_POST[item] checks to see if item already exists in the column for the specified userid.

 

 

 

Thank you.

 

 

 

 

 

 

 

<?php

 

include "config.php";

 

$userid = $_SESSION['userid'];

 

 

 

$sql="INSERT INTO List (UserID,Item)

 

VALUES

 

      ('$userid','$_POST[item]')";

 

 

 

if ( $userid == 'tom' and $_POST[item] == 'in the column' )

 

  {

 

            echo "Item $_POST[item] already exists!\n<br>

 

  }

 

 

 

elseif (!mysql_query($sql))

 

 

 

  {

 

        die('Error: ' . mysql_error());

 

  }

 

 

 

        echo "Item $_POST[Tank] has been added Successfully!\n<br>

 

 

 

mysql_close("Connect_mySQL.php")

 

?>

Link to comment
https://forums.phpfreaks.com/topic/168778-php-mysql-query-pulling-my-hair-out/
Share on other sites

What do you want to happen if the item already exists?

 

A few things that I found:

 

It would be helpful if you could post clean code. There are many semi-colons and quotes missing, indentation and extra lines make it hard to read.

 

Put

 tags around the code.

Correct syntax for arrays is like this: $array['key'], except when it occurs inside double quotes like in an echo. Read the  [url=http://php.net/arrays]array do's and don'ts[/url] for further clarification

Here is a clean version of your code:

[code=php:0]include "config.php";
$userid = $_SESSION['userid'];

$sql = "INSERT INTO List (UserID,Item)";
$sql .= " VALUES('$userid','$_POST[item]')";

if ($userid == 'tom' and $_POST['item'] == 'in the column') {
echo "Item $_POST[item] already exists!\n<br />";
} elseif (!mysql_query($sql)) {
trigger_error('Error: ' . mysql_error(),E_USER_ERROR);
}

echo "Item $_POST[Tank] has been added Successfully!\n<br />";
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.