PDA

View Full Version : PHP/SQL Question.


DeathsRHM
07-21-2008, 02:01 PM
Right, if you are using PHP to enter data into an SQL table, how exactly does it work?

I used this:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");

mysql_close($con);
?>

And it adds the records, but wouldnt it add the same record every time i opened the page? and if I put primary key, wouldnt it come up with an error every time after the first time i opened the page?

An explaination would be helpful, thanks, and if the php code i inserted needs changing, tell me please ;)

_Aerospace_Eng_
07-21-2008, 04:28 PM
You should be doing some error checking.
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$sql = "INSERT INTO person(FirstName, LastName, Age) VALUES('Peter', 'Griffin', '35')";
$result = mysql_query($sql, $con) or die(mysql_error());

$sql = "INSERT INTO person(FirstName, LastName, Age) VALUES('Glenn', 'Quagmire', '33')");
$result = mysql_query($sql, $con) or die(mysql_error());

mysql_close($con);
?>
Yes each time you load the page those two queries will run inserting the same record. It won't throw an error if you primary key isn't the firstname, lastname, or age. Currently your primary key is probably an auto increment id in which case they won't ever be the same so no error is given.

If you wanted it so the same firstname and lastname couldn't be inserted into the database then make those unique and use INSERT IGNORE instead as this won't put in duplicate values.