繁体   English   中英

php:处理选择标记

[英]php:process the select tag

此代码运行,但是当测试它..数据不正确时,我从数据库中选择数据,并在数组广告中将其显示为通过选择标签显示ID,但是当选择任何ID并提交时。例如,我选择5并单击提交记录将删除的是2而不是5

<?php
require_once "config.php";
$qid="select id from info_user";
$arrayid=array();
$result=mysql_query($qid);
while($res=mysql_fetch_array($result)){
$arrayid[]=$res['id'];
}
var_dump($arrayid);
if(isset($_POST['sub'])){
$id=$_POST['id'];
$q="delete from info_user where id=$id ";
$qq=mysql_query($q);
if($qq){
    echo "you delete record ";
}
else{
    echo "error in deleting";
}}
?>
<html>
<head>
<title>delete</title>
</head>
<form action="delete.php" method="post">
<select name="id"><?php for($i=0;$i<count($arrayid);$i++){?>
<option value="<?php echo $i;?>"><?php echo $arrayid[$i];} ?></option></select> <br />
<input type="submit" name="sub" />     
</form>
</html>

我认为该问题对于期权具有价值。

尝试将选项行更改为

<option value="<?php echo $arrayid[$i];?>"><?php echo $arrayid[$i];} ?></option></select> <br />

您的<option>标记是错误的。 使您的标记像这样;

<select name="id">
  <?php for ($i = 0; $i < count($arrayid); $i++) { ?>
     <option value="<?php echo $i; ?>"><?php echo $arrayid[$i]; ?></option>
  } ?>
</select>

提示:如果缩进代码,您会发现调试会更容易 IDE通常具有此选项。 NetBeans是我的最爱。

而不是发送ID,而是发送与ID关联的数组键。

例如,假定: $arrayid = array(10, 11, 12);

这等效于: $arrayid = array(0 => 10, 1 => 11, 2 => 12);

您将看到选项10、11和12,但是将发送0、11或12,因为这是您要为选项值设置的内容:

<select name="id">
   <option value="0">10</option>
   <option value="1">11</option>
   <option value="2">12</option>
</select>

如果选择选项“ 11”,则删除条目的SQL语句将为:

delete from info_user where id=1

我没有测试此代码,并且我假设id是整数,但是尝试一下:

<?php
require_once "config.php";
$qid     = "select id from info_user";
$arrayid = array();
$result  = mysql_query($qid);
while( $res = mysql_fetch_array($result) ){
    $arrayid[] = $res['id'];
}

if( isset($_POST['sub']) ){
    $id = (int)$_POST['id']; // make sure it's an integer to avoid SQL injections
    $q  = "delete from info_user where id=$id";
    $qq = mysql_query($q);
    if( $qq ) {
        $error = "you delete record ";
    } else {
        $error = "error in deleting";
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>delete</title>
    </head>
    <body>
        <?php
        if( isset($error) ) :
            echo '<p>', htmlspecialchars($error), '</p>';
        elseif( !empty($arrayid) ) :
            var_dump($arrayid);
        endif;
        ?>

        <form action="delete.php" method="post">
            <select name="id">
                <?php foreach($arrayid as $id): ?>
                <option value="<?php echo (int)$id;?>">
                    <?php echo (int)$id; ?>
                <?php endforeach; ?>
                </option>
            </select>
            <br />
            <input type="submit" name="sub" />     
        </form>
    </body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM