I'm writing a website that allows for people to add movies into a database.
At the moment the user can either select from a director that is already within the database or create a new one.
<div class='dropdownrow' id='director_namerow'>
<div>
<label for='director_name'>Director:</label>
<select name='director_name'>
<option value='blank' selected>Select...</option>
<?php
$sql = "SELECT *
FROM director
ORDER BY director_name ASC";
$director = mysql_query($sql);
while ($directors=mysql_fetch_array($director)) {
?>
<option value="<?php echo $directors['director_id']; ?>"><?php echo $directors['director_name']; ?></option>
<?php
}
?>
</select>
<span style = 'color:red;'> *</span>
</div>
<div>
<label for='director_namenew'>Or new director:</label>
<input type='text' name='director_namenew' size='25' maxlength='128' />
</div>
</div>
So the problem is, how do I check that "director_namenew" isn't equal to "director_name" AND that director_namenew isn't already within the database.
Furthermore, is the "director_namenew" isn't within the database, I need to add them into the database too.
Controller Script
function validateDirector ($formdata) {
if(($formdata['director_name'] == "blank") && ($formdata['director_namenew'] == "")){
return false;
}
else if($formdata['hidden_director_name'] == $formdata['director_namenew']){
echo 'cannot have directors match';
return false;
}
else {
return true;
}
} // TO COMPLETE
Thanks guys,
pb.
Answer to my own question
if(($formdata['director_name'] == "blank") && ($formdata['director_namenew'] == "")){
print "<p>Please enter in director information - Use the back button on your browser to rectify this problem.</p>";
return false;
}
else if($formdata['director_namenew']) {
$doesntExist = true;
$db = getDBConnection();
$directors = $db->query("SELECT director_name FROM director");
//Check each one
foreach ($directors as $director){
//If the username is already in the DB stop looking
if($formdata['director_namenew'] == $director['director_name']){
$doesntExist = false;
print "<p>Director entered in new director already exists, please enter in new director or select from drop down menu - Use the back button on your browser to rectify this problem.</p>";
break;
}
}
//DB connection closed when PDO object isn't referenced
//ie setting $db to null closes the connection
$db = null;
return $doesntExist;
}
-- However, how would I check to see if both the drop down and input field have been filled?
I was thinking something like:
else if(($formdata['director_name']) && ($formdata['director_namenew'])) {
print "Please select either new director or director from drop down menu";
}
And checking on the submit to see if both $_POST variables have been submitted.
What do you think?
You can use Ajax to transfer the front-end requirement to back-end so that seperate the view and controller.
view.html (Some modification base on your original code):
<script src="checkRepeatName.js"></script>
<div>
<label for='director_namenew'>Or new director:</label>
<input type='text' name='director_namenew' size='25' maxlength='128' />
<span id="notation"></span>
</div>
checkRepeatName.js (Written with jQuery):
$("input[name='director_namenew']").change(function(){
$.get("backend.php?dnamenew=" + this.value,function(data,status){
$(".notation").text(data);
});
});
backend.php (I use Object Oriented Style of PHP code,and refer the recommendation of #Barmar):
<?php
if (isset($_GET['dnamenew'])) {
$director_namenew = $_GET['dnamenew'];
};
$dbconn = new mysqli(HOST, USERNAME, PASSWORD, DBNAME, PORT);
$sqlStat = sprintf('SELECT director_id FROM director WHERE director_name = "%s";', $director_namenew);
if ($sqlQuery = $dbconn->query($sqlStat)){
if ($sqlQuery->num_rows == 0){
echo 'This is validated database name';
} else {
echo 'Invalidated database name!';
}
}
$dbconn->close;
?>
-------- supplement something --------
It maybe something help in design dynamic dropdown menu with MVC design pattern
view.html:
<div class='dropdownrow' id='director_namerow'>
<div>
<label for='director_name'>Director:</label>
<select name='director_name'>
<option value='blank' selected>Select...</option>
</select>
<span style = 'color:red;'> *</span>
</div>
<div>
controllor.js:
$("select[name='director_name']").change(function(){
$.get("optionOutput.php", function(data,status){
$("select[name='director_name']").append(data); // append the call-back message from back-end file
});
});
optionOutput.php:
<?php
include 'dbmng/dbconfig.php';
$dbconn = new mysqli(HOST, USERNAME, PASSWORD, DBNAME, PORT);
$sqlStat = 'SELECT * FROM director ORDER BY director_name ASC;';
if ($sqlQue = $dbconn->query($sqlStat)){
while($sqlRes = $sqlQue->fetch_assoc()){
$output = sprintf('<option value = "%d">%s</option>', $sqlResult['director_id'], $sqlRes['director_name']);
echo $output;
}
}
$dbconn->close;
?>
Related
Im trying to add the chosen values from my drop down menu into my database by using primary and foreign keys. Im trying to figure out how when the customer selects the drop down box option, the VALUE is entered into sql, which is the same number as room table primary. Would i somehow post the drop down box select id = rooID? Can anyone please help me with this.
Below is my makeabookingphp code:
<!DOCTYPE HTML>
<html><head><title>Make a Booking</title> </head>
<body>
<?php
//function to clean input but not validate type and content
function cleanInput($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
//the data was sent using a formtherefore we use the $_POST instead of $_GET
//check if we are saving data first by checking if the submit button exists in the array
if (isset($_POST['submit']) and !empty($_POST['submit']) and ($_POST['submit'] == 'Book')) {
//if ($_SERVER["REQUEST_METHOD"] == "POST") { //alternative simpler POST test
include "config.php"; //load in any variables
$DBC = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);
//prepare a query and send it to the server
$query = 'SELECT room.roomID, room.roomname, room.roomtype, booking.bookingID, booking.roomID, booking.roomname
FROM room
INNER JOIN booking
ON room.roomID = booking.roomID';
if (mysqli_connect_errno()) {
echo "Error: Unable to connect to MySQL. ".mysqli_connect_error() ;
exit; //stop processing the page further
};
//validate incoming data - only the first field is done for you in this example - rest is up to you do
$error = 0; //clear our error flag
$msg = 'Error: ';
if (isset($_POST['roomname']) and !empty($_POST['roomname']) and is_string($_POST['roomname'])) {
$fn = cleanInput($_POST['roomname']);
$roomname = (strlen($fn)>50)?substr($fn,1,50):$fn;
//check length and clip if too big
//we would also do context checking here for contents, etc
} else {
$error++; //bump the error flag
$msg .= 'Invalid'; //append eror message
$roomname = '';
}
$roomname = cleanInput($_POST['roomname']);
$checkindate = cleanInput($_POST['checkindate']);
$checkoutdate = cleanInput($_POST['checkoutdate']);
$contactnumber = cleanInput($_POST['contactnumber']);
$bookingextras = cleanInput($_POST['bookingextras']);
//save the customer data if the error flag is still clear
if ($error == 0) {
$query1 = "INSERT INTO booking (roomname, checkindate, checkoutdate, contactnumber, bookingextras) VALUES (?,?,?,?,?)";
$stmt = mysqli_prepare($DBC,$query1); //prepare the query
mysqli_stmt_bind_param($stmt,'sssss', $roomname, $checkindate, $checkoutdate,$contactnumber,$bookingextras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>Booking saved</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}
mysqli_close($DBC); //close the connection once done
}
?>
<h1>Make A Booking</h1>
<h2><a href='menu.php'>[Return to the main page]</a></h2>
<form method = "post" action = "processbooking.php">
<p>
<label for = "rooID">Room: (name, type, beds): </label>
<select id = "rooID" name = "rooID" required>
<option name = "" value = "" disabled selected>Select</option>
<option name = "1" value = "1">Kellie, S, 5</option>
<option name = "2" value = "2">Herman, D, 2</option>
<option name = "3" value = "3">Scarlett, D, 2</option>
<option name = "4" value = "4">Jelani, S, 5</option>
<option name = "5" value = "5">Sonya, S, 4</option>
<option name = "6" value = "6">Miranda, S, 2</option>
<option name = "7" value = "7">Helen, S, 2</option>
<option name = "8" value = "8">Octavia, D, 3</option>
<option name = "9" value = "9">Bernard, D, 5</option>
<option name = "10" value = "10">Dacey, D, 1</option>
</select>
</p>
<p>
<label for="checkindate">Check in date: </label>
<input type="date" name="checkindate"required>
</p>
<p>
<label for="checkout">Check out date: </label>
<input type="date" name="checkoutdate"required>
</p>
<p>
<label for="contactnumber">Contact number: </label>
<input type="tel" name="contactnumber" required>
</p>
<p>
<label for="bookingextras">Booking extras: </label>
<input type="text" name="bookingextras" size="100" minlength="5" maxlength="200" required>
</p>
<input type="submit" name="submit" value="Book">
[Cancel]
</form>
</body>
</html>
Room table:
roomID (PK)
roomname
description
roomtype
beds
Booking table:
bookingID (PK)
roomname
checkindate
checkoutdate
contactnumber
bookingextras
roomID (FK)
I've rewritten your code - hope it helps
<?php
//function to clean input but not validate type and content
function cleanInput($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
// STEP 1 -test if form has been submitted
if (isset($_POST['submit']) && ($_POST['submit'] == 'Book')) {
// STEP 2. process the inputs
// get inputs - clean or set a default if not supplied
$roomID = isset( $_POST['rooID'] ) ? cleanInput($_POST['rooID']) : -1;
$checkindate = isset( $_POST['checkindate'] ) ? cleanInput($_POST['checkindate']) : "";
$checkoutdate = isset( $_POST['checkoutdate'] ) ? cleanInput($_POST['checkoutdate']) : "";
$contactnumber = isset( $_POST['contactnumber'] ) ? cleanInput($_POST['contactnumber']) : "";
$bookingextras = isset( $_POST['bookingextras'] ) ? cleanInput($_POST['bookingextras']) : "";
// STEP 3 validate/clean the inputs (don't trust anything coming in)
// validate all the inputs according to business rules
$error = 0;
$errMsg = [];
if( roomID == -1 ) {
$error++;
$errMsg[] = "Room not selected";
}
// do all other inputs
// proceed if no errors
if( $error != 0 ) {
// STEP 4 connect to the database
// connect to the database
include "config.php"; //load in any variables
$DBC = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);
if (mysqli_connect_errno()) {
echo "Error: Unable to connect to MySQL. ".mysqli_connect_error() ;
exit; //stop processing the page further
};
// STEP 5 check if the roomID is valid
// if roomID is valid then continue
$query = "SELECT roomID FROM roomTable WHERE roomID=".$roomID;
$result = $DBC->query( $query ); // ???? check the syntax of this line
if( $result ) { // something returned ???? check syntax
// STEP 5 update the relevant table(s)
$query1 = "INSERT INTO booking (roomID, checkindate, checkoutdate, contactnumber, bookingextras) VALUES (?,?,?,?,?)";
$stmt = mysqli_prepare($DBC,$query1); //prepare the query
mysqli_stmt_bind_param($stmt,'issss', $roomID, $checkindate, $checkoutdate,$contactnumber,$bookingextras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>Booking saved</h2>";
}
} else {
// STEP 3.1 show user messages of what went wrong
echo $errMsg;
}
mysqli_close($DBC); //close the connection once done
}
?>
I creating an inventory web-base system by using php and php myadmin (InnoDB). I want to insert the value in inventory when I inserting the record, I can see the data of the (FK) in the dropdown but when I submit the form the data to the db, it returns as no input value in the field and the dropdown not there anymore. Is the way I'm using the foreign key in the dropdown wrong?
I have a table that contains multiple foreign keys.
Table Inventory(
id (pk),
name,
condition_(fk),
producttype (fk))
Table condition_type(
condition_ (pk))
Table producttype(
producttype(fk))
<?php
// Include config file
require_once "../config.php";
// Define variables and initialize with empty values
$name = $condition_ = $producttype = "";
$name_err = $condition_err = $producttype_err = "";
$sql2 = "SELECT * FROM condition_type";
$sql4 = "SELECT * FROM producttype";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_name = trim($_POST["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
}else{
$name = $input_name;
}
// Validate condition
$input_condition = trim($_POST["condition_"]);
if(empty($input_condition)){
$condition_err = "Please choose the condition.";
} else{
$condition_ = $input_condition;
}
// Validate producttype
$input_producttype = trim($_POST["prodcuttype"]);
if(empty($input_producttype)){
$producttype_err = "Please enter the product type..";
} else{
$producttype = $input_producttype;
}
// Check input errors before inserting in database
if(empty($name_err) && empty($condition_err) && empty($producttype_err)){
// Prepare an insert statement
$sql = "INSERT INTO inventory (name, condition_, producttype) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_name, $param_condition, $param_producttype);
// Set parameters
$param_name = $name;
$param_condition = $condition;
$param_producttype = $producttype;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: ../application");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
}
?>
-------> This is the form
<div class="form-group <?php echo (!empty($condition_err)) ? 'has-error'
: ''; ?>">
<label>Condition</label>
</br>
<select id="condition_" name="condition_" class="form-control" value="<?
php echo $condition_ ;?>">
<option>Please Select Product Condition</option>
<?php
if($result2 = $mysqli ->query($sql2)){
while($row = $result2->fetch_array()){
echo "<option value=".$row['condition_'].">" .$row['condition_']. "
</option>";
}
}
?>
</select>
<span class="help-block"><?php echo $condition_err;?></span>
</div>
<div class="form-group <?php echo (!empty($producttype_err)) ? 'has-
error' : ''; ?>">
<label>Product</label>
</br>
<select name="producttype" class="form-control" value="<?php echo
$producttype ;?>">
<?php if($result4 = $mysqli ->query($sql4)){
while($row = $result4->fetch_array()){
echo "<option value=".$row['producttype'].">" .$row['producttype']. "
</option>";
}
}
?>
</select>
<span class="help-block"><?php echo $manufacturer_err;?></span>
</div>
So when I submit it return as the condition and producttype are empty. I think the error is because of
}
// Close connection
$mysqli->close();
}
statement that already close. But I don't know to place it.
PHP Warning: mysqli::query(): Couldn't fetch mysqli in /home/my-path/application/create_new.php on line 173
You should debug the html form first by right click with 'Inspect element' and make sure that the 'Select' value is getting?
I got a problem this is simple form i have to submit the data through radio buttons problem is that no value is displayed in database neither of disases name nor for yes,no option I have created database with name doctor with fields id ,dis_name,and ans.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
if (!empty($_POST)) {
// keep track validation errors
$disError = null;
$ansError = null;
// keep track post values
$dis_name = isset($_POST['dis_name']);
$ans=isset($_POST['ans']);
// validate input
$valid = true;
if (empty($dis_name)) {
$disError = 'Please enter Diseases Name';
$valid = false;
}
if (empty($ans)) {
$ansError = 'Please check one of option';
$valid = false;
}
// insert data
if ($valid) {
if(isset($_POST['dis_name'])){
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO diseases (dis_name) values(?)";
$q = $pdo->prepare($sql);
$q->execute(array($dis_name));
Database::disconnect();
//header("location: diseases.php");
}
}
}
?>
//some html code here
<div class="control-group <?php echo !empty($ansError)?'error':'';?>">
<label class="check">Have you suffered pain preiviously???</label>
<div class="controls">
<input type="radio" name="choice" <?php if (isset($ans) && $ans=="yes") echo "checked";?>
value="Yes">Yes
<input type="radio" name="choice"<?php if (isset($ans) && $ans=="no") echo "checked";?>
value="No">No
<?php
//if(isset($_POST['submit'])){
if(!empty($_POST['choice'])){
$ans=isset($_POST['ans']);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO diseases (question) values(?)";
$q = $pdo->prepare($sql);
$q->execute(array(isset($_POST['choice'])));
Database::disconnect();
}
//}
?>
`isset() it gives undefined index warning.`
I suppose ans stands for answer which is filled by the radio control value. And this is how you fetch it on server side:
$ans=isset($_POST['ans']);
In your html it is actually choice
Shouldn't you be getting it like this?
$ans=isset($_POST['choice']);
EDIT:
And why would you use isset function to fetch post value?
isset() returns boolean and the input is named 'choice'.
Perhaps you mean:
if( isset($_POST['choice']) ){
$ans = $_POST['choice'];
// Optionally you may want $ans to be boolean:
if($ans == 'Yes') {
$ans = TRUE;
} else {
$ans = FALSE;
}
}
then (if the table column is properly defined to store the boolean/integer/enum):
$q->execute(array($ans));
will store 1 (True) or 0 (False)
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'); ?>