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>
Related
I'm trying to populate a Table after a user picks options from a drop down list when this options are picked the table should be populated based on selected options. I'm not sure how can I get this done and I've searched for tutorias etc but nothing helped me. So I'll be glad if someone can help somehow for example with small test codes etc.
I'm using PHP and the options for the drop-down list come from a MySQL-Database so in summary a person will choose a user from Users-drop down list after that a another option from different drop down list and then there's also going to be a date filter after 1, 2 or all 3 are selected a table will be produced based on the selected values.
So far I've no code done because I have no idea how to do it but I guess I need to put all 3 dropdown lists in a form and after submission I should produce the table, but how can I have more than one <select> ..... </select> in a <form> and submit them all simultaneously.
What I've done so far (I know it's unsafe and that mysql_* doesn't exist anymore in PHP7) but please don't criticize it.
UPDATE
//Database query for User drop-down(DD) population.
$sqlDD = " SELECT DISTINCT `user` FROM `users` " ;
$resultDD = mysql_query($sqlDD);
//Database query for Status drop-down(DD) population.
$sqlDDStatus = " SELECT `status` FROM `status` WHERE `id` = 1 OR
`id` = 123 OR `id` = 182 OR `id` = 12 ";
$resultDDStatus = mysql_query($sqlDDStatus);
<form id="form1" name="form1" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<select name="userSelect">
<?php
while($rowDD = mysql_fetch_array($resultDD)):
echo "<option value='" . htmlspecialchars($rowDD['user']) ."'>" . htmlspecialchars($rowDD['user']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<!-- Second DD-list in the same form -->
<select name="Status" style="max-width: 250px;" >
<?php
while($rowDDS = mysql_fetch_array($resultDDStatus)):
echo "<option value='" . htmlspecialchars($rowDDS['status']) ."'>" . htmlspecialchars($rowDDS['status']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<input type="submit" name="submit" value='Find'/>
</form>
//Get the submited data
<?php if(isset($_POST['submit'])): ?>
<?php echo 'This is submitted ' . $_POST['submit']; ?>
<?php endif; ?>
I've added echo 'This is submitted ' . $_POST['submit'];
because i wanted to see what is submitted but all it get's echoed out is only
"Find".
Any ideas how can i get the data submitted from both 's in the form and populate a table based on it ?
UPDATE 2
After getting an answer from other users I saw that my forms handles the data correctly but my question now is how can I use the data from the Submitted DDL Form and populate a table with them? So far I've tried the following:
<?php if(isset($_POST['submit'])): ?>
<?php $result = mysql_query( "SELECT * FROM `users` WHERE `user` =
$_POST['userSelect'] AND (`id` = 1 OR `id` = 18)" );
?>
<?php endif; ?>
and then in the table
<table>
<?php while ($row = mysql_fetch_assoc($result)) :; ?>
<tr>
<td><?php echo $row['user']; ?></td>
<?php endwhile; ?>
</table>
But I just don't get any response when I try it. How can I fix my problem and get the wanted output?
EDIT
I think that i've found my mistake after some research im not able to test the code now but i'm almost positive that you can't use $_POST['userSelect'] in the Database query so i just need to assign $_POST['userSelect'] to some variable before i use it in the query. So far i've gotten useful 1 little useful tip...... so disappointed from stackoverflow .......
This is a basis HTML/PHP page for getting data from the backend to the frontend, this should get you started. Try to print the data (in the while loop on the HTML page).
<html>
<head>
<title></title>
</head>
<body>
<form action="dropdown.php" method="POST">
<select name='options'>
<option>option 1</option>
<option>option 2</option>>
<option>option 3</option>>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}else{
if (!empty($_POST)){
if(!empty($_POST['options'])){
$option = $_POST['options'];
$query = "SELECT * FROM table WHERE option='$option'";
$res = $mysqli->query($query);
while($data = $res->fetch_assoc()){
//print data to HTML page
print_f('%s, $s\n', $data['firstname'], $data['lastname']);
}
}
}
}
?>
Your form is probably working, the reason you only get "Find" is because you are printing the value of the submit button.
To get an overview of your form data, try:
echo '<pre>';
print_r($_POST);
echo '</pre>';
You will get the other values of your form by using the name attribute of your <select> with $_POST:
echo $_POST['userSelect'];
echo $_POST['Status'];
By the way, you are using a deprecated extension (written here for example), it is recommended to use MySQLi or PDO (especially PDO is recommended). If you are working with PHP 7, mysql_connect won't work as it has been removed.
And I'm not sure the use of htmlspecialchars() is relevant on each database data you use.
PHP.net - print_r() (See also var_dump())
PHP.net - $_POST
I had spent some time trying to get the drop down box working correctly, getting the values of department and location to populate from the DB. This is working fine and I have added additionally date fields so a customer can select records for a specific period, location and department. When I action the form running departmentReport.php the page returns blank even when trying to echo each value as seen below.
<form id="departmentReport" action="departmentReport.php" method="get" onsubmit="#">
<fieldset id="departmentReport">
<h3>Department Report</h3>
<br>
<?php
include 'includes/DbCon.php';
$sql = "select department_name from departments";
echo"<select name = 'departments' value=''>Department Name</option>";
foreach ($conn->query($sql) as $row){
echo "<option value=$row[department_name]>$row[department_name]</option>";}
echo "</select>";
?>
<br></br>
<?php
include 'includes/DbCon.php';
$sql = "select `location_name` from `location`";
echo "<select name = 'location' value=''>Location Name</option>";
foreach ($conn->query($sql) as $row){
echo "<option value=$row[location_name]>$row[location_name]</option>";}
echo "</select>";
?>
<br></br><br>
<label for="date">Date From<br></label>
<input id="date1" type="date" name="dateF"
autofocus="true"/>
<br>
<br>
<label for="date">Date To<br></label>
<input id="date2" type="date" name="date2"
autofocus="true"/>
<br>
<br>
<input type="submit" class="button" value="Submit">
On Submit departmentReport.php is actioned
<?php
include "../includes/dbCon.php"; //* CONNECTION TO DATABASE
$department = mysqli_real_escape_string($conn, $_POST['departments']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
$location = mysqli_real_escape_string($conn, $_POST['location']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
$date1 = mysqli_real_escape_string($conn, $_POST['date1']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
$date2 = mysqli_real_escape_string($conn, $_POST['date2']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
echo "$department";
echo "$location";
echo "$date1";
echo "$date2";
This brings the results below..
However when adjusting post to get I see the values I selected
http://localhost:8888/departmentReport.php?departments=Marketing&location=London&dateFrom=02%2F01%2F2017
Im unsure why I cannot see the values when echoing them!
Any assistance will be much appreciated.
Your variable when retrieving the post data is wrong
Select department html code:
<select name = departments value=''>Department Name</option>
In the select form, the name is "departments", but when you retrieve them in the PHP, it is:
$_POST['departmant_name']
Which is wrong input variable name. It should be:
$_POST['departments']
Also, please put quotes mark on the select name
<select name = 'departments' value=''>Department Name</option>
All other variable also wrong.
Looks like you entered the database column name, not the form input name.
Edit:
I also noticed that in your form, the form "method" is set to "GET" while your PHP code is using "POST"
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.
I've created a php form to insert values into a database.
One of my form options is a dynamic list populated with fields from another table.
I first created the form without the dynamic option, and all data inserted just fine (and still does).
Now I'm attempting to include the code below, and while it displays the option values properly, the value fails to insert. Any advice?
<?php
/*
* LIST ALL CATEGORIES
****************************************/
include('../dbconnection.php');
$query = 'SELECT category_id, category_name FROM ingredient_categories';
$result = mysql_query($query);
echo '<select>';
while ($ingredientCategoryOption = mysql_fetch_array($result)) {
echo '<option value="'.$ingredientCategoryOption[category_id].'">'.$ingredientCategoryOption[category_name].'</option>';
}
echo '</select>';
?>
I had created something similar yesterday. The $polls array is passed to the view in CodeIgniter in the $this->load->view('poll.php', $data['polls']), while you do it in the page itself. However, you can have the general idea.
<FORM id="formPoll" class="question" name="createpoll" action="<?php echo base_url()?>index.php/poll/selectOption/" method="POST">
<select name="poll_list">
<?php
foreach($polls as $poll){
echo "<option name='poll_table'>$poll->name</option>";
}
?>
</select>
<div id="input">
Poll name: <input type="text" name="name"></input>
Title: <input type="text" name="title"></input>
</div>
<div id="options">
Option: <input type="text" name="option"></input>
</div>
<input type="submit"></input>
</FORM>
Some ideas:
Check if $results is not empty before using it
Give your <select> form a name, as I showed above
Check if $ingredientCategoryOption is not null or is something returned.
Check your database connection
im new to php so im having some problems creating what i want
i'll explain first what i need .. there conferences, each conference has a list of reviewers and authors.
i have create a dropdown list where the user chooses which conference ... i want to show a list of the reviewers and the authors that are in this conference after clicking submit.
that is my code
<?php
$con = mysql_connect("localhost:3306","root","");
mysql_select_db("messaging_dd", $con);
$sql_drop = "SELECT conference_ID,conference_name FROM Conferences";
$drop_result = mysql_query($sql_drop,$con) or die(mysql_error());
$num_rows = mysql_num_rows($drop_result) or die(mysql_error());
mysql_close($con);
?>
<form name="choose" action="savedata.php" method="POST">
<br />
Conference: <select name="conference">
<?php
for($i=0 ; $i<$num_rows ; $i++)
{
$idofconference = mysql_result($drop_result,$i,0);
$nameofconference = mysql_result($drop_result,$i,1);
echo '<option value=" '.$idofconference.' ">'.$nameofconference.'</option>';
}
?>
</select>
<br />
<input type="submit" value="submit" name="submit" />
</form>
Try this,
$conf_id = $_POST['conference'];
$con = mysql_connect("localhost:3306","root","");
mysql_select_db("messaging_dd", $con);
$sql = "SELECT review, author FROM Reviews WHERE conf_id = ".$conf_id;
$review_list = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
Or you can go for Ajax. Updating your search result, without reloading the whole page. Reference for Ajax: http://www.w3schools.com/php/php_ajax_database.asp
All the data being submitted gets stored in the $_POST variable as an array. Your conference ID will be in $_POST['conference'] as the name of your select element is conference.
An other approach is to load the desired data (reviewers and authors) through an AJAX request so that the viewer of your website won't leave the webpage.
it's similar to what you have done, just add conference id details like this:
$sql = "SELECT reviewer, author FROM Conferences where conference_ID = " . $_POST['conference'];
In your file savedata.php you can put
$whatever = $_POST['conference']
$_POST is one of several arrays in php that is reserved for system data, for example you can make calls to $_server to find out details about the server(eg the time on the server)
you could also change the method='POST' to method='GET' and it would be in the GET array
$whatever = $_GET['conference']
this is a bit less secure, but if that's not a priority its worth considering
I think you should Try this.
<form name="choose" action="savedata.php" method="POST">
<br />
Conference: <select name="conference">
<?php
while($row=mysql_fetch_array($drop_result)
{
echo '<option value=" '.$idofconference.' ">'.$nameofconference.'</option>';
}
?>
</select>