如果数据库中没有行,则仍应显示字段

时间:2012-04-27 08:17:55

标签: php

在我的表单上,我有一个echo,它链接到我数据库中的数据。 但是,如果这是第一次访问表单(表中没有与会话相关的ID),则文本框不会显示,而它们应该显示为空! 当id链接到会话并且数据库中有一行时(用户已经完成一次表单并且已经回来编辑),它是成功的。) 我希望这是有道理的。为了更清楚,如果用户第一次访问表单时textareas应该在那里(他们现在消失)但是是空的。

 $rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");

     <br>

  <form action="thesis.php" method="post" name="regForm" id="regForm" >

  <?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>

      Title of Proposed Thesis<span class="required">*</span>

      <textarea name="thesis_Name" type="text" style="width:500px; height:150px" 

      id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?>   
      </textarea>

2 个答案:

答案 0 :(得分:1)

使用mysql_num_rows()


<form action="thesis.php" method="post" name="regForm" id="regForm" >
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>

//your textarea with values from database

<?php } 
} else { ?>
//empty textares
<textarea></textarea>

<?php } ?>

你的意思是什么

答案 1 :(得分:0)

请尝试下面给出的代码可能有帮助..          

<form action="thesis.php" method="post" name="regForm" id="regForm" >

    <?php if (mysql_num_rows($rs_settings) <= 0) { ?>
        <textarea name = "thesis_Name" type = "text" style = "width:500px; height:150px"

                id = "thesis_Name" size = "600"></textarea>
                <?php
            } else {
                while ($row_settings = mysql_fetch_array($rs_settings)) {
                    ?>

            Title of Proposed Thesis<span class="required">*</span>

            <textarea name="thesis_Name" type="text" style="width:500px; height:150px" 

                    id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?>   
            </textarea>
            <?php
        }
    }?>

这里mysql_num_rows($query)首先检查结果是否存在任何行

但如果表单有多个字段,那么

<?php
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = {$user_id}") or die(mysql_error());
$result = array();
if (mysql_num_rows($rs_settings) == 0) {
    $result[0]['thesis_Name'] = "";
    $result[0]['field1'] = "";
} else {
    $i = 0;
    while ($res = mysql_fetch_array($rs_settings)) {
        $result[$i] = $res;
        $i++;
    }
}
foreach ($result AS $index => $r) {
    ?>

    Title of Proposed Thesis<span class="required">*</span>

    <textarea name="thesis_Name" type="text" style="width:500px; height:150px" 

            id="thesis_Name" size="600"><?php echo $r['thesis_Name']; ?>   
    </textarea>
<?php } ?>