Jump to content

help with PHP mySQL code with INSERT function


jcjst21

Recommended Posts

Hello,

 

I am writing some code that inserts a value into a table and then displays it further down the page; what I am running into is when I click the link that goes to the page; an empty record is being inserted into the table when I arrive at the page and after I leave it.

 

HEre is my code; at first I placed the INSERT statement in the <head> of the html page and then I moved it into the body thinking it's executing when the page loads, but the same behavior occurs with the code in the <body> as well.

 

<html>
<head>
<link rel="stylesheet" type="text/css" href="xxxx.css" />



</script>
<title>
</title>
<?php



echo $allergy;

$con=mysql_connect("xxxx", "xxx", "xxxx") or die ("cannot connect");
mysql_select_db("testcamp") or die ("cannot select database");

$allergy=$_POST['addAllergy'];
$sql="INSERT INTO Allergies(allergyNameID)
VALUES
('$_POST[addAllergy]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }


$result = mysql_query("SELECT * FROM Allergies");
?>






</head>
<body >

<div class="panel" id="panel">

<form method="POST" action="addAllergies.php" name="addAllergies">

<table cols="2">
	<tr>
		<td colspan="2">Add An Allergy:</td>
	</tr>
	<tr>
		<td colspan="2"><input type="text" size="25" name="addAllergy" /></td>
	</tr>
	<tr>
		<td align="center"><input type="submit" name="add" value="Add" /></td></tr>
</table>
</form>
<br />
<br />



<div id="allergyWall">
<?php
while($row = mysql_fetch_array($result))
  {
  echo $row['allergyNameID'];
  echo "<br />";
  }
  
  mysql_close($con);
?></div>
<div align="center">
<a href="xxxx.php">Return to Admin Menu</a></div>
</body>
</html>

Try using an if statement that checks if data has been sent, to be put into the data.

 

if(isset($_POST['add']))
{
         //code that enters entry into the database
}

 

edit: That code makes sure the "add" submit button was pressed. Though, refreshing the page after adding a valid entry will produce duplicate entries. That is a whole 'nother problem, that I have yet to find the answer to though.

No, not really. All of the form processing logic should be completed before anything is sent to the browser. You can't think of php code as being "in" the html markup like that.

 

<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
     //process form data
}
?>
<html>
<head> . . . 

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.