我试图制作一个下拉列表,允许用户选择符合其需求的培训计划,因此当他们选择它时,该选项将进入MySQL数据库中的表。
我的代码是:
<form action="sessionreq.php" method="POST">
<div class="form-group">
<label for="exampleSelect1">Category</label>
<select class="form-control" id="exampleSelect1">
<option name='eg1'>Example option</option>
<option name='eg2'>Example option 2</option>
<option name='eg3'>Example option 3</option>
</select>
</div>
<button type="submit" class="button button-block" name="delete">Request</button>
<br>
</form>
我需要的是一个SQL查询,因此当他们选择&#39;示例选项3&#39;时,它将在名为method
的列中输入到数据库中。我应该使用值插入method
(取决于它们在下拉列表中的选项)。例如,如果用户选择Example option 2
,则会将method
插入Example option 2
,其值为class CompaniesController < ApplicationController
before_action :authenticate_user!, only: [ :new, :create, :edit, :update, :destroy ]
def new
@company = Company.new
@company.quotes.build
@company.employees.build
end
def create
@company = current_user.companies.new(company_params)
if @company.save
redirect_to company_quote_url(@company.id), notice: 'Quote request created'
else
render :new
end
end
private
def company_params
params.require(:company).permit(:co_name, :co_number, :postcode, :industry,
:quotes_attributes => [:id, :lives_overseas, :payment_frequency],
:employees_attributes => [:id, :first_name, :last_name, :email, :gender, :date_of_birth, :salary, :_destroy] )
end
end
。
TL; DR如何使用下拉列表填充数据库表/列?
答案 0 :(得分:3)
首先为您的select
命名。在这种情况下,我给了training
<form action="sessionreq.php" method="POST">
<div class="form-group">
<label for="exampleSelect1">Category</label>
<select class="form-control" id="exampleSelect1" name="training">
<option value='Example 1'>Example option 1</option>
<option value='Example 2'>Example option 2</option>
<option value='Example 3'>Example option 3</option>
</select>
</div>
<button type="submit" class="button button-block" name="delete">Request</button>
<br>
</form>
现在,在您的sessionreq.php
中,您可以通过$_POST
获取值
$_POST['training']; //You can manipulate the data anyway you like.
现在您可以运行要插入的查询。鉴于是准备好的声明(首选)
$stmt = $connection->prepare("INSERT INTO table (column) VALUES (?)");
$stmt->bind_param("s",$_POST['training']);
$stmt->execute();
$stmt->close();