Populating a dropdown list through SQL with specific condions - php

Essentially, i'm trying to select all the users from my table where their type ='users' and if that condition is met, select their first and last name. Store them into variables and then display the variables into a dropdown list one by one(array).
Current code:
<div id="ContainerC">
<form action="AppointmentAddQuery.php" method="post">
<input type="text" name="date" class="datepicker" placeholder="Please select a date" required><br>
<input type="text" name="patient" class="textbox" placeholder="Patient" required> <br>
<?php
include 'dbconnection.php';
?>
<input type="text" name="phlebotomist" class="textbox" placeholder="phlebotomist" required> <br>
<input type="text" name="bloods" class="textbox" placeholder="blood required" required><br>
<p>Has the appointment been allocated?</p>
<select name="allocated" class="textbox" required>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
<br><br><br>
<button type="submit" name="submit" class="SUB">Add patient</button>
</form>
</div>
SQL setup:

For the SQL part of your question, you are probably looking for something like:
select firstname
, lastname
from <table>
where type = 'user'

Assuming the structure of your database (you will likely need to replace table and column names) this is how you could do it:
<?php
include 'dbconnection.php';
$sql = "SELECT firstname, lastname FROM users WHERE type = 'users'";
$result = $conn->query($sql) or die($conn->error);
if ($result->num_rows > 0) {
echo '<select>';
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row["firstname"].$row["lastname"].'">'.$row["firstname"].$row["lastname"].'</option>';
}
echo '</select>';
} else {
echo '<select><option value="">No Users</option></select>';
}
$conn->close();
?>
This also assumes that inside of dbconnection.php you created a mysqli object like so:
$conn = new mysqli($servername, $username, $password, $dbname);

Related

Create Autofill form with PHP

So im still relatively new to php and im trying to create a form that autofill's with information from a table. The table is called students and has the students id, first and last name, and their address. Im trying to make it so it only autofill's with the information of the student with a certain id, for example if the students id is 102 it fills the textboxes with their info.
I have some code which i thought would work but its telling me somethings wrong with the while loop and i don't know what.
Edit: The error i keep getting is this:"mysqli_fetch_assoc() expects parameter 1 to be mysqli_result".
PHP code:
<?php
require_once ('Connection.php');
$query = "SELECT * from students where Id = 102";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($result)) {
$row['student_id'];
$row['stu_Fname'];
$row['stu_Lname'];
$row['stu_addr'];
}
?>
Html Form:
<form action="http://localhost/test.php" method="post">
<p>Student ID:
<input name="stu_id" size="5" value="<?php echo $row['student_id']; ?>" pattern="^\d{3}" required autofocus /><?php echo $row['student_id']; ?>
</p>
<p>First Name:
<input type="text" name="fname" size="30" value="<?php echo $row['stu_Fname']; ?>"/>
</p>
<p>Last Name:
<input type="text" name="lname" size="30" value="<?php echo $row['stu_Lname']; ?>"/>
</p>
<p>Address:
<input type="text" name="address" size="30" value="<?php echo $row['stu_addr']; ?>"/>
</p>
<p>
<input type="submit" name="submit" value="Send"/>
</p>
</form>
EDIT: Connection code:
<?php
DEFINE ('DB_User', 'testuser');
DEFINE ('DB_Password', 'abc123*');
DEFINE ('DB_Host', 'localhost');
DEFINE ('DB_Name', 'student');
//start database connection
$dbc = new mysqli(DB_Host, DB_User,DB_Password,DB_Name);
if(mysqli_connect_errno())
{
printf("can't connect to database.", mysqli_connect_error());
exit();
}
?>
while ($row = mysqli_fetch_assoc($result)) {
$row['student_id'];
$row['stu_Fname'];
$row['stu_Lname'];
$row['stu_addr'];
}
You're not actually accomplishing anything within the while loop above. There is no assignment, nor output.
Each iteration of the while loop will grab a row (if there is one in the database). Assuming that the row has the four columns you've listed, you can print the data to the screen. For example:
while ($row = mysqli_fetch_assoc($result)) {
echo $row['student_id'] . ", ";
echo $row['stu_Fname'] . ", ";
echo $row['stu_Lname'] . ", ";
echo $row['stu_addr'];
}
Assuming you're outputting a form for each student, you can place the form logic within the while loop.

Inserting Data into MySQL table using HTML form

I am currently trying to insert rows into a MySQL database, and most of the code is there but I'm having a few issues I can't diagnose. I know the database connection is good, and every time the submit button is pressed it runs the correct php script. The issue I'm having is that it always adds 2 records to the database table and fails to carry though any of the form data (it inserts two completely blank rows.)
Here's the code for the form (with a little extra code for the wordpress page)
<div class="main-container">
<div class="content-area">
<div class="middle-align">
<div class="site-main" id="sitefull">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<div>
<form method="POST" name="cutting tool" action="add-tool-script.php">
<table style="width:auto;">
<tr>
<th width="50%"><h2><ul>Tool Information</ul></h2><br></th>
<th width="50%"><ul><h2>Storage Information</h2></ul><br></th>
</tr>
<tr>
<td width="50%">
<h3>Tooling Name</h3><br>
<input type="text" name="name" placeholder="e.g. ShearHog"><br><br>
<h3>Tooling Type</h3><br>
<select name="type">
<option selected disabled hidden style='display: none' value=''></option>
<option value="Ballnose Endmill">Ballnose Endmill</option>
<option value="Bullnose Endmill">Bullnose Endmill</option>
<option value="Boring Bar">Boring Bar</option>
<option value="Brush">Brush</option>
<option value="Burnishing">Burnishing</option>
<option value="Chamfer Mill">Chamfer Mill</option>
<option value="Countersink">Countersink</option>
<option value="Drill">Drill</option>
<option value="Drill/Mill">Drill/Mill</option>
<option value="Engraver">Engraver</option>
<option value="Face Mill">Face Mill</option>
<option value="Flat Endmill">Flat Endmill</option>
<option value="High Feed Mill">High Feed Mill</option>
<option value="Reamer">Reamer</option>
<option value="Slitting Saw">Slitting Saw</option>
<option value="Spot Drill">Spot Drill</option>
<option value="Tap">Tap</option>
<option value="Threadmill">Threadmill</option>
<option value="Woodruff">Woodruff</option>
<option value="Other">Other</option>
</select><br><br>
<h3>Tooling Brand</h3><br>
<input type="text" name="brand" placeholder="e.g. Lakeshore Carbide"><br><br>
<h3>Part Number</h3><br>
<input type="text" name="part_number" placeholder="e.g. 360014X"><br><br>
<h3>Price</h3><br>
<input type="text" name="price" placeholder="e.g. 24.95"><br><br>
<h3>Overall Length</h3><br>
<input type="text" name="oal" placeholder="e.g. 2.5"><br><br>
<h3>Tooling Material</h3><br>
<select name="material">
<option selected disabled hidden style='display: none' value=''></option>
<option value="Carbide">Carbide</option>
<option value="Ceramic">Ceramic</option>
<option value="Diamond">Diamond</option>
<option value="HSS">HSS</option>
<option value="Powdered Metal">Powdered Metal</option>
</select><br><br>
<h3>Cutting Diameter</h3><br>
<input type="text" name="cutting_diam" placeholder="e.g. 0.250"><br><br>
<h3>Shank Diameter</h3><br>
<input type="text" name="shank_diam" placeholder="e.g. .250"><br><br>
<h3>Number of Flutes</h3><br>
<input type="text" name="flutes" placeholder="e.g. 3"><br><br>
<h3>Length of Cut (Flute Length)</h3><br>
<input type="text" name="loc" placeholder="e.g. .750"><br><br>
<h3>Corner Radius</h3><br>
<input type="text" name="corner_rad" placeholder="e.g. .004"><br><br>
</td>
<td width="50%">
<h3>Quantity in Stock</h3><br>
<input type="text" name="qty" placeholder="e.g. 37"><br><br>
<h3>Minimum Trigger Quantity</h3><br>
<input type="text" name="trigger_qty" placeholder="e.g. 4"><br><br>
<h3>Reorder Link</h3><br>
<input type="text" name="reorder_link" placeholder="e.g. example.com"><br><br>
<h3>Toolbox Number</h3><br>
<input type="text" name="toolbox_no" placeholder="e.g. 1"><br><br>
<h3>Drawer Number</h3><br>
<input type="text" name="drawer_no" placeholder="e.g. 1"><br><br>
<h3>Bin Number</h3><br>
<input type="text" name="bin_no" placeholder="e.g. 1"><br><br>
<h3>Product</h3><br>
<input type="text" name="product" placeholder="e.g. Widget #2"><br><br>
<input type="submit" value="Add to Tool Crib" name="submitbutton" action="submit"/>
</td>
</tr>
</table>
</form>
</div>
<?php
//If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || '0' != get_comments_number() )
comments_template();
?>
<?php endwhile; // end of the loop. ?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<?php get_footer(); ?>
And here's the code for the php script to add form data to the database:
//MySQL Database
$servername = "url.com";
$username = "user_login";
$password = "user_password";
$datab = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $datab);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_REQUEST['name'];
$type = $_REQUEST['type'];
$brand = $_REQUEST['brand'];
$part_number = $_REQUEST['part_number'];
$price = $_REQUEST['price'];
$oal = $_REQUEST['oal'];
$material = $_REQUEST['material'];
$cutting_diam = $_REQUEST['cutting_diam'];
$shank_diam = $_REQUEST['shank_diam'];
$flutes = $_REQUEST['flutes'];
$loc = $_REQUEST['loc'];
$corner_rad = $_REQUEST['corner_rad'];
$qty = $_REQUEST['qty'];
$trigger_qty = $_REQUEST['trigger_qty'];
$reorder_link = $_REQUEST['reorder_link'];
$toolbox_no = $_REQUEST['toolbox_no'];
$drawer_no = $_REQUEST['drawer_no'];
$bin_no = $_REQUEST['bin_no'];
$product = $_REQUEST['product'];
$username = $user_login;
$sql = "INSERT INTO `cutting tools` (`name`, `type`, `brand`, `part_number`, `reorder_link`, `oal`, `price`, `material`, `cutting_diam`, `shank_diam`, `flutes`, `loc`, `corner_rad`, `qty`, `trigger_qty`, `user`, `drawer_no`, `bin_no`, `toolbox_no`)
VALUES ('$name', '$type', '$brand', '$part_number', '$reorder_link', '$oal', '$price', '$material', '$cutting_diam', '$shank_diam', '$flutes', '$loc', '$corner_rad', '$qty', '$trigger_qty', '$username', '$drawer_no', '$bin_no', '$toolbox_no')";
if(mysqli_query($conn, $sql)){
echo "Record added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
Also I know my database is vulnerable to injection, that was a change I planned on making once the form was up and running.
Use WordPress to your advantage. Instead of defining your own connection, use global $wpdb, and then use the insert command.
global $wpdb;
$success = $wpdb->insert('tbl_name', array(<br>
'field1_name' => $_REQUEST['field1'],<br>
'field2_name' => $_REQUEST['field2'],<br>
));<br>
if($success){<br>
echo "Inserted correctly";<br>
} else {<br>
echo "Something went awry!";<br>
}
Here's a prepared statement, a more secure way of creating a MYSQL record in your table.
<?php
//MySQL Database
$servername = "url.com";
$username = "user_login";
$password = "user_password";
$datab = "database_name";
// Create connection
$con = new mysqli($servername, $username, $password, $datab);
global $con;
// Post form data
$name = $_POST['name'];
$type = $_POST['type'];
$brand = $_POST['brand'];
$part_number = $_POST['part_number'];
$price = $_POST['price'];
$oal = $_POST['oal'];
$material = $_POST['material'];
$cutting_diam = $_POST['cutting_diam'];
$shank_diam = $_POST['shank_diam'];
$flutes = $_POST['flutes'];
$loc = $_POST['loc'];
$corner_rad = $_POST['corner_rad'];
$qty = $_POST['qty'];
$trigger_qty = $_POST['trigger_qty'];
$reorder_link = $_POST['reorder_link'];
$toolbox_no = $_POST['toolbox_no'];
$drawer_no = $_POST['drawer_no'];
$bin_no = $_POST['bin_no'];
$product = $_POST['product'];
// Prepared statement
$insert = mysqli_prepare($con, "insert into cutting tools (name,type,brand,part_number,reorder_link,oal,price,material,cutting_diam,shank_diam,flutes,loc,corner_rad,qty,trigger_qty,user,drawer_no,bin_no,toolbox_no) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
mysqli_stmt_bind_param($insert, "sssssssssssssssssss", $name,$type,$brand,$part_number,$reorder_link,$oal,$price,$material,$cutting_diam,$shank_diam,$flutes,$loc,$corner_rad,$qty,$trigger_qty,$product,$drawer_no,$bin_no,$toolbox_no);
mysqli_stmt_execute($insert);
if ($insert) { echo "success"; mysqli_close($con); } else { echo "error"; mysqli_close($con); }
?>
Pay close attention to the order of your columns and the data you are submitting to those columns. I have edited this post because your order was incorrect in several places.
The column names and the data variables being uploaded to them have to be in the exact same order if you want data created correctly.
By the way the variable $product does not seem to match the column name of user, you may want to check this.

How to add to this update SQL statement and make a drop down list too for it

Okay i have this SQL statement for update which works find but I want to add locations which is in te_venue table after adding the location into sql i want for locations to be a drop down list which user can pick one location from list and when clicked on update it should update.
This is the php code that I have already (I need to add location into this)
<?php
$eventID = $_GET['id'];
if(isset($_POST['submit']))
{
$title = $_POST['title'];
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$price = $_POST['price'];
$description = $_POST['description'];
$sql = "UPDATE te_events SET eventTitle='$title',eventStartDate='$startdate',eventEndDate='$enddate',eventPrice='$price',eventDescription='$description' WHERE eventID=$eventID";
if ($conn->query($sql) === TRUE)
{
header('Location:edit.php');
}
else
{
echo "Error updating record";
}
}
$sql = "SELECT * FROM te_events where eventID='$eventID'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$eventTitle = $row['eventTitle'];
$eventDescription = $row['eventDescription'];
$eventStartDate = $row['eventStartDate'];
$eventEndDate = $row['eventEndDate'];
$eventPrice = $row['eventPrice'];
}
?>
And this is where i want to have a drop down list for location.
<form method="post" action="">
<label for="title">Title</label><br/>
<input type="text" name="title" required/ value="<?php echo $eventTitle; ?>"><br/>
<label for="startdate">Start Date</label><br/>
<input type="date" name="startdate" required/ value="<?php echo $eventStartDate; ?>"><br/>
<label for="enddate">End Date</label><br/>
<input type="date" name="enddate" required/ value="<?php echo $eventEndDate; ?>"><br/>
<label for="price">Price (£)</label><br/>
<input type="number" step="any" name="price" required/ value="<?php echo $eventPrice; ?>"><br/>
<label for="description">Description</label><br/>
<textarea name="description" cols="55" rows="5"><?php echo $eventDescription; ?></textarea><br/>
<input type="submit" name="submit" value="Update" class="button">
</form>
Here is a screenshot of my tables too it might help.
https://postimg.org/image/6ui8nsi55/
Do you want something like this? Getting the location from te_venue and adding the results to a select?
<select>
<?php
$sql = "SELECT location FROM te_venue";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
}
?>
<option value="<?php echo $row['location'];?>"><?php echo $row['location'];?> </option>
<?php
}
?>
</select>
<label for="location">Choose a location: </label>
<select class="form-control" name="location">
<option value="London">London</option>
<option value="Paris">Paris</option>
<option value="Rome">Rome</option>
<option value="Berlin">Berlin</option>
<option value="Moscow">Moscow</option>
</select>

Incorrect integer value: '' for column 'customerid' at row 1

I am working on my project for school and is now stuck on this problem that I hope someone here my point me in the right direction.
I am designing a booking system which uses a web front and MySQL database. I have a few tables: Customers, Seats, Price, Booking and Screening. I am trying to insert data into the booking table from the other tables using there primary keys. however I keep getting the following error message: Incorrect integer value: '' for column 'customerid' at row 1
I have search every where but doesn't seem to get any solution. I have copied my code below.
<?php
$customerid=$_POST['customerid'];
$screeningid=$_POST['screeningid'];
$seatid=$_POST['seatid'];
$priceid=$_POST['priceid'];
$status=$_POST['status'];
$query = "INSERT INTO `booking`(bookingid, customerid, screeningid, seatid, priceid, bookingdate, status)
VALUES(NULL, '". mysql_real_escape_string($customerid)."', '". mysql_real_escape_string($screeningid)."', '". mysql_real_escape_string($seatid)."','". mysql_real_escape_string($priceid)."', 'DateTime()', '". mysql_real_escape_string($status)."')";
$result=mysql_query($query) or die (mysql_error());
// if successfully insert data into database, displays message "Successful".
if($result)
{
echo "<p>success</p>";
echo "<BR>";
}
else
{
echo mysql_error();
}
?>
This is my Form:
<div id="content">
<h2>Enter Booking Details Below</h2>
<form name="reg_form" action="bookingecho.php?action=add type=booking" onsubmit="return validate_reg()" method="POST" >
<table>
<tr>
<td>Customer</td>
<td> <select name="customerid">
<?php
//Perform database query
$query = ("SELECT * FROM customers
ORDER BY customerid DESC");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$customerid = $row['customerid'];
$fname = $row['fname'];
$lname = $row['lname'];
$telephone = $row['telephone'];
//use
echo "<option value>$customerid $fname $lname $telephone</option>";
}
?>
</select></td></tr>
<tr>
<td>Screening</td>
<td> <select name="screeningid">
<?php
//Perform database query
$query = ("SELECT * FROM screening");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$screeningid = $row['screeningid'];
$day = $row['day'];
$screeningdate = $row['screeningdate'];
$filmtitle = $row['filmtitle'];
//use
echo "<option value>$screeningid $day $screeningdate $filmtitle</option>";
}
?>
</select></td></tr>
<tr>
<td>Seat</td>
<td> <select name="seatid">
<?php
//Perform database query
$query = ("SELECT seats.seatid, seats.seatnumber, seats.seatclass
FROM seats
WHERE seatid
NOT IN (SELECT seatid FROM booking
WHERE screeningid = '$screeningid')
ORDER BY `Seats`.`seatid` ASC");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$seatid = $row['seatid'];
$seatnumber = $row['seatnumber'];
$seatclass = $row['seatclass'];
//use
echo "<option value>$seatid $seatnumber $seatclass</option>";
}
?>
</select></td></tr>
<tr>
<td>Concession</td>
<td> <select name="priceid">
<?php
//Perform database query
$query = ("SELECT * FROM price");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$priceid = $row['priceid'];
$concession = $row['concession'];
$cost = $row['cost'];
//use
echo "<option value>$priceid $concession $cost</option>";
}
?>
</select></td></tr>
<tr>
<td>Status</td>
<td>
<input type= radio name="status" value="Booked"> Booked
<input type= radio name="status" value="Reserved"> Reserved
</td>
</tr>
</select></td></tr>
</table>
<p align="center">
<td><input type="submit" name="submit" id= "submit" value="Add"/></td>
<input type="reset" value="Reset Form">
</p>
</form>
</div>
Use intval() for integer values.
Use mysql_real_escape_string on strings, Never for integers.
Single quotes around integer values in a mySQL query is optional.
Because intval() guarantees $customerid is an integer value, the quotes are not necessary and will never generate an error.
I have only included the two lines of code directly related to your customer id. The same likely applies to the other values as well.
$customerid=intval($_POST['customerid']);
$query = "INSERT INTO `booking`
(`bookingid`, `customerid`, `screeningid`,`seatid`,`priceid`, `bookingdate`, `status`)
VALUES(NULL,$customerid,'$screeningid','$seatid','$priceid',CURDATE(),'$status')";
Change:
<input name="status" value="Booked" type="radio"> Booked
<input name="status" value="Reserved" type="radio"> Reserved
To:
<input name="status" value="1" type="radio"> Booked
<input name="status" value="2" type="radio"> Reserved
Always submit integer values greater then zero whenever possible. They are easy to validate. To get the text back:
$statuses = array('unknown','booked','reserved')
$strStatus = $statuses[$status];
UPDATE FOREIGN KEY CONSTRAINT ERROR
A CONSTRAINT ERROR says you do not have a customer record for the added booking table. Or the foreign key is wrong. The foreign key is not needed.
You could combine the customer add, lookup and booking INSERT at the same time.
Rather than some sort of login to create or retrieve the customer record get the booking then during the last step in the booking process just ask for the phone number. Personally I do not care if someone were to query the system with my phone number and found out which seat I have. Some might. But asking for a a login in before getting the booking is a nuisance and a road block to finalizing the booking.
What I did was add the security ID
If they want to secure their seats with a password let it be their choice.
If the record does not exist, then ask for their name AFTER the seats are booked.
//$customerid = intval($_POST['customerid']);
$screeningid = intval($_POST['screeningid']);
$seatid = intval($_POST['seatid']);
$priceid = intval($_POST['priceid']);
$status = intval($_POST['status']);
$fname = mysql_real_escape_string($_POST['status']);
$lname = mysql_real_escape_string($_POST['lname']);
$telephone = intval(preg_replace('/[^D]/','',$_POST['telephone']));
//must have UNIQUE Index on `telephone`
$sql = "INSERT INTO `customer` (`customerid`,`fname`, `lname`, `telephone`)
VALUES(NULL,'', '', $telephone)";
$result = mysql_query($sql);
if(mysql_insert_id()){
$customerid = mysql_insert_id();
}
else{
list($customerid, $fname`, $lname,$id) = mysql_fetch_array(mysql_query(
"SELECT `customerid`,`fname`, `lname`, `telephone`,`id`
FROM `customer` WHERE `telephone`=$telephone"),MYSQL_NUM);
}
$query = "INSERT INTO `booking`
(`bookingid`, `customerid`, `screeningid`,`seatid`,`priceid`, `bookingdate`, `status`)
VALUES(NULL,$customerid,$screeningid,$seatid,$priceid,CURDATE(),$status)";
echo <<<EOT
<p>Your seats are booked.</p>
<form action="update.php" method="post">
<label>Last:</label>
<input type="text" name="lname" value="$lname" />
<br/>
<label>First:</label>
<input type="text" name="fname" value="$fname" />
<br/>
<label>Phone:</label>
<input type="tel" name="telephone" value="$telephone" />
<br/>
<p class="footnote">Security ID is optional</p>
<label>Security ID:</label>
<input type="text" name="id" value="$id" />
<br/>
<input type="hidden" name="phone" value="$telephone" />
<br/>
<div class="footnote">
If you want to keep your booking secure then enter a security id.
<br>If blank, no security ID will be necessary to retrieve your seats in the future.
<br/>This can be any number (e.g. PIN) word, or any characters.
<br/>Maximum 16 characters.</p>
<p>Do NOT use an existing high security password (e.g. your banking password)</p>
<h4>If you would like your seats sent to you via text,<br/>Select your mobile carrier<br/>This will also verify you entered the correct phone number</h4>
</div>
<label>Mobile Carrier</label>
<select>
<option value="">No Text / Land Line</option>
<option value="#message.alltel.com">Alltel</option>
<option value="#paging.acswireless.com">Ameritech</option>
<option value="#mmode.com">ATT Wireless</option>
<option value="#bellsouth.cl">Bellsouth</option>
<option value="#myboostmobile.com">Boost</option>
<option value="#mobile.celloneusa.com">CellularOne</option>
<option value="#mobile.mycingular.com">Cingular</option>
<option value="#sms.edgewireless.com">Edge Wireless</option>
<option value="#mymetropcs.com">Metro PCS</option>
<option value="#messaging.nextel.com">Nextel</option>
<option value="#mobile.celloneusa.com">O2</option>
<option value="#mobile.celloneusa.com">Orange</option>
<option value="#qwestmp.com">Qwest</option>
<option value="#pcs.rogers.com">Rogers Wireless</option>
<option value="#messaging.sprintpcs.com">Sprint PCS</option>
<option value="#teleflip.com">Teleflip</option>
</optgroup>
<option value="#msg.telus.com">Telus Mobility</option>
<option value="#email.uscc.net">US Cellular</option>
<option value="#vtext.com">Verizon</option>
</select>
<br/>
<input type="submit" value="Save Changes" />
</form>
EOT;
FORM SNIPPET
label {
width: 5em;
display: inline-block;
text-align: right;
}
.footnote {
margin: .5em 0 .5em 5em;
}
input[type="submit"] {
margin: 1em 6em;
}
h4 {
margin-bottom: 0;
}
<p>Your seats are booked.</p>
<form action="update.php" method="post">
<label>Last:</label>
<input type="text" name="lname" value="$lname" />
<br/>
<label>First:</label>
<input type="text" name="fname" value="$fname" />
<br/>
<label>Phone:</label>
<input type="tel" name="telephone" value="$telephone" />
<br/>
<p class="footnote">Security ID is optional</p>
<label>Security ID:</label>
<input type="text" name="id" value="$id" />
<br/>
<input type="hidden" name="phone" value="$telephone" />
<br/>
<div class="footnote">
If you want to keep your booking secure then enter a security id.
<br>If blank, no security ID will be necessary to retrieve your seats in the future.
<br/>This can be any number (e.g. PIN) word, or any characters.
<br/>Maximum 16 characters.</p>
<p>Do NOT use an existing high security password (e.g. your banking password)</p>
<h4>If you would like your seats sent to you via text,<br/>Select your mobile carrier<br/>This will also verify you entered the correct phone number</h4>
</div>
<label>Mobile Carrier</label>
<select>
<option value="">No Text / Land Line</option>
<option value="#message.alltel.com">Alltel</option>
<option value="#paging.acswireless.com">Ameritech</option>
<option value="#mmode.com">ATT Wireless</option>
<option value="#bellsouth.cl">Bellsouth</option>
<option value="#myboostmobile.com">Boost</option>
<option value="#mobile.celloneusa.com">CellularOne</option>
<option value="#mobile.mycingular.com">Cingular</option>
<option value="#sms.edgewireless.com">Edge Wireless</option>
<option value="#mymetropcs.com">Metro PCS</option>
<option value="#messaging.nextel.com">Nextel</option>
<option value="#mobile.celloneusa.com">O2</option>
<option value="#mobile.celloneusa.com">Orange</option>
<option value="#qwestmp.com">Qwest</option>
<option value="#pcs.rogers.com">Rogers Wireless</option>
<option value="#messaging.sprintpcs.com">Sprint PCS</option>
<option value="#teleflip.com">Teleflip</option>
</optgroup>
<option value="#msg.telus.com">Telus Mobility</option>
<option value="#email.uscc.net">US Cellular</option>
<option value="#vtext.com">Verizon</option>
</select>
<br/>
<input type="submit" value="Save Changes" />
</form>
The error message means you are getting an "empty string" ('') for customerid, which simply means that your first chunk of code is not getting any value at all for that field when the form is submitted.
Here is the problem:
echo "<option value>$customerid $fname $lname $telephone</option>";
The values between <option> and </option> are what will be displayed to the end-user, but they will not be submitted with your form, which means they won't be available to that first chunk of code.
To submit the customerid, you have to put it into the value part:
echo "<option value=$customerid>$customerid $fname $lname $telephone</option>";
You placed apostrophes around $customerid (and other non-string values) when it is actually an integer inside your database. Delete the apostropes (') around all values that are meant to be integers in your database (I have a feeling that is the case for many of your variables). Also please organize your code because it was extremely difficult to look at it without crying :)
<?php
$customerid=mysql_real_escape_string($_POST['customerid']);
$screeningid=$_POST['screeningid'];
$seatid=mysql_real_escape_string($_POST['seatid']);
$priceid=mysql_real_escape_string($_POST['priceid']);
$status=mysql_real_escape_string($_POST['status']);
$query = "INSERT INTO `booking`(bookingid, customerid,
screeningid, seatid, priceid, bookingdate, status)
VALUES (NULL, ". $customerid.", ". $screeningid.", ".
$seatid.", ".$priceid.", 'DateTime()', '".$status."')";
$result=mysql_query($query) or die (mysql_error());
// if successfully insert data into database, displays message "Successful".
if($result)
{
echo "<p>success</p><br>";
}
else
{
echo mysql_error();
}
?>
Also note, DateTime() is a php function, not an SQL command. I left it in the previous code but be aware that you should fix that error.
Let me know if this worked for you.

Using AJAX How can I generate selections for a dropdown menu based on records available in a database?

Using AJAX How can I generate selections for a dropdown menu based on records available in a database?.
How can then use these selections to prefill a form with record/row data from a database when selected?
Heres a mock up I created of what I'm trying to do:
http://oi58.tinypic.com/2urb2ae.jpg
PHP FILE: contact_form.php
-----------------------------------------------------------
<?php
define('DB_NAME', 'xxx');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'xxx');
define('DB_HOST', 'xxx');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$connection){
die('Database connection failed: ' . mysqli_connect_error());
}
$db_selected = mysqli_select_db($connection, DB_NAME);
if(!$db_selected){
die('Can\'t use ' .DB_NAME . ' : ' . mysqli_connect_error());
}
echo 'Connected successfully';
if (isset($_POST['itemname'])){
$itm = $_POST['itemname'];
}
else {
$itm = '';
}
if($_POST['mile']){
$mi = $_POST['mile'];
}else{
echo "Miles not received";
exit;
}
if($_POST['email']){
$email = $_POST['email'];
}else{
echo "email not received";
exit;
}
$sql = "INSERT INTO seguin_orders (itemname, mile, email)
VALUES ('$itm', '$mi', '$email')";
if (!mysqli_query($connection, $sql)){
die('Error: ' . mysqli_connect_error($connection));
}
CONACT FORM: formz.php
------------------------------------------------------------------------------
<html>
<header>
</header>
<body>
<form action="/demoform/contact_form.php" class="well" id="contactForm" method="post" name="sendMsg" novalidate="">
<big>LOAD PAST ORDERS:</big>
<select id="extrafield1" name="extrafield1">
<option value="">Please select...</option>
<?php
$email = $_POST['email'];
$query="select * from tablename WHERE email={$_POST['email']}";
$res=mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($res))
{
?>
<option value="<?php echo $row['fieldname']; ?>"><?php echo $row['fieldname']; ?></option>
<?php
}
?>
</select>
</br>
<input type="text" required id="mile" name="mile" placeholder="Miles"/>
</br>
<input id="email" name="email" placeholder="Email" required="" type="text" value="demo#gmail.com" readonly="readonly"/>
</br>
<input id="name" name="itemname" placeholder="ITEM NAME 1" required="" type="text" />
</br>
<input type="reset" value="Reset" />
<button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
Using an exemple, let's assume you want to fill the "name" select based on the option selected at the "gender" select:
<select name="gender" id="gender">
<option value="m">Male</select>
<option value="f">Female</select>
</select>
When nothing is selected yet, the "name" select is empty:
<select name="name" id="name">
<option value="NULL">Please select a gender first</option>
</select>
So, what you gotta do is: when the gender select got some selection, you populate the name select with values based on the gender select option.
$(document).ready(function() {
$('select#gender').change(function(){
$('select#name').load('LOAD_NAMES_BASED_ON_GENDER.php?gender='+$(this).val());
});
});
And your PHP file responsible for loading the names based on gender should look like:
$gender = $_GET['gender'];
$list = // the way you retrieve your list of names from your DB
And then you loop this $list into an list of options, such like:
foreach($list as $key=>$value)
echo '<option value="$key">$value</option>';
This simple.
PS: the load() function is kind of an alias for the $.ajax request, given that the only purpose here is to retrieve data.

Categories