3

简单来说,我有一个具有三个相同输入字段的表单。名称不同;但是,发布时它们具有相同的结构,只是名称前缀不同(即三个系统具有不同的名称前缀:它们是 windowstitle、mactitle、linuxtitle 等)。

目前,我有一个只能使用一个同名的过程,即 windowstitle(当然,如果表格已填写)

代码看起来像这样:

<?php
$title = $_POST['windowstitle'];
//validate info or redirect
if ($title != "" ) {
    $title = mysql_real_escape_string($title);
    $sql = "insert into newwindows (title) values ('$title');
    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
?>

表单块也看起来像这样

<form action="newuserprocess.php" method="post" enctype="multipart/form-data">
<div class="form">
    <h3>Windows</h3>

    <!-- title of system name -->
    <p><label for="windowstitle"> edition of system </lable></p>
    <input type="text" name="windowstitle"  size=20 /><br />
    </div>
    <div class="form">
    <h3>Mac</h3>

    <!-- title of system name -->
    <p><label for="mactitle"> edition of system </lable></p>
    <input type="text" name="mactitle"  size=20 /><br />
    </div>
<p><input type="submit" id="submit" class="bigbutton" value="Upload" /></p>
</form>

然而,这留下了其他形式,唯一的区别是我想要输入的数据库和后值前缀不同。

所以我想出了一个我认为是聪明的解决方案:

<?php
$arr = array('windows', 'mac', 'linux');
foreach ($arr as &$value) {
    $title = $_POST['$valuetitle'];
    //validate info 
    if ($title != "" ) {
        $title = mysql_real_escape_string($title);
        $sql = "insert into new$value (title) values ('$title');
        $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
    }
?>

但是,这不起作用。我知道部分原因;因为''使变量按原样显示,因此 my$_Post将始终以 $value 的形式返回。另一个原因与我的 new$value 数据库名称相同。什么是正确的格式?我该如何进行这项工作?

4

3 回答 3

2

你可能想要

$title = $_POST[$value . 'title'];

$sql = "insert into new$value (title) values ('$title')";
于 2012-08-22T01:21:53.477 回答
1

Another reason is the same with my new$value database name. My question is what is the proper format for this?

为了清楚起见,我会$value用括号括起来{$value}。您的格式有效,但可能更清晰。查看一些测试:http: //ideone.com/A2kWU

此外,如果您不更改数组中的值,$arr那么您应该使用

foreach ($arr as $value) { //...

以防止意外更改。不过,在这种情况下,这没什么大不了的,因为您只使用了一次数组。

于 2012-08-22T01:31:37.677 回答
0

编辑您的代码,如:

<?php
     $arr = array('windows', 'mac', 'linux');
     foreach ($arr as $value) {
于 2012-08-22T11:16:08.310 回答