i am trying to create a form and in that form have a selection list in which the options are automatically populated with data from a database (namely customer's last names), after which when the last name is chosen from the list and the submit button is hit the "customer ID" that is related to that last name in the database will be submitted to another PHP file (task8.php) to be sent through further queries. I hope i have explained that all in an understandable manner. I have had a go at some code but i am really unsure on how to do this or if what i have written is on the right path.
Here is what i have written so far:
<body>
<?php
$conn = mysql_connect("localhost", "twa312", "dam6av9a");
mysql_select_db("warehouse312", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "select customerID, lastName from customer";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
$options= '<option value="0">Choose</option>';
while ($row=mysql_fetch_array($rs)) {
$id=$row["customerID"];
$name=$row["lastName"];
$options="<OPTION VALUE='" . $id . "'>" . $name ."</option>";
}
?>
<form method="GET" action="task8.php" id="custinfo" >
Choose name:<select name="lname" id="lname"><?php echo $options; ?>
</select>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
What i am trying to do with the code is access the table "customer" and fields "customerID" and "lastName". Using the customer's last name as the option and the customer's ID as the options value in the selection list. Currently the code displays only a single name as an option in the selection list when it should display all the names in the database. Any help on this would be really great as i am fairly unsure.
There is an error in the code that I can see would cause PHP to generate notice error.
In the while loop you're using .= on the $options variable that isn't yet defined so PHP will barf on that.
Aside from that, it doesn't make sense to me that you're waiting for $_GET['submit'] to be set before iterating over the result set from mysql. As far as I can tell, the first time you'd hit this page there would be a single option in the select ("Choose"), and since the form submits to a different page I don't think you'd ever see a list of customer last names.
Finally, it's not really recommended to name your submit buttons 'submit', since when the page is parsed by the browser all the form elements of a specific form are created as attributes of that form, JS form objects have a 'submit' method so when you name an input 'submit' you clobber that value in the form object which makes it really hard to submit that form with JS.
First off move away from the mysql_functions.
Secondly create a model with all querys related to your customers that will handle fetching/puttin/updating the data related to your customer db.
<?php
Class CustomerModel{
private $db;
function __construct($host,$dbname,$user,$pass){
$this->dbhost = $host;
$this->dbname = $dbname;
$this->dbuser = $user;
$this->dbpass = $pass;
}
private function connect(){
if (!$this->db instanceof PDO){
$this->db = new PDO('mysql:dbname='.$this->dbname.';host='.$this->dbhost, $this->dbuser, $this->dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}
}
public function select_all_customer($cols="*"){
$this->connect();
$sql = "SELECT $cols FROM customer";
$statement = $this->db->prepare($sql);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
public function select_customer($cols="*",$where=null, $id=null){
$this->connect();
$sql = "SELECT $cols FROM customer WHERE $where = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
}
?>
Now you can access the model like:
<form method="POST" action="task8.php" id="custinfo" >
Choose name:
<select name="customerID" id="customerID">
<option value="0">Choose</option>
<?php foreach($customer->select_all_customer("customerID, lastName") as $row): ?>
<option value="<?php echo $row['customerID']?>"><?php echo $row['lastName']?></option>
<?php endforeach; ?>
</select>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
<?php
//Get customer from form values
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['customerID'])){
$result = $customer->select_customer("*", "customerID", $_POST['customerID']);
//Do something with result
echo '<pre>'.print_r($result, true).'</pre>';
}
?>
Hope it helps
Related
I am posting a shortened version of the form and updating lines. I will truly appreciate any help. I have spent the last 48 hours trying all I could think of and it's driving me insane. If I remove the line if($_SERVER["REQUEST_METHOD"]=="POST"), the program runs on loading the page and does update the table at the ID in the url with a blank field. Thanks in advance. Here's the code:
<?php
$id = $_GET['id'];
$user = $_SESSION['user'];
Echo '<form action="editone.php" method="POST">
Enter new name:<input type="text" name="namex" />
<input type="submit" name="Submit" value="Update List" /> </form>';
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $id);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I think your form action didn't pass id.
<form action="editone.php" method="POST">
If you're using this single file as form editor and action, your form editor URL should be http://localhost/editone.php?id=1
Try to change your form action to
<form action="editone.php?id='.$_GET['id'].'" method="POST">
or just leave the action blank
<form action="" method="POST">
Ok - maybe I'm way off base here but I see the following problems.
1) Your method is POST however your id is coming from GET.
2) I don't see where the id is coming from. It could be coming from somewhere and not posted but I don't see it.
Have you checked to verify the value is actually being passed through to the php?
try this
echo "GET = " . var_dump($_GET);
echo "<br><br>";
echo "POST = " . var_dump($_POST);
exit();
Post the results and then post where the id is coming from if you can't figure it out still. :)
Use the below code:
$query = "SELECT now_edit, FROM EDITORIES WHERE edit_id='$numb' LIMIT 1";
I assume your page is being called initially from an anchor link on another page which is why you are getting the id from $_GET['id'].
When the user presses the submit button of course the form is being submitted as a POST so all the data will be in $_POST, therefore $_GET['id'] will fail and should be generating an error message.
You need to save the $_GET['id'] from the first instantiation so you can use it when the form is posted to you. So put it in a hidden field that will be posted to you with the post
<?php
session_start();
$user = $_SESSION['user'];
if($_SERVER["REQUEST_METHOD"]=="GET") {
if ( isset($_GET['id']) ) {
$id = $_GET['id']);
} else {
// no param passed, could be a hack
header('Location: some_error_page.php');
exit;
}
echo '<form action="editone.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo 'Enter new name:<input type="text" name="namex" />';
echo '<input type="submit" name="Submit" value="Update List" /></form>';
}
if($_SERVER["REQUEST_METHOD"]=="POST") {
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $_POST['id']);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I've got a PHP class, and I'd like to create instances I can update later from the data that I pull from the database. Here's what I've got so far:
<?php
$servername = "localhost";
$username = "super";
$password = "cala";
$database = "fraga";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$getTableQuery = "SELECT ani.Id, ani.Name, ani.Size, ani.Color, tbs.Name as Species, tbs.Description
FROM animals as ani INNER JOIN
animalTypes as tbs ON ani.Species = tbs.Id
ORDER BY ani.Id";
$table = $conn->query($getTableQuery);
$pageLoaded = false;
if(isset($_POST['btnInsert']) && ($_POST['txtName'] != "")){
$pageLoaded = true;
}
if ($table->num_rows > 0) {
echo "<table border='1'><tr><th>Name</th><th>Size</th><th>Color</th><th>Species</th></tr>";
// output data of each row
while($row = $table->fetch_assoc()) {
echo "<tr><td>".$row["Name"]."</td><td>".$row["Size"]."</td><td>".$row["Color"]."</td><td>".$row["Species"]."</td></tr>";
$fish[] = $row;
}
echo "</table>";
echo "</br>";
} else {
echo "0 results";
}
if(isset($_POST['btnInsert']) && ($_POST['btnInsert'] == "Insert") && $pageLoaded == true)
{
$Animal = new Animal($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txtSpecies'], $_POST['txtDescription']);
$Animal->InsertAnimal($conn);
}else if(isset($_POST['btnSave']) && ($_POST['btnSave'] == "Save") && $pageLoaded == true){
$Animal->UpdateAnimal($Animal);
}
class Animal
{
private $name = "Animal Name";
private $size = 0;
private $color = "255:255:255";
private $speciesName = "Species Name";
private $speciesDescription = "Species Description";
public function Animal($name, $size, $color, $species, $description){
$this->name = $name;
$this->size = $size;
$this->color = $color;
$this->speciesName = $species;
$this->speciesDescription = $description;
}
private function ColorCheck($color){
if($color >= 256 || $color <= 0)
return false;
else
return true;
}
public function InsertAnimal($conn, $pageLoaded){
$this->speciesName = mysqli_real_escape_string($conn, $this->speciesName);
$this->speciesDescription = mysqli_real_escape_string($conn, $this->speciesName);
$this->name = mysqli_real_escape_string($conn, $this->name);
$this->size = mysqli_real_escape_string($conn, $this->size);
$this->color = mysqli_real_escape_string($conn, $this->color);
$speciesId = "SELECT Id from animalTypes WHERE Name = '$this->speciesDescription'";
$speciesInsert = "INSERT IGNORE INTO animalTypes (Name, Description)
VALUES ('$this->speciesName', '$this->speciesDescription')";
$result = mysqli_query($conn, $speciesInsert) or die("Query fail: " . mysqli_error($conn));
if($id = $conn->query($speciesId)){
$row = $id->fetch_assoc();
$intId = $row['Id'];
}
$AnimalInsert = "INSERT INTO animals (Name, Size, Color, Species)
VALUES ('$this->name', $this->size, '$this->color', $intId)";
$result2 = mysqli_query($conn, $AnimalInsert) or die("Query fail: " . mysqli_error($conn));
echo '<script type="text/javascript">window.location = window.location.href;</script>';
$_POST['txtName'] = "";
}
public function UpdateAnimal($animal, $conn){
$speciesCheck = "SELECT * FROM animalTypes WHERE Name = '$this->speciesName";
$speciesList = mysqli_query($conn, $speciesCheck) or die("Query fail: " . mysqli_error($conn));
$updateQuery = "UPDATE animals";
}
}
$conn->close();
?>
<body>
<form action="index.php" method="post">
Animal Name:<br />
<input name="txtName" type="text" /><br />
<br />
Size:<br />
<input name="txtSize" type="text" /><br />
<br />
Color:<br />
<input name="txtColor" type="text" /><br />
<br />
Species Name:<br />
<input name="txtSpecies" type="text" /><br />
<br />
Species Description:<br />
<input name="txtDescription" style="width: 419px; height: 125px" type="text" /><br />
<br />
<input name="btnInsert" type="submit" value="Insert" />
<input name="btnSave" type="submit" value="Save" />
</form>
</body>
Now, what I'd like to do is create instances of Animal from the data that loads when the page loads, and store them for update. Problem is, I'm not sure how to do it. I've googled a bit (but my fu is admittedly weak), and saw suggestion for creating an array of Animals and adding them during the while loop. Is that really the best way to do that? And then how could I load the instance back into the text boxes so that I could update them?
First of all you should learn to seperate the concerns in your code correctly.
If I started to explain how you should build your script up from scratch, this would take too long, so I will try to give you only a good direction to go. I think this will help you more in your learning process.
So, if I understand correctly, the code you posted is all set up in one file, I guess it's inside you index.php? (missing some information here)
If this is the case...
index.php
Use your index.php for displaying a list of your "Animals" from db, not more. Every list entry will have an edit and delete button/link next to it. On top of your list put a link that's called create.
Now all your index.php does is getting the animals from db and listing them.
Put this part of your code in another file, called dbconfig.php
$servername = "localhost";
$username = "super";
$password = "cala";
$database = "fraga";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
include it on top of your index.php, before you start scripting the index.php
include 'dbconfig.php'
now you can use your $conn variable inside you index.php. We put this into another file and included it, because we're going to reuse this part in the next steps.
I won't write your whole code here for index.php, I think you'll master that. Maybe you ask yourself what your create, edit, delete links should do.
The create link point to a create.php, a simple html link.
The edit link, you will have to render an html link to edit.php?id=IDOfYourAnimalInsideDB
The delete link looks like the edit one, put a link to delete.php?id=IDOfYourAnimalInsideDB.
So where I wrote "IDOfYourAnimalInsideDB" you have to output the actual id, this will be done in your while loop.
create.php
first of all, include the dbconfig.php again here, so you can use your $conn variable which has the db connection.
check if the request has some of your post variables, if true, build an instance of animal and write it to db.
outside the if you build your form. So it doesn't matter if it's post or not, you will show the create form.
delete.php
Again the dbconfig.php include first.
Then you want to check if $_GET['id'] is set and maybe if it's bigger than 0 and if its an integer value. If so, execute your delete sql to the db.
update.php
Again the dbconfig.php include first.
Then you want to check your GET Parameter again and build an sql request to get your specific database entry.
Output a form that already contains your values from db. If a post request comes, you create a new Animal instance, fill it with your data from $_POST and then use it for updating your db.
getters in Animal Class
add getter functions to you animal class, so you can access the private properties from outside. you should write you create, update, delete logic inside the create.php, update.php, delete.php or in another class which you use for database manipulation. There you want to get access to properties for example in order to build up your update sql.
So make a getter method for every property of your "Animal" model class
public function getName() {
return $this->name;
}
so from outside you can get your animals name like so
$animalName = $animal->getName();
more specific?
If you need something more specific, you should specify a little bit more your question. What I described is just a way that splits your script into parts you can understand and maintain better, because stucture and correct seperation of things is one of the most important things in programming.
What I described is far far away from a clean "CRUD" solution, but I think this is a little step for you that you can take now to come closer to a clean solution.
Kind regards
I have a database that users can search by any number of predetermined fields (chosen from a drop down). The problem I'm having is being able to edit existing records. The first script prompts for the record ID to edit. If no record is found the user is told to try again.
When a record is found the results are suppose to display in HTML input boxes. The user can then modify the data, hit submit and the record updates (another script).
Enabled errors. This is what is thrown:
Fatal error: Call to undefined method mysqli_result::fetch__assoc() in (path to script) on line 37
Any ideas on what is wrong?
<?php
//Include everything but the password to connect to db
include 'includes/connect_pw.php';
//User supplies password on previous form
$dbpass = $_POST['password'];
//User supplies id on previous form
$rec_id = $_POST['query'];
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Check connection. If error then kill process, show error and tell user to retry
if ($conn->connect_error) {
die ("<br><br>" . $conn->connect_error . "<p></p>Did you forget the password?");
}
//If no error then set select statement as variable
$sql = "SELECT * FROM dcr_master
WHERE (`ID` = '".$rec_id."')";
//Pass select ($sql) into connection ($conn) with result to ($result)
//Set new variables to populate input boxes. ex: $variable = $row['record field']
$result = $conn->query($sql);
if ($result->num_rows >=1) {
while ($row = $result->fetch__assoc()) {
$Server_Name = $row['Server_Name'];
$Description = $row['Description'];
$IP_Address = $row['IP_Address'];
$Wiki_Link = $row['Wiki_Link'];
}
?>
<form action="modify_dcr_3.php" method="POST">
<input type="hidden" name="ID" value="<?=$rec_id;?>">
Server Name<input type="text" name="Server_Name" value="<?=$Server_Name;?>">
Description<input type="text" name="Description" value="<?=$Description;?>">
IP_Address<input type="text" name="IP_Address" value="<?=$IP_Address;?>">
Wiki_Link<input type="text" name="Wiki_Link" value="<?=$Wiki_Link;?>">
<input type="submit">
</form>
<?php
}
else {
echo "<rb><br>No matching ID found.
<p></p>Try again. Just don't use " .$rec_id. " OK?";
}
?>
You have a double underscore on fetch__assoc(), this should have only a single underscore: fetch_assoc(). Specifically change this:
while ($row = $result->fetch__assoc()) {
...
}
To:
while ($row = $result->fetch_assoc()) {
...
}
I have this function on my php:
function getLastMatchs($nb) {
try
{
$db = new PDO(DBHOST, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
die('connexion failed: '.$e->getMessage());
}
$i=0;
$get5tmatchs = $db->query('SELECT wid, lid, date, cwid, clid FROM `match`');
while ($nb<$i)
{
$data5matchs = $get5tmatchs->fetch();
echo '<tr>
<td>'.$data5matchs['wid'].'</td>';
echo '<td>'.$data5matchs['lid'].'</td>';
echo '<td>'.$data5matchs['cwid'].'</td>';
echo '<td>'.$data5matchs['clid'].'</td>';
echo '<td>'.$data5matchs['date'].'</td>
<br>
</tr>';
$i++;
}
}
And my form is:
echo '<form action="index.php" method="post">
<h3>My question......</h3>
<p>
<input type="text" name="nbmatchs" />
<input type="submit" value="ok" />
</p>
</form>';
echo getLastMatchs('nbmatchs');
How can i do for show nbmatch time the guys want my table ?
When i do now, nothing happen.
Thanks for your help
PS: For exemple i tape 5, i can see 5 time the tabe i have put in my function.
What you indended to accomplish (as far I understood) to allow a visitor enter a numer and then submit it after what some "matches" data it shown. The number visitor entered acts as a limiter.
1. Where do you get your POST variables? You have placed a function below the form with an input value of string 'nbmatchs'. I guess you wanted to submit the form and get the 'nbmatches' value and then apply it to the SQL query for filtering. The way you have done it doesn't work. You have action attribute on your form element set to index.php. That's where we are going to submit the form data. So we need to have a way to get the submitted POST variables. We do it like this:
$nbmatchs = $_POST['nbmatchs'];
Never trust data client has given you. As we know that it must a number let's do a check on it:
$nbmatches = is_numeric(trim($_POST['nbmatchs'])) ? $_POST['nbmatchs'] : 1;
Above we checked if the data client has given really is a number. If it is we'll assign this nubmer to variable $nbmatches. If the data client has given is not a number (eg. some string) we assign number 1 to the variable. At this point we may end the script execution a let the visitor know he must enter a number but we just assign 1 to the variable if anything seems suspicious. After that we can submit this variable to the function getLastMatchs which takes the variable and assigns it to the SQL query as a results limiter. Assuming that all the code will be in one file 'index.php' you should have the following code:
<?php
function getLastMatchs($nbmatches) {
try{
$db = new PDO(DBHOST, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die('connexion failed: '.$e->getMessage());
}
try {
$select = $db->prepare('SELECT wid, lid, date, cwid, clid FROM `match` LIMIT '.$nbmatches.';');
$select->execute();
$results = $select->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $ex) {
echo "<span style='color:red'>".$ex->getMessage()."</span></p>";
}
echo '<table>';
foreach($results as $result){
$output = '<tr>';
$output .= '<td>'.$result['wid'].'</td>';
$output .= '<td>'.$result['lid'].'</td>';
$output .= '<td>'.$result['cwid'].'</td>';
$output .= '<td>'.$result['clid'].'</td>';
$output .= '<td>'.$result['date'].'</td>';
$output = '</tr>';
echo $output;
}
echo '</table>';
}
if(isset($_POST['nbmatchs'])){
$nbmatches = is_numeric(trim($_POST['nbmatchs'])) ? $_POST['nbmatchs'] : 1;
getLastMatchs($nbmatches);
}
?>
<form action="index.php" method="post">
<h3>My question......</h3>
<p>
<input type="text" name="nbmatchs" />
<input type="submit" value="ok" />
</p>
</form>
Let me know if this works the way you wanted.
I'm trying to write a function that will allow a user to enter a name into a field, insert the field to a MySQL table and then update a dropdown menu to include those names (while allowing for further additions).
On first load of the page, the dropdown menu shows the correct names that I seeded into the table. When I input a name into the form, it inserts to the table correctly, but then none of the options show in the dropdown list and it removes my entry form. If I refresh the page, everything comes back fine, and the names previously entered show up in the list.
I know I'm missing something obvious in the code to refresh the page, but I'm not even sure what to search for. I thought that by setting my form action to .$_SERVER['PHP_SELF']. it would cause the page to process and reload. I have a hunch this is where my problem is, but I'm not sure what it is.
The dropdown code was something I found off the web, perhaps I have to rewrite it myself, though it's the one part of this mess that's actually working.
Also, the mysql login is hardcoded in db_tools.php b/c I can't get it to work otherwise.
Sorry for the following wall of text, but I'm just trying to provide the most information possible. Thank you for your replies and pointing me in the right direction.
I have 2 files, db_tools.php and dropdown.inc
db_tools.php:
<?php
require_once 'db_login.php';
require_once 'MDB2.php';
require_once("dropdown.inc");
//Define a function to perform the database insert and display the names
function insert_db($name){
//initialize db connection
//$dsn = 'mysql://$db_username:$db_password#$db_hostname/$db_database';
$dsn = "mysql://redacted";
$mdb2 =& MDB2::connect($dsn);
if (PEAR::isError($mdb2)) {
//die($mdb2->getMessage());
die($mdb2->getDebugInfo());
}
//Manipulation query
$sql = " INSERT INTO participants (id, name) VALUES (NULL, \"$name\");";
$affected =& $mdb2->exec($sql);
if (PEAR::isError($affected)){
//die($affected->getMessage());
die($affected->getDebugInfo());
}
//Display query
$query = "SELECT * FROM participants;";
$result =& $mdb2->query($query);
if (PEAR::isError($result)){
die ($result->getMessage());
}
while ($row = $result->fetchRow()){
echo $row[1] . "\n";
}
$mdb2->disconnect();
}
?>
<html>
<head>
<title>Event Bill Splitter</title>
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
else {
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
}
?>
<p>Participants:<br />
<?php dropdown(id, name, participants, name, participant_name1); ?></p>
</body>
</head>
</html>
dropdown.inc
require_once ('db_login.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if (!$connection) {
die ("Could not connect to the database: <br />". mysql_error() );
}
$db_select = mysql_select_db($db_database);
if (!$db_select) {
die ("Could not select the database: <br />". mysql_error() );
}
function dropdown($intNameID, $strNameField, $strTableName, $strOrderField, $strNameOrdinal, $strMethod="asc") {
//
// PHP DYNAMIC DROP-DOWN BOX - HTML SELECT
//
// 2006-05, 2008-09, 2009-04 http://kimbriggs.com/computers/
echo "<select name=\"$strNameOrdinal\">\n";
echo "<option value=\"NULL\">Select Value</option>\n";
$strQuery = "select $intNameID, $strNameField
from $strTableName
order by $strOrderField $strMethod";
$rsrcResult = mysql_query($strQuery);
while($arrayRow = mysql_fetch_assoc($rsrcResult)) {
$strA = $arrayRow["$intNameID"];
$strB = $arrayRow["$strNameField"];
echo "<option value=\"$strA\">$strB</option>\n";
}
echo "</select>";
}
?>
The problem of the form disappearing is simple, just remove the else after the insert section:
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
// else { // gone
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
// } // gone
?>
Apart from that I would definitely re-write the dropdown code and add some security, a whitelist for table names, etc.
By the way, you are calling your function in a strange way:
<?php dropdown(id, name, participants, name, participant_name1); ?>
I assume these are variables so it should be $id etc, but where do they come from? If you mean to send values directly, it should be:
<?php dropdown('id', 'name', 'participants', 'name', 'participant_name1'); ?>