dqdtgiw4736
dqdtgiw4736
2015-07-22 08:41

基于HTML select选项在PHP中分配变量,并将结果插入数据库表

已采纳

I'm running the following queries to retrieve info from the timesheetlogin table.

$clientlist = db_select("SELECT * FROM timesheetlogin WHERE type='client' ORDER BY company DESC");
$candlist = db_select("SELECT * FROM timesheetlogin WHERE type='cand' ORDER BY name DESC");

This info is displayed in a form on the front-end.

<select name="client" id="client">
<?php 
    foreach($clientlist as $key => $value) {
            $company = $clientlist[$key]["company"];
            $name = " (" . $clientlist[$key]["name"] . ")";
            echo '<option value="'. $company .'">'. $company . $name .' </option>';
            $clientid = $clientlist[$key]["id"];
                    }
                ?>  
</select><br />

So the form has lots of blank fields that I haven't shown, with just the client and candidate name being chosen from a dropdown.

Finally I'd like to insert the entry to the database:

if (isset($_POST['submit'])) {
    $clientid = db_quote($_POST['client']);
    $candid = db_quote($_POST['cand']);

Here is the SQL

db_query("INSERT INTO timesheets (clientid, candid, weekending, department, orderno, basicpay, basiccharge, otpay, otcharge, ot2pay, ot2charge, status, hue, huc) VALUES ('$client', '$cand', '$week_ending', '$department', '$order_no', '$basic_pay', '$basic_charge', '$ot_pay', '$ot_charge', '$ot2_pay', '$ot2_charge', '$status', '$hue', '$huc')");

The problem I have is I need to pass the id's associated with $_POST['client'] and $_POST['cand'] NOT the strings that are currently in the option fields.

My initial thoughts are to do something like this to check the 'client' field and query the database to get the value of the id:

if (isset($_POST['client'])) {
    //code
}

That seems messy though. I have already queried the db and looped through the $clientlist array, so the ids are available in that loop. Is there a way to assign the $clientid variable based on what the user chooses from the select box?

Thanks

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doulu3399 doulu3399 6年前

    You can put ids like this :

    $clientid = $clientlist[$key]["id"];
    echo '<option value="'.$clientid.'">'. $company . $name .' </option>';
    
    点赞 评论 复制链接分享