php mysql based on user input form - php

I am having trouble using a checkbox to select one or multiple fields of data for PHP/AJAX to process and display. I have the PHP/AJAX working great on my <select>s but as soon as I try setting up the checkbox all hell breaks lose.
I also am very unsure on how to further prevent SQL injection on the site so if anyone could fill me in a little more about this I would GREATLY appreciate it! I read the link I was provided and just don't understand how bid_param or PDO works exactly.
The ajax script:
(I can't seem to insert the ajax/js so I'll leave a link to the live site)
Link to Agent search page
My php page that displays the data:
<div id="bodyA">
<h1>Find a Local OAHU Agent.</h1>
<!-- This is where the data is placed. -->
</div>
<div id="sideB">
<div class="sideHeader">
<em>Advanced Search</em>
</div>
<form class="formC">
<label for="last">Last Name</label><br />
<select id="last" name="Last_Name" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT Last_Name FROM `roster` ORDER BY Last_Name ASC;");
echo '<option value="">' . 'Select an Agent' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['Last_Name'].'">'.$row['Last_Name'].'</option>';
}
?>
</select>
<label for="company">Company</label><br />
<select id="company" name="users" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT Company FROM `roster` ORDER BY Company ASC;");
echo '<option value="">' . 'Select a Company' .'</option>';
while ($row = mysqli_fetch_array($result)) {
if ($row['Company'] == NULL) {
} else {
echo '<option value="'.$row['Company'].'">'.$row['Company'].'</option>';
}
}
?>
</select>
<label for="WorkCity">City</label><br />
<select id="WorkCity" name="WorkCity" onChange="showUser(this.value)" value="city">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT WorkCity FROM `roster` ORDER BY WorkCity ASC;");
echo '<option value="">' . 'Select a City' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['WorkCity'].'">'.$row['WorkCity'].'</option>';
}
?>
</select>
<label for="WorkZipCode">Zip Code</label><br />
<select id="WorkZipCode" name="WorkZipCode" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT WorkZipCode FROM `roster` ORDER BY WorkZipCode + 0 ASC;");
echo '<option value="">' . 'Select a Zip Code' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['WorkZipCode'].'">'.$row['WorkZipCode'].'</option>';
}
?>
</select>
<label for="agent">Agent Expertise</label><br />
<label for="ancillary"><input type="checkbox" value="Ancillary" name="Ancillary[]" id="ancillary" />Ancillary</label><br />
<label for="smallgroup"><input type="checkbox" value="Smallgroup" name="Smallgroup[]" id="smallgroup" />Small Group</label><br />
<label for="largegroup"><input type="checkbox" value="LargeGroup" name="LargeGroup[]" id="largegroup" />Large Group</label><br />
<label for="medicare"><input type="checkbox" value="Medicare" name="Medicare[]" id="medicare" />Medicare</label><br />
<label for="longterm"><input type="checkbox" value="LongTerm" name="LongTerm[]" id="longterm" />Long Term Care</label><br />
<label for="individual"><input type="checkbox" value="Individual" name="Individual[]" id="individual" />Individual Plan</label><br />
<label for="tpa"><input type="checkbox" value="TPASelfInsured" name="TPASelfInsured[]" id="tpa" />TPA Self Insured</label><br />
<label for="ppaca"><input type="checkbox" value="CertifiedForPPACA" name="CertifiedForPPACA[]" id="ppaca" />Certified for PPACA</label><br />
</form>
</div>
My php page that pulls the info and places it into a container on the page:
$q = (isset($_GET['q'])) ? $_GET['q'] : false; // Returns results from user input
include 'datalogin.php'; // PHP File to login credentials
$sql="SELECT * FROM `roster` WHERE Company = '".$q."' OR Last_Name = '".$q."' OR WorkCity = '".$q."' OR WorkZipCode = '".$q."' ORDER BY Last_Name ASC";
$result = mysqli_query($con,$sql) // Connects to database or die("Error: ".mysqli_error($con));
echo "<h1>" . "Find a Local OAHU Agent." . "</h1>";
while ($row = mysqli_fetch_array($result)) { // Gets results from the database
echo "<div class='agentcon'>" . "<span class='agentn'>" . "<strong>".$row['First_Name'] . " " .$row['Last_Name'] . "</strong>" . "</span>" . "" . "<span class='email'>".$row['Email'] . "</span>" . "" ."<div class='floathr'></div>";
if ($row['Company'] == NULL) {
echo "<p>";
}
else {
echo "<p>" . "<strong>" .$row['Company'] . "</strong>" . "<br>";
}
echo $row['WorkAddress1'] . " " .$row['WorkCity'] . "," . " " .$row['WorkStateProvince'] . " " .$row['WorkZipCode'] . "<br>";
if ($row['Work_Phone'] !== NULL) {
echo "<strong>" . "Work" . " " . "</strong>" .$row['Work_Phone'] . "<br>";
}
if ($row['Fax'] !== NULL) {
echo "<strong>" . "Fax" . " " . "</strong>" .$row['Fax'] . "<br>";
}
echo "<strong>" . "Agent Expertise:" . "</strong>";
if ($row['Ancillary'] == 1) {
echo " " . "Ancillary" . "/";
}
if ($row['SmallGroup'] == 1) {
echo " " . "Small Group" . "/";
}
if ($row['IndividualPlans'] == 1) {
echo " " . "Individual Plans" . "/";
}
if ($row['LongTermCare'] == 1) {
echo " " . "Long Term Care" . "/";
}
if ($row['Medicare'] == 1) {
echo " " . "Medicare" . "/";
}
if ($row['LargeGroup'] == 1) {
echo " " . "LargeGroup" . "/";
}
if ($row['TPASelfInsured'] == 1) {
echo " " . "TPA Self Insured" . "/";
}
if ($row['CertifiedForPPACA'] == 1) {
echo " " . "Certified For PPACA";
}
echo "</p>" . "</div>";
}
mysqli_close($con);
?>
I appreciate any and all help on this topic! Any time I add the checkbox values to my php file it ends up displaying everyone in the database for all fields in the form.
I am also trying to prevent sql injection on this but how can a user do this if I don't have a field the user can input text into?
EDIT As of today I gave a try with using jQuery to activate the checkboxes and then call some AJAX.
Here is the script I wrote and it is pulling an agent, just not everyone that has that "expertise".
$('input').click(function() {
$.ajax({
url: "process.php",
data: { value: 1},
success: function (data) {
$('#bodyA').html(data);
}
});
});

Here's a quick example of something I recently worked on in which I needed to loop through multiple checkboxes and pass those values into a SQL statement. Although this example happens on a button click, hopefully its something along the lines of what you are trying to accomplish, or at least at start... :)
<?php
$array = array();
if (isset($_POST['medicare'])) {
foreach ($_POST['medicare'] as $value) {
array_push($array, $value);
}
}
// this will return the value of each selected checkbox, separating each with a comma
$result = implode(",", $array);
// if you want to loop through each individually (for example pass each into a SQL statement)
foreach ($_POST['medicare'] as $value) {
// Do your SQL here
// $value will be the value of each selected checkbox (Smallgroup, Largegroup, etc.)
$sql = "insert into tablename(fieldname) values ('$value')"; // just an example
}
?>
<input type="checkbox" name="medicare[]" id="smallgroup" value="Smallgroup" />
<label for="smallgroup">Small Group</label>
<br />
<input type="checkbox" name="medicare[]" id="largegroup" value="Largegroup" />
<label for="largegroup">Large Group</label>
<br />
<input type="checkbox" name="medicare[]" id="medicare" value="Medicare" />
<label for="medicare">Medicare</label>
<br />
<input type="checkbox" name="medicare[]" id="individualplan" value="IndividualPlan" />
<label for="individualplan">Individual Plan</label>
<br />
<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
UPDATE
Instead of setting one variable, try setting a variable for each select control and putting your SQL statement in a foreach loop. I just tested this with some dummy data and didn't have any issues with it.
<?php
$lastname = (isset($_GET['Last_Name'])) ? $_GET['Last_Name'] : false;
$users = (isset($_GET['users'])) ? $_GET['users'] : false;
$workCity = (isset($_GET['WorkCity'])) ? $_GET['WorkCity'] : false;
$WorkZipCode = (isset($_GET['WorkZipCode'])) ? $_GET['WorkZipCode'] : false;
foreach ($_GET['medicare'] as $value) {
//echo $value;
$sql="SELECT * FROM roster WHERE Company = '$users' OR Last_Name = '$lastname' OR WorkCity = '$workCity' OR WorkZipCode = '$WorkZipCode' OR Ancillary = '$value' ORDER BY Last_Name ASC";
}
...continue as you were...
?>

I DID IT!! Wohoo! I ended up just making a separate php page called expertise.php to process the checkboxs using jquery/ajax.
The jQuery that achieved this: (Thank god I went onto the jQuery website to look up functions!)
$('input').click(function() {
$.ajax({
url: "expertise.php",
data: { value: 1},
success: function (data) {
$('#bodyA').html(data);
}
});
});
The PHP page is the same as my process.php page except for the sql:
$sql="SELECT * FROM `roster` WHERE Ancillary = '1' AND SmallGroup = '1' AND CertifiedForPPACA = '1' ORDER BY Last_Name ASC";
If anyone would enlighten me more on making this better protected against sql injections, feel free to!
Agent Search Page
Well I at least got both parts of the search working but a new problem has arose :p
Now in the sql I can use AND or OR, with AND it pulls only agents that have everyone of those expertise and with OR it seems to pull everyone. Any ideas?

Related

Add input field based on drop down list using php variables

I'm in the middle of making a simple inventory system for keeping track of equipment going in and out of our doors. The inventory is stored in MYSQL, with a table looking like this: id name storage used location_storage location
This is all fun and games when I create a simple form with PHP, so it stays dynamic with the content from the server. I can update all values with no problem.
But for the sake of simplicity I'm looking into having a drop down menu, with a button, that creates/shows input fields in a form. The reason being is that I will have many rows in my table in the upcoming time. As the forms earlier have been made from server information, I will also need the scripts to be dynamic. Right now I'm stuck thinking about what I should do.
As of now, my code for the bits look like this:
"Static" PHP form:
<form action="<?php $_PHP_SELF ?>" method="POST">
<?php
//conn stuff
$sql = "SELECT id, name, storage, used, location FROM inventory";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo ' ' . $row["id"]. ' ' . $row["name"]. '<input type="text" name="newamount[' . $row["id"]. ']" />';
echo '<br>';
}
} else {
echo "0 results";
}
$conn->close();
?>
<input type="submit" name="checkout" value="Check out"/>
<input type="submit" name="checkin" value="Check in"/>
</form>
Check in PHP (check out is identical except for change of + and minus):
if(isset($_POST['sjekkinn'])){
//conn stuff
mysql_select_db( 'experimental' );
$newamount = $_POST['newamount'];
foreach($newamount as $key => $value){
$sql = "UPDATE inventory ". "SET storage = (storage + $value), used = (used - $value)". "WHERE ID = $key " ;
if (empty($value)) continue;
$retval = mysql_query( $sql, $conn );}
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully!<br>";
header("Refresh:1");
mysql_close($conn);
}
Those are all working great, but I would like to use something like the code below for a neater setup... Anyone got any advice?
Drop down list generated from MYSQL:
<form action="#" method="post">
<select name="selectinventory">
<?php
//conn stuff
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);
while ($row = $result->fetch_array()){
echo '<option value="' . $row["id"]. '">' . $row['name'] . '</option>';
}
?>
</select>
<input type="submit" name="submit" value="Add line">
</form>
Okay, so I found my own solution.
I ended up using my table-populated drop down list as I showed you in the last code box of the question. What came to my mind was that I could simply use the jQuery show/hide function.
What I did was to make a script that told (in "readable") div 'x' to show and move when option 'x' was selected and button clicked. I will show you my complete code in the end.
That way I could have my input fields each created inside a div from my table (the same that populated the drop down list), so I could manage them easier (probably possible to do it easier - but if it ain't broken, don't fix it). These were created outside the form. When I then click the previously mentioned button, the div will move inside the form. The next one I select will end up UNDER the previous one, instead of just showing up in table-order.
Feel free to shout any questions!
Here's the complete code:
<form action="<?php $_PHP_SELF ?>" method="post">
<select name="selectinventory" id="selectinventory">
<option selected="selected">Choose one</option>
<?php
//conn stuff
$sql = "SELECT id, name FROM inventory";
$result = $conn->query($sql);
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);
while ($row = $result->fetch_array()){
echo '<option value="' . $row["id"]. '">' . $row['name'] . '</option>';
}?>
</select>
<div id="btn">Add line</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
$("#" + $("#selectinventory").val()).show();
$("#" + $("#selectinventory").val()).appendTo($(".selecteditems"));
});
});
</script>
<?php
//conn stuff
$sql = "SELECT id, name FROM inventory";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div style="display:none" id="' . $row["id"]. '"> ' . $row["id"]. ' ' . $row["name"]. '<input type="text" name="newamount[' . $row["id"]. ']" /><br></div>
';
}
} else {
echo "0 results";
}
$conn->close();
?>
<form action="<?php $_PHP_SELF ?>" method="POST" name="isthisthearrayname">
<div class="selecteditems">
</div>
<input type="submit" name="checkout" value="Check out"/>
<input type="submit" name="checkin" value="Check in"/>
</form>

how to edit a record from MySQL database

this is my first post!
First off, I have my code which outputs a table on index.php. At the end I have an edit link which takes me to the edit.php page:
if ($result->num_rows > 0) {
echo "<p><table><tr><th>ID</th><th>Film Name</th><th>Producer</th><th>Year Published</th><th>Stock</th><th>Price</th><th>Function</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["ID"]."</td><td>".$row["FilmName"]."</td><td>".$row["Producer"]."</td><td>".$row['YearPublished']."</td><td>".$row['Stock']."</td><td>".$row['Price']."</td><td>"."Edit / Delete"."</td></tr></p>";
}
echo "</table>";
edit.php (first there is the form):
$query = "SELECT * FROM ProductManagement WHERE ID=" . $_GET["ID"] . ";"; // Place required query in a variable
$result = mysqli_query($connection, $query); // Execute query
if ($result == false) { // If query failed
echo "<p>Getting product details failed.</p>";
} else { // Query was successful
$productDetails = mysqli_fetch_array($result, MYSQLI_ASSOC); // Get results (only 1 row
// is required, and only 1 is returned due to using a primary key (id in this case) to
// get the results)
if (empty($productDetails)) { // If getting product details failed
echo "<p>No product details found.</p>"; // Display error message
}
}
?>
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductCostPrice">ID</label>
<input id="updateFormProductCostPrice" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text" value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductDescription">Producer</label>
<textarea rows="4" cols="50" id="Producer"
name="productDescription"><?php echo $productDetails["Producer"]; ?></textarea>
</div>
<div>
<label for="updateFormProductPrice">Year Produced</label>
<input id="updateFormProductPrice" name="YearProduced" type="text"
value="<?php echo $productDetails["YearProduced"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductEan">Price:(&#163)</label>
<input id="updateFormProductEan" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
</body>
Then there is the php code to update the record (edit.php continued):
if (((!empty($_GET["mode"])) && (!empty($_GET["id"]))) && ($_GET["mode"] == "update")) { // If update
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) { // If update form submitted
// Check all parts of the form have a value
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearProduced"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
// Create and run update query to update product details
$query = "UPDATE products "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearProduced = '" . $_POST["YearProduced"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE id=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) { // If query failed - Updating product details failed (the update statement failed)
// Show error message
echo "<p>Updating failed.</p>";
} else{ // Updating product details was sucessful (the update statement worked)
// Show success message
echo "<p>Updated</p>";
}
}
}
}
I do apologise that there is a lot of code here. Basically when I click edit in the table on the home page, I would expect it to load up the data for the respective row selected so I can update it.
Currently, when I click the 'edit' link, it loads the edit page and it has the blank fields and says "getting product details failed". It would be great if it can retrieve the data for the respective row selected. Can someone help please? Thanks!
In edit.php file $_GET["ID"] is empty because there is no ID value in your link so query returns no results.
Also in your last file you have $_GET["id"] which is different from the value you use ($_GET["ID"]).
Try this:
echo "
<tr>
<td>".$row["ID"]."</td>
<td>".$row["FilmName"]."</td>
<td>".$row["Producer"]."</td>
<td>".$row['YearPublished']."</td>
<td>".$row['Stock']."</td>
<td>".$row['Price']."</td>
<td>Edit
<td>Delete
</tr>";
Also you are SQL Injection vulnerable. You can combine mysqli with prepared statements to avoid this.

Database not updating correctly in PHP / MySQL [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I've got a database with a Users table which I'm trying to update.
Currently I have customers.php, which displays form fields with the user information so it can be updated.
This form points to edit_customer_processor.php , which takes the new values, puts them into a MYSQL query... and then despite the query working correctly when I query the DB via the PHPMyAdmin command line, the record doesn't update.
customers.php
<?php
session_start();
if(!$_SESSION["logged_in"]){
header("location:home.php");
die;
}
?>
<?php include 'header.html'; ?>
<div id='maincontent'>
<?php
if (isset($_GET["id"])){
$customer_id = $_GET["id"];
require_once('config.php');
$customer_query = "SELECT * FROM customer WHERE customer_id = $customer_id";
$customer_results = mysql_query($customer_query, $conn);
if (!$customer_results) {
die ("Error selecting car data: " .mysql_error());
}
else {
while ($row = mysql_fetch_array($customer_results)) {
echo "<h3>Edit Customer</h3>";
echo "<FORM method='post' action='edit_customer_processor.php'>";
echo '<p> Name: <input type="text" name="name" size = "40" value=' . $row[name] . '></p>';
echo '<p> Address: <input type="text" name ="address" size="40" value=' . $row[address] . '></p>';
echo '<p> Email: <input type="text" name="email" value=' . $row[email] . '></p>';
echo '<p> Phone: <input type ="text" name="phone" size="20" value=' . $row[phone] . '></p>';
echo '<input type ="hidden" name="customer_id" value="' . $row[customer_id] . '">';
echo '<input type ="hidden" name="formtype" value="edit_customer">';
echo '<input type="submit" name="submit" value= "Update">';
echo '</form>';
}
}
} else {
// If there isn't an ID, display the New Customer form and all customers below, with links
// to their edit pages.
echo "<h3>Enter new customer information and submit.</h3>";
echo "<FORM method='post' action='new_customer_processor.php'>";
echo '<p> Name: <input type="text" name="name" size = "40"></p>';
echo '<p> Address: <input type="text" name ="address" size="40"></p>';
echo '<p> Email: <input type="text" name="email"></p>';
echo '<p> Phone: <input type ="text" name="phone" size="20"></p>';
echo '<input type ="hidden" name="formtype" value="new_customer">';
echo '<input type="submit" name="submit" value= "Submit">';
echo '<input type ="reset" name="reset" value ="Reset">';
echo '</form>';
require_once('config.php');
echo "<h3>Current Customers</h3>";
$query = "SELECT * FROM customer";
$results = mysql_query($query, $conn);
if (!$results) {
die ("Error selecting customer data: " .mysql_error());
}
else {
// In the absence of an ID, all customers will be displayed down
// the bottom of the page
while ($row = mysql_fetch_array($results)) {
echo "<a href=customers.php?id=";
echo $row[customer_id];
echo "><p> $row[name] </p></a>";
echo "<p> $row[address] </p>";
echo "<p> $row[phone] </p>";
echo "<p> $row[email] </p>";
}
}
}
?>
Back to Customers Page
</div>
<?php include 'footer.html' ?>
edit_customer_processor.php
<?php include 'header.html' ?>
<div id="maincontent">
<?php
// Pulling in hidden customer ID from post value
$mysqli = new mysqli( 'localhost', 'root', 'root', 'w_c_a' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// Insert our data
$sql = mysql_query("UPDATE customer
SET name = '".mysql_real_escape_string($_POST['name'])."',
address = '".mysql_real_escape_string($_POST['address'])."',
phone = '".mysql_real_escape_string($_POST['phone'])."',
email = '".mysql_real_escape_string($_POST['email'])."'
WHERE customer_id='".mysql_real_escape_string($_POST['customer_id'])."'");
$update = $mysqli->query($sql);
echo "Customer updated: ";
echo "<a href=customers.php?id=" . $_POST['customer_id'] . ">";
echo "Back to Edit Customer</a>";
?>
</div>
<?php include 'footer.html' ?>
And when I echo the MYSQL query, I get:
UPDATE customer SET name = 'Kellyassdsa', address = 'ads', phone = '0260123123', email = 'asdasd' WHERE customer_id='1'
Which works when I put it in PHPMyAdmin.
I know it'll be some boneheaded little mistake, but I've been trying to get this work for ages now. Any ideas?
Maybe your program just can't connect to your MySQL database.
$customer_results = mysql_query($customer_query, $conn);
I can't see where you gave a value to the var $conn.
If the problem is connection problem then we might need your database info like the name of your table in PhpMyAdmin.
your problem is...
$sql = mysql_query(..);
$update = $mysqli->query($sql);
it should be
$sql = 'UPDATE ...';
$update = $mysqli->query($sql);
i think problem occurs due to line break. pleas make a query in single line without line break.
$sql = mysql_query("UPDATE customer SET name = '".mysql_real_escape_string($_POST['name'])."',address = '".mysql_real_escape_string($_POST['address'])."', phone = '".mysql_real_escape_string($_POST['phone'])."', email = '".mysql_real_escape_string($_POST['email'])."' WHERE customer_id='".mysql_real_escape_string($_POST['customer_id'])."'");
Hope this helps..

PHP show data from Oracle database in a listbox

I want to show data from a Oracle database into a listbox.
, but I don't no how to do that.
Now I'm using a textbox and that works good.
This is my HTML code
<form name="form1" method="get" action="Get_opdracht.php"
Opdrachtnummer: <br /> <input id="Password1" type="number" name="nummer1" required="required"/>
<input type="submit" name="submit1" value="Zoeken" />
<hr />
</form>
PHP code (get_opdracht.php)
// database connect
$conn = oci_connect('username', 'password', 'connect');
// variable textbox
$username = $_GET['nummer1'];
// SELECT query
$array = oci_parse($conn, "SELECT * FROM OPD_VW, MDW_VW WHERE OPD_OPDRACHTNUMMER = '$username'");
$query = oci_execute($array);
//show data on page
while (($row = oci_fetch_array($array, OCI_BOTH)) != false) {
echo "<h1>Opdrachtnummer: " . $row['OPD_OPDRACHTNUMMER'] . "</h1><p> <b>Status: </b>" . $row['OPD_STATUS'] . "<p><b>Registratiedatum: </b>" . $row['OPD_REGISTRATIEDATUM'] . "<p><b>Einddatum: </b>" . $row['OPD_EINDDATUM'] . "<p><b>BTW tarief: </b>". $row['OPD_BTW_TARIEF'] . "<p><b>Totale contractsom: €</b>" . $row['OPD_TOTALE_CONTRACTSOM'] . "<p><b>Percentage gerealiseerd: </b>" . $row['OPD_PERCENTAGE_GEREALISEERD'] . "%";
oci_free_statement($array);
oci_close($conn);
To create a listbox you need to use the select multiple as shown below.
<select name="myselect" multiple="multiple">
<option value="value">OPTION</option>
<option value="value">OPTION</option>
</select>

How do I select value from DropDown list in PHP??? Problem

I want to know the error in this code
The following code retrieves the names of the members of the database query in the
dropdownlist
But how do I know who you selected.... I want to send messages only to the members that selected form dropdown list
<?php
include ("connect.php");
$name = $_POST['sector_list'];
echo $name ;
?>
<form method="POST" action="" >
<input type="hidden" name="sector" value="sector_list">
<select name="sector_list" class="inputstandard">
<option size ="40" value="default">send to </option>
<?php
$result = mysql_query('select * from members ')
or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo '<option size ="40" value=" '. $row['MemberID'] . '" name="' . $row['MemberName']. '">' . $row['MemberName']. '</option>';
}
?>
</select>
</form>
I hope somebody can help me
This should do the trick.
<?php
$member_id = intval($_POST['sector_list']);
if($member_id == 0) {
// Default choice was selected
}
else {
$res = mysql_query("SELECT * FROM members WHERE MemberID = $member_id LIMIT 1");
if(mysql_num_rows($res) == 0) {
// Not a valid member
}
else {
// The member is in the database
}
}
?>
<form method="post" action="">
<input type="hidden" name="sector" value="sector_list">
<select name="sector_list" class="inputstandard">
<option value="0">send to</option>
<?php
$result = mysql_query('SELECT * from members') or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="' . $row['MemberID'] . '">' . $row['MemberName']. '</option>';
}
?>
</select>
</form>
To get an input to change when you select someone try this:
<select onchange="document.getElementById('text-input').value = this.value;">
<!-- Options here -->
</select>
<input type="text" id="text-input">

Categories