I'm having trouble inserting data into a table.
I have the following tables: track (id, tracktitle), album (id, albumtitle), composer (id, composername), albumtrack (PRIMARY: trackid, albumid, composerid).
My PHP page allows you to add a track and then select the album and composer connected with it. It adds the track to the tracktable okay but it won't add it to an album.
I keep looking around for how to do it and I keep getting a bit lost.
Can anyone tell me how I should be correctly doing this?
Thanks
if (isset($_POST['tracktitle'])):
// A new track has been entered
// using the form.
$cid= $_POST['cid'];
$tracktitle = $_POST['tracktitle'];
$albs = $_POST['albs'];
if ($cid == '') {
exit('<p>You must choose an composer for this track. Click "Back" and try again.</p>'); }
$sql = "INSERT INTO track, albumtrack SET
track.tracktitle='$tracktitle', albumtrack.albumid='$albs', albumtrack.composerid='$cid' " ;
if (#mysql_query($sql)) {
echo '<p>New track added</p>';
} else {
exit('<p>Error adding new track' . mysql_error() . '</p>');
}
$trackid = mysql_insert_id();
if (isset($_POST['albs'])) {
$albs = $_POST['albs'];
} else {
$albs = array();
}
$numAlbs = 0;
foreach ($albs as $albID) {
$sql = "INSERT IGNORE INTO albumtrack
SET albumtrack.trackid='$trackid', albumtrack.albumid='$albs', albumtrack.composerid='$cid'";
if ($ok) {
$numAlbs = $numAlbs + 1;
} else {
echo "<p>Error inserting track into album $albID: " .
mysql_error() . '</p>';
}
}
?>
<p>Track was added to <?php echo $numAlbs; ?> albums.</p>
<p>Add another track</p>
<p>Return to track search</p>
<?php
else: // Allow the user to enter a new track
$composers = #mysql_query('SELECT id, composername FROM composer');
if (!$composers) {
exit('<p>Unable to obtain composer list from the database.</p>');
}
$albs = #mysql_query('SELECT id, albumtitle FROM album');
if (!$albs) {
exit('<p>Unable to obtain album list from the database.</p>');
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>Enter the new track:<br />
<textarea name="tracktitle" rows="1" cols="20">
</textarea></p>
<p>Composer:
<select name="cid" size="1">
<option selected value="">Select One</option>
<option value="">---------</option>
<?php
while ($composer= mysql_fetch_array($composers)) {
$cid = $composer['id'];
$cname = htmlspecialchars($composer['composername']);
echo "<option value='$cid'>$cname</option>\n";
}
?>
</select></p>
<p>Place in albums:<br />
<?php
while ($alb = mysql_fetch_array($albs)) {
$aid = $alb['id'];
$aname = htmlspecialchars($alb['albumtitle']);
echo "<label><input type='checkbox' name='albs[]' value='$aid' />$aname</label><br />\n";
}
?>
Your insert sentence is wrong:
Try this:
$sql = "INSERT IGNORE INTO albumtrack (trackid, albumid, composerid) values " .
"($trackid, $albs, $cid)";
Assuming your IDs are numeric.
Beware of SQL Injections when you inject non-sanitized values you get from your request.
Beside's Pablo's corrected way of writing the query. I also notice you are trying to insert into two tables at once with:
$sql= "INSERT INTO track, albumtrack"
MySQL does not allow inserting into two tables at once.
Related
Through hours of research and looking through code in questions submitted on this site, I was finally able to get the select options (dropdowns) to pull data from my database tables into the dropdown lists on my html form.
However, my issue is that when the fields on the form were inputs they inserted the new information into the database just fine. Unfortunately, now that I've implemented the dropdown lists as part of the form, none of the information from the form inserts into the database anymore. Clicking on the 'submit' button returns the response that it was successful, but when I check the table in the database, the new information is not there.
I'm sorry I haven't been able to figure this piece of functionality out by myself. I noticed my last question received negative feedback, so I'm leary to even submit this one, but I really need some help.
Will you please look through the following code and let me know what I'm missing or have coded incorrectly? I just need to know what I need to do to make the selected values from the dropdown lists insert into the 'dvd' table and 'categoryname' and 'genretype' fields, respectively.
<?php
session_start();
//include the header
include ('../main/header.php');
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
require_once ('../../../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize error array.
// Check for a first name.
if (empty($_POST['title'])) {
$errors[] = 'You forgot to enter a title.';
} else {
$title = mysqli_real_escape_string($dbc, $_POST['title']);
}
// Check for a category.
if (empty($_POST['numavail'])) {
$errors[] = 'You forgot to enter quantity purchased.';
} else {
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
}
// Check for a category.
if (empty($_POST['categoryname'])) {
$errors[] = 'You forgot to enter a category.';
} else {
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
}
// Check for a genre.
if (empty($_POST['genretype'])) {
$errors[] = 'You forgot to enter a genre.';
} else {
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
}
if (empty($errors)) { // If everything's OK.
// Add the movie to the database.
// Check for existing record.
$query = "SELECT id FROM dvd WHERE title='$title'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
if ($result) { // If it ran OK.
echo "<p><b>Success! The new movie has been added.</b></p>";
echo ('<p><div style="margin-top:30px;">');
echo ('<span style="float:left;">');
echo ('<FORM METHOD="LINK" ACTION="../dvd/index.php"><INPUT TYPE="submit" VALUE="Back to DVDs" STYLE="margin:0px 15px 0px 0px;"></form></span></div></p>');
echo ('<br style="clear:both;"></br>');
exit();
} else { // If it did not run OK.
$errors[] = 'The movie could not be added due to a system error. We apologize for any inconvenience.'; // Public message.
$errors[] = mysqli_error($dbc); // MySQL error message.
}
} else { // Title is already taken.
$errors[] = 'The movie title entered already exists.';
}
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} else { // Form has not been submitted.
$errors = NULL;
} // End of the main Submit conditional.
// Begin the page now.
if (!empty($errors)) { // Print any error messages.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo "$msg<br />";
}
echo '</p>';
echo '<p style="color:red; font-weight:bold;"><em>Please try again.</em></p></br>';
}
// Create the form.
?>
<h1>Add a Movie</h1>
<h2>Please complete all of the fields below:</h2>
<form action="../dvd/add.php" method="post">
<p>Title: <input type="text" name="title" size="15" maxlength="15" value="<?php echo $_POST['title']; ?>"></p>
<p>Quantity Purchased: <input type="text" name="numavail" size="15" maxlength="30" value="<?php echo $_POST['numavail']; ?>"></p>
<p>
<?php
include ('../../../mysqli_connect.php'); // Connect to the db.
$ddlquery = "SELECT categoryname FROM category ORDER BY categoryname ASC";
$ddlresult = mysqli_query($dbc, $ddlquery) or die("Bad SQL: $ddlquery");
echo 'Category: <select name="categoryname" size="1">';
while($ddlrow=mysqli_fetch_array($ddlresult, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow['categoryname']."'>" . $ddlrow['categoryname'] . "</option>";
}
echo "</select>";
?>
<p>
<?php
$ddlquery2 = "SELECT genretype FROM genre ORDER BY genretype ASC";
$ddlresult2 = mysqli_query($dbc, $ddlquery2) or die("Bad SQL: $ddlquery");
echo 'Genre: <select name="genretype" size="1">';
while($ddlrow2=mysqli_fetch_array($ddlresult2, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow2['genretype']."'>" . $ddlrow2['genretype'] . "</option>";
}
echo "</select>";
?>
<p>
<input type="submit" name="submit" value="Submit">
<input type=reset value=Reset>
<input type="hidden" name="submitted" value="TRUE"></p>
</form>
<?php
// Include footer.php
include("../../includes/footer.php");
?>
You forgot to actually run the insert into database
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
$result = mysqli_query($dbc, $query); // <---- ADD HERE
if ($result) { // If it ran OK.
....
I have stayed up two nights and I haven't been able to fix this. I am new to the site as well as in PHP please forgive my inexperience. The idea is that when a user selects several courses it should be sent to the database and stored in separate rows. what happens now is that it stores only the first value twice in the database. thanks.
code:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
$user_id=$_SESSION['user_id'];
?>
<h2>Register</h2>
<?php
if(isset($_GET['success']) && empty($_GET['success'])){
echo 'You have successfully registered!';
}
else{
if(empty($_POST)===false){
$course[]=$_POST['course_code'];
$user_id= $user_data['user_id'];
$username=$user_data['username'];
foreach($course as $c){
$data= '\''.implode('\',\'',$c).'\'';
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) VALUE ('$user_id','$username', $data)");
header('location:courses.php?success');
exit();
}
}
?>
<form action="" method="post">
<?php
$sql = "SELECT * FROM course";
$result = mysql_query($sql)or die(mysql_error());
echo "<table>";
echo "<tr><th>COURSE CODE</th><th>COURSE TITLE</th><th>UNIT</th><th>SEMESTER</th><th>LEVEL</th></tr>";
while($row = mysql_fetch_array($result)){
$course_code = $row['course_code'];
$course_title = $row['course_title'];
$course_unit = $row['course_unit'];
$semester = $row['semester'];
$level = $row['level'];
echo "<tr><td style='width: 100px;'>".$course_code."</td><td style='width: 600px;'>".$course_title."</td><td>".$course_unit."</td><td>".$semester."</td><td>".$level."</td><td><input type=\"checkbox\" name=\"course_code[]\" value=".$course_code."></td></tr>";
} // End our while loop
echo "</table>";
?>
<input type="submit" value="Register">
</form>
<?php
}
include 'includes/overall/footer.php';
?>
Your code is dangerous. It is not resistant for sql injection. You should stop using mysql_ functions and switch to mysqli or PDO.
But just to fix the bug now you can change your code in this part:
foreach($course as $c){
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`)
VALUES ('$user_id','$username', $c)");
}
header('location:courses.php?success');
exit();
redirection inside loop stopped the process so it did only once. for good practice do not put sql query inside loop it makes slow process.
$values = '';
foreach($course as $c){
$values .= "('$user_id','$username', '$c'), ";
}
$values = rtrim($values, ',');
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) VALUES {$values}");
header('location:courses.php?success');
exit();
if you don't agree, why you don't write some comment?
I have a simple form in PHP, having 4 check boxes. The user can select 0-4 number of checkboxes and based on their selection the results should differ.
Basically the four checkboxes represents the four campuses of a university- Campus A,B,C,D. and suppose if the user select 2 campuses say A and C. then I want to query the database based on the selection and retrieve the courses corresponding to those two campuses A and C. If the user selects only one campus then I want to retrieve courses in that single campus.
On mySQL, I have a Location table with the following schema (ID,Campus Name, City, State) with ID being the primary key. Also I have a course table with schema as Course(ID,CourseName,LocationID,Seatsleft). ID is the primary key and LocationID is the foreign key, which references ID of Location table.
My PHP code is as follows:
Here is the updated version of my code.
PHP form check box selecting different campuses
<body>
<?php
require 'connection.php';
if(isset($_POST['formSubmit']))
{
$aCampus = $_POST['campus'];
if(empty($aCampus))
{
echo("<p>You didn't select any campus.</p>\n");
}
else
{
$N = count($aCampus);
echo("<p>You selected $N campus(s): ");
for($i=0; $i < $N; $i++)
{
echo($aCampus[$i] . " ");
}
echo("</p>");
}
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
$where="1";
if(!empty($_POST['campus'])){
foreach ($_POST['campus'] as $campus){
$where=" LocationID='". $campus."'";
}
}
//$query = "SELECT `Name` FROM `course` WHERE LocationID=1";
$query="SELECT `Name` FROM `course` WHERE 1 AND (".$where.")";
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$coursename =$query_row['Name'];
echo $coursename. '<br/>';
}
} else {
echo mysql_error();
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
Which campus courses do you want to get access to?<br/>
<input type="checkbox" name="campus[]" value=1 />Campus A<br />
<input type="checkbox" name="campus[]" value=2 />Campus B<br />
<input type="checkbox" name="campus[]" value=3 />Campus C<br />
<input type="checkbox" name="campus[]" value=4 />Campus D
</p>
<input type="submit" name="formSubmit" value="Submit" />
</form>
</body>
</html>
My question is how do I take options from my PHP form and query the database to retrieve courses from the selected campuses only?
Please try with following simple query creator logic.
$whereArr =Array();
$whereArr[] = 1;
if(!empty($_POST['campus'])){
foreach ($_POST['campus'] as $campus){
$whereArr[]=" LocationID LIKE ',". $campus.",'";
}
}
$query="SELECT `Name` FROM `course` WHERE 1 AND(".implode(" OR ",$whereArr)." )";
Above code will work for following record:
289,"Math","2,3,",67
In this instance I would store the campuses as a comma delimited string in the database. Then you can use the FIND_IN_SET() function in mySQL to query based on that
for instance
a record for the course
203,"Biology","1,2,4",34
then you can
SELECT * FROM course WHERE FIND_IN_SET(4,locationid)
which will give you all of the records that have 4 in the "set"
Something like this :
$validoptions = array('A','B','C','D');
$allvalid = true;
foreach ($_POST['campus'] as $campus){
if (!in_array($campus,$validoptions)) $allvalid = false;
}
if (!$allvalid) {
echo 'Wrong campuses selected. Try again.';
exit;
}
$query = 'SELECT * FROM `Courses` WHERE ';
$query .= 'LocationID = \''.implode('\' OR LocationID = \'',$campuses).'\'';
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) die('Could not connect: ' . mysql_error());
mysql_select_db("databasename");
$res = mysql_query($query);
$data = array();
if ($res && mysql_num_rows()) {
$data = array();
while($d = mysql_fetch_array($res)) {
$data[] = $d;
}
}
if (count($data) > 0) {
echo 'No courses found !';
}else {
echo 'Courses found : ';
print_r($data);
}
I have a site in which logged in users can accumulate points which they can later buy with via a shopping cart. The page below is an admin php feature in which an Admin can give points to an individual user (one user at a time for now).
There are three tables involved with this script:
users: contains the users details
tally_point: stores all of the points transactions, both incoming and ordering
reward_points: stores the total amount of points that the user has
The script retrieves the users’ details via a drop down menu and adds the points to the tally point table ok but....
<?php # add-points-ind.php
// This is the main page for the site.
// Include the configuration file for error management and such.
require_once ('./includes/config.inc.php');
// Set the page title and include the HTML header.
$page_title = 'Add Points to User';
include ('includes/header_admin_user.html');
// If no dealer_code variable exists, redirect the user.
if (!isset($_SESSION['admin_int_id'])) {
// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
?>
<h1>Add Points to User</h1>
<div id="maincontent_inner">
<div id="maincontent_inner2">
<?php //add-points-ind.php
// This page allows the admin to add points to an individual user
require_once ('mydatabase.php'); // Connect to the database.
if (isset($_POST['submitted'])) { // Check if the form has been submitted.
// Check if points were submitted through the form.
if (is_numeric($_POST['tally_points_in'])) {
$p = (float) $_POST['tally_points_in'];
} else {
$p = FALSE;
echo '<p><font color="red">Please enter the pointås!</font></p>';
}
// Validate the User has been selected
if ($_POST['selected_user'] == 'new') {
// If it's a new categories, add the categories to the database.
$query = 'INSERT INTO tally_points (users_id) VALUES (';
// Check for a last_name.
if (!empty($_POST['users_id'])) {
$query .= "'" . escape_data($_POST['users_id']) . "')";
$result = mysql_query ($query); // Run the query.
$a = mysql_insert_id(); // Get the categories ID.
} else { // No last name value.
$a = FALSE;
echo '<p><font color="red">Please enter the Dealers name!</font></p>';
}
} elseif ( ($_POST['selected_user'] == 'existing') && ($_POST['existing'] > 0))
{ // Existing categories.
$a = (int) $_POST['existing'];
} else { // No categories selected.
$a = FALSE;
echo '<p><font color="red">Please select a registered Dealer!</font></p>';
}
if ($p && $a) { // If everything's OK.
// Add the print to the database.
$query = "INSERT INTO tally_point (users_id, tally_points_in, order_id, total, tally_points_entry_date) VALUES ('$a', '$p', '0', '0', NOW())";
if ($result = mysql_query ($query))
{
// Worked.
echo '<p>The reward product has been added.</p><br />Go back<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
} else {
// If the query did not run OK.
echo '<p><font color="red">Your submission could not be
processed due to a system error.</font></p>';
}
} else { // Failed a test.
echo '<p><font color="red">Please click "back" and try again.</font></p>';
}
} else { // Display the form.
?>
<form enctype="multipart/form-data" action="add-points-ind.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
<fieldset>
<legend>Add Points Individually:</legend>
<p><b>Select User:</b></p>
<p>
<select name="existing"><option>Select One</option>
<?php // Retrieve all the users details and add to the pull-down menu.
$query = "SELECT users_id, users_sale_id, users_first_name, users_surname FROM users ORDER BY users_surname ASC";
$result = #mysql_query ($query);
while ($row = #mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo "<option value=\"{$row['users_id']}\">{$row['users_sale_id']}: {$row['users_first_name']} {$row['users_surname']} </option>\n";
}
#mysql_close($dbc); // Close the database connection.
?>
</select></p>
<span class="extras"><input type="radio" name="selected_user" value="existing" /> Please confirm this is the correct user</span>
<p><b>Points:</b> <br />
<input type="text" name="tally_points_in" size="10" maxlength="10" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden"name="submitted" value="TRUE" />
</form>
<?php
} // End of main conditional.
?>
<br class="clearboth" />
End text
</div>
<?php // Include the HTML footer file.
include ('includes/footer_admin_user.html');
?>
... Im having trouble with getting the new points added to the points total field (reward_user_points) in the reward_points table, I have some code below but Im not sure where I am supposed to put it, if anyone has any suggestions please let me know.
<?php
$query = "SELECT reward_user_points FROM reward_points WHERE users_id = $a";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$TotalPoints = $row['reward_user_points'];
if (#mysql_affected_rows($dbc) == 1) { // Whohoo!
$new_credit = $TotalPoints + $p;
$query = "UPDATE reward_points SET reward_user_points ='$new_credit' WHERE users_id = $a";
$result = #mysql_query($query);
}
?>
Ok, I have to say that I don't understand very well what your trouble is. You say you're having trouble with getting the new points added to the points total field, but could you be a little more specific? Is there any error message returned by php or mysql?
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'); ?>