Generate data in form from drop down list - php

been searching around and can't seem to find the answer as yet, the plan is to have 2 drop down lists which will be model and SKU that list data from sql which is fine i got that working but when an item is selected, i need to populate input fields like price, RRP, discount rate and anything else required.
So i have cleaned up what i had into a sample and i need to build a function that when the drop down option is selected another sql command can execute to obtain the rest of the data from that item and fill in other forms. If a sample can be worked out i can expand it across the rest of the giant form that i have prepped.
Once this issue can be worked out i can then work on the php/mysql processing of the data and generate the PDF at the end. But until i can get all the data in the fields im kinda stuck and would appreciate any idea's.
<?php
//connect to the database
$db=mysql_connect ("localhost", "root", "toor") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("db");
// Option 1
$sql="SELECT * FROM `cctv` ORDER BY `cctv`.`SAPCode` ASC ";
$q=mysql_query($sql);
echo "<select name=\"q_option1\">";
echo "<option size =30 ></option>";
while($row = mysql_fetch_array($q))
{
echo "<option value='".$row['SAPCode']."'>".$row['SAPCode']."</option>";
}
echo "</select>";
?>
<form id="form1" name="form1" method="post" action="">
<label for="price">price</label>
<input type="text" name="price" id="price" />
</form>

Related

Populate select field from SQL, use select to update database

I am practicing with developing a little bit but I stumbled upon a small issue which I just cannot get my head around. The goal is simple: users fill out a form and are then redirected to either the results page or the form. From the results page, users can navigate to a page where they can edit any records that match the time period and the name they enter.
Example: User 1 adds a car named 'Banshee', is redirected to the results page, sees the 'Banshee' car but then decides he wants the color to be different. The user navigates to the update page and is able to either type in 'Banshee' or select 'Banshee' from a dropdown list. The first option works but the latter is the solution I'm looking for.
Currently I have the following form (this is just the part that matters):
<form method="post" name="input" action="edittest.php" >
<?php
include("/var/www/html/includes/sqlconnecttest.php");
$db=mysqli_select_db($connect,$database)
or die("Could not connect to the database");
$query = "SELECT * FROM cars WHERE datetime > DATE_SUB(CURDATE(), INTERVAL 5 DAY);";
$sql = mysqli_query($connect,$query);
?>
<p>
<label>Name</label>
<select name="name" form="input" required>
<?php
echo "<option value=\"\" disabled=\"disabled\" selected=\"selected\" style=\"display\:none\"></option>";
while ($row = mysqli_fetch_array($sql)){
echo "<option value=\"name\">" . $row['name'] . "</option>";
}
?>
</select>
</p>
The connection is done through the following PHP code:
<?php
include("/var/www/html/includes/sqlconnecttest.php");
$db = new mysqli("$host","$user","$pass","$database");
$name=$_POST['name'];
$stmt = $db->prepare("UPDATE cars
SET color=?, airco=?, tires=?, rims=?, price=?, engine=?, remarks=?
WHERE name='$name' AND datetime > DATE_SUB(CURDATE(), INTERVAL 5 DAY);");
$stmt->bind_param('ssssiss', $ccolor, $cairco, $ctires, $crims, $cprice, $cengine, $cremarks);
$color=$_POST['color'];
$airco=$_POST['airco'];
$tires=$_POST['tires'];
$rims=$_POST['rims'];
$price=$_POST['price'];
$engine=$_POST['engine'];
$remarks=$_POST['remarks'];
$ccolor=htmlspecialchars($color,ENT_QUOTES);
$cairco=htmlspecialchars($airco,ENT_QUOTES);
$ctires=htmlspecialchars($tires,ENT_QUOTES);
$crims=htmlspecialchars($rims,ENT_QUOTES);
$cprice=htmlspecialchars($price,ENT_QUOTES);
$cengine=htmlspecialchars($engine,ENT_QUOTES);
$cremarks=htmlspecialchars($remarks,ENT_QUOTES);
if ($stmt->execute()) {
header("Location: redtest.php");
}
?>
The issue is as follows: when I use the above posted HTML form with the while-loop populating the options, the update page doesn't do anything. No errors, no updates it just performs the action (open edittest.php).
However, when I replace the above posted dropdown menu with this simple textfield, it works fine. Whatever I type in the textfield, it uses it in the update query.
<p>
<label>Name</label>
<input type="text" maxlength="50" name="name" required />
</p>
I've got the feeling that the PHP code breaks the connection between the select-field and the rest of the form.
I see two issues with your select. First you have what appears to be a default value that you're then hiding with display:none. You're also setting the same value for every option. I believe this is what you're trying to do.
<select name="name" form="input" required>
<option value=""></option>
<?php
while ($row = mysqli_fetch_array($sql)){
echo "<option value=\"". $row['name'] ."\">" . $row['name'] . "</option>";
}
?>
</select>

I really need an advice with multiple checkboxes + textboxes in PHP

I'm trying to make a mobile repair website and I am currently stuck a little. From my tiny admin panel I can add a "brand", a "service" e.g. repair a display, and add a phone model. The problem is with adding a phone model. Just stay with me. Right now I am adding services with price attached, so there can be "Fix display for 100", "Fix display for 200" etc. So after adding a lot of "services" you can add a phone model and check the services withing a checkbox list. This uses too much space, so I'm stuck with the problem of having just the service names, and inputing the price to the service later (when i add a phone model)
$result3 = mysqli_query($con,"SELECT id,name FROM Brand");
echo '<select class="form-control"name="brandid">';
while ($row3 = mysqli_fetch_array($result3)) {
echo '<option value="'.$row3['id'].'">'.$row3['name'].'</option>';
}
echo '</select>';
?>
Name: <input class="form-control" type="text" name="modelname">
Image: <input class="form-control" type="text" name="modelimage"></br>
Service List: <?php echo '<table class="table table-bordered table-condensed"><tr><th>*</th><th>Service Name</th><th>Price</th></tr>';
$result4 = mysqli_query($con,"SELECT id,servicename, serviceprice FROM service");
while ($row4 = mysqli_fetch_array($result4)) {
echo '<tr><td><lable>';
echo '<input type="checkbox" value="'.$row4['id'].'" id="'.$row4['id'].'" name="servicelist[]"></td><td>'.$row4['servicename'].' </td><td>'.$row4['serviceprice'];
echo '</lable></td></tr>';
}
echo '</table>';
$row4['serviceprice']; - I want to replace this with a text box. But not sure how to send the values. I'm just lost. Should I make a mysql table named Price now? With priceid, serviceid and modelid? And then somehow join all of this when showing the model? Really lost.
Would like to hear a tip from someone more expirienced than me. Thank you.
Alex.
Edit:
I got to this point:
$pricelist=$_POST['price'];
foreach ($pricelist as $k){
$sql="INSERT INTO Price (modelname, serviceid, price)
VALUES ('$name', '$SERVICE_ID_OF_ONE_SERVICE', '$k')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
need to put in service id for each price from an array that i get from a from of checkboxes. should i have foreach within foreach?
Im not i fully understand what you want to do, but if you want to send data from your website using a text box to your php file you can do it as follows.
<form action="yourphpfile" method="post">
<input type= "text" name="price" placeholder="enter your price"/>
<input type="submit" value="submit"/>
</form>
your php
$price= $_POST["price"]
now the variable $price holds the price that you sent. If your php is in the same file as your html you leave action as "" or just write the filename.

How to get a HTML Form to query and produce results from Mysql datebase

I have created a form that has one text field and one select box, I also have created a button. Now what I want to happen is when the button is pressed I want the string in the forms to be matched up to my database and then I want the results of those matches to be returned and shown on the screen.
For example if I was to type 'History' into my text field box and I also selected 'level 2' from my select box when the button (Submit Button) was pressed I would want returned on the page everything that matches up with the word history and the selection of level 2 in my database.
I know that I have to connect my page with my Database through PHP and I have successfully done that, but what I don't understand is how to then get my HTML Form to Query the database and provide results back onto the screen
In terms of a example website that is very similar to the concept I would like to create take a look at this webpage. http://search.ucas.com/cgi-bin/hsrun/search/search/search.hjx;start=search.HsSearch.run?y=2013&w=H (UCAS Course Search) this website has multiple text fields and select boxes and a submit button exactly as I am trying to create and the results provided are only the results that match with what has been searched.
The code below works in terms of it links my text-field to my database but I can't get my text-field and my select box to link and query the database, only one or the other. I want them both to work from the same button (search button)
<form method="post" action="Webpage here" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
<form id="form1" name="ExamBoard" method="post" action="Webpage here">
<label for="select"></label>
<select name="ExamBoard" id="select">
<option value="EB1" selected="selected">EB1</option>
<option value="EB2">EB2</option>
<option value="EB3">EB3</option>
</select>
<input type="submit" name="submit" value="Search">
</form>
<p> </p>
<p>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$db=mysql_connect ("Name", "User", "Password*") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("Table Name");
//-query the database table
$sql="SELECT ID, CourseName, ExamBoard FROM subjects WHERE CourseName LIKE '%" . $name . "%' ";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$CourseName =$row['CourseName'];
$ID=$row['ID'];
$ExamBoard=$row['ExamBoard'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" .$CourseName . " " . "</li>\n" ;
echo $ExamBoard . " " . "</a>\n";
echo "</ul>";
}
}
}
}
?>
New HTML File
newHTML.htm
<form method="post" action="Webpage here" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form
New PHP file
newPHP.pfp
<?php
if(preg_match("/^[ a-zA-Z]+/", $_REQUEST['name'])){
$name=$_REQUEST['name'];
//connect to the database
$db=mysql_connect ("Name", "User", "Password*") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("Table Name");
//-query the database table
$sql="SELECT ID, CourseName, ExamBoard FROM subjects WHERE CourseName LIKE '%" . $name . "%' ";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$CourseName =$row['CourseName'];
$ID=$row['ID'];
$ExamBoard=$row['ExamBoard'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" .$CourseName . " " . "</li>\n" ;
echo $ExamBoard . " " . "</a>\n";
echo "</ul>";
}
?>
You have to ask yourself Do you want to do this with AJAX or with normal screen refreshes..
With normal screen refreshes (The easy way)
Take your HTML and place it in one file (HTMLfile.html)
Take your PHP and place it in another file (PHPCode.php)
HTML file form calls the PHP script from action attribute.
PHP file renders the response.
Dont mash up the view and the controlling application.
There is other ways to do this in one script if you want to use AJAX.

Display result in dropdown and select to perform query in php mysql

I have a database named Data which has a table in which their are different names of products their id and prices, i want to make a web page using php so that i can edit,add and save the items from the web page to the DB and search the names accordingly.
<html>
<head>
<title>Products store</title>
</head>
<body>
<p style="font-size:20px" align="center"> <b>Product Database Editor</b> </p>
<p>
<form method="post">
Enter Product Name: <input type="text" name="pname" id="pname" size="70">
<input type="submit">
</p>
<form method="post">
<select id="opt" name="opt">
<?php
$pname = $_REQUEST['pname'];
// $pname= mysql_real_escape_string($_POST['pname']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Dataentry", $con);
$result = mysql_query("SELECT * FROM products where name like '%$pname%'");
$result_rows = mysql_num_rows($result);
if($pname==NULL)
{
echo "Please enter a product name!";
}
else if($result_rows==0)
{
echo "Product Name does not exist!";
}
else
{
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
echo "<option value='$name_selected'>$name</option>";
//echo ("<option value = '" . $row['name'] . "'>" . $row['id'] . "</option>");
echo $name_selected;
echo "<br />";
}
}
mysql_close($con);
?>
</select>
</form>
</body>
</html>
when i run this code i get the names list in the dropdown but after i select any name, nothing happens, how should i modify my code so that i can select any name from the dropdown and then be able to fetch the price of that particular name to edit it.
please help, coding will be much helpful.
Suppose you have a question like this in your dropdown menu.
Q - How many colors does the US flag has?
Now, from what I understand you want your choice from the drop down menu to appear instantly..
Well, here is a simple select form.
<form method="post">
<select id="opt" name="opt">
<option value="four">four</option>
<option value="five">five</option>
<option value="two">two</option>
<option value="million">million</option>
</select>​
And, the JS code:
$(document).ready(function() {
$("#opt").change(function() {
alert($(this).val());
});
});​
Now, click her a DEMO with jsFiddle to show you, how it works.
You can copy/paste the codes and include them in your site, this is a simple code, but you if you small knowledge of Javascript you can manipulate the data the way you need it to appear. .
To get a value of an input (this case, from a dropdown) on the fly, you need to use client-side scripting language javascript (or jquery) and use ajax to sent it to server-side, where the code is in PHP.

trouble populating form fields from mysql table

Please help!
I'm a complete php/sql newb, and i'm feeling pretty (ok, really) dumb.
I really need help pre-populating text fields of a form i've built for our office staff to contact the workmen in the field, (and the form works well enough); I've searched a million threads, but just could not figure it out...
Only some of the form fields need to pre-populate after a users login, but I have no idea how to make that happen... I've created a mysql DB with a table called 'users', and i know how to open the DB (and close it), but can't figure out how to pull the data from a given row, and populate the fields I need correctly. here's where I'm at:
mysql_connect("localhost", "XXXXX", "XXXXX") or die("Error connecting to MySQL: ".mysql_error());
mysql_select_db("vendor_sqldb") or die("Error selecting database: ".mysql_error());
$sql = mysql_query("SELECT * FROM USERS") or die("Error connecting to table: ".mysql_error());
$rowdetail=mysql_fetch_array($sql);
date_default_timezone_set('America/Los_Angeles');
//1. Add your email address here.
//You can add more than one receipient-
$formproc->AddRecipient('foreman#mysite.com'); //<<--- supervisor email address here
$formproc->SetConditionalField('select field emplyee');
$formproc->AddConditionalReceipent(employee1,'email#email.com');
$formproc->AddConditionalReceipent('employee2','email#email.com');
$formproc->AddConditionalReceipent('employee3','email#email.com');
$formproc->AddConditionalReceipent('employee4','email#email.com');
$formproc->AddConditionalReceipent('employee5','email#email.com');
$formproc->AddConditionalReceipent('employee6','email#email.com');
$formproc->AddConditionalReceipent('employee7','email#email.com');
$formproc->AddFileUploadField('newupload','',1024);//<<------- New file upload
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->RedirectToURL("thank-you.php");
}
And heres the area where I need the help to prepopulate fields:
<p align="center">
<label for='email' ></label>
<label for='name' >Office Staff Employee Name* </label>
<input type='text' name='name' id='name' readonly='readonly' 'value='<?php echo $formproc->SafeDisplay('name') ?>' maxlength="50" value="<?php echo $session->name?>" name="name" />" />
</p>
<p align="center">
<label for='email2' >Your Email Address*</label>
<input type='text' name='email2' id='email2' value='<?php echo $row_Recordset1['email']; ?><?php echo $formproc->SafeDisplay('email') ?>' maxlength="50" />
I'm not sure how to prepopulate the values for office staffer's name, their email etc? I supposed that it was a simple echo command, but if it is, I guess I'm not getting the syntax right?
I'm sure im missing a line of code, which would specify row and collumn containing the data too, but don't know how to write this!?
Thanks a bunch for your help!
Your sql selects a row for each user.
$sql = mysql_query("SELECT * FROM USERS") or die("Error connecting to table: ".mysql_error());
You need to specify which user you are trying to get from the database table. I am going to give you an example for the SQL query if the user's names were stored in a column named "USERNAME":
$sql = mysql_query("SELECT * FROM USERS WHERE USERNAME='name'") or die("Error connecting to table: ".mysql_error());
You can then pull the user specific data and insert it where needed.

Categories