2013-03-17 143 views
1

这一直在窃听我3天现在..我是新来的,并试图让我的头圆的东西。我有一个涉及3个领域的表格。名字,姓氏,标记。我使用了一个while循环来从mysql表中生成表。我使用了一个文本框,并使用循环来调用“ID”后的文本框,以便每个文本框都被唯一命名。然后,我使用post方法将值发送到第二个页面,该页面将用用户刚输入的值更新'标记'列。这是我发现我的问题的地方!使用While循环php更新mysql数据库

这是首页。

<html> 
<head><title>Please Enter Your Surname</title></head> 
<body> 
<center> 
<h2><font color=blue>Please Enter Your Surname</font></h2><p> 

<form action="insert.php" method="POST"> 

<?php 

$db = mysql_connect("localhost","root",""); 
if (!$db) 
{ 
    do_error("Could not connect to the server"); 
} 

mysql_select_db("session6",$db)or do_error("Could not connect to the database"); 


$result = mysql_query("SELECT * FROM members ORDER BY id",$db); 


$rows=mysql_num_rows($result); 


if(!$rows) 
{ 
    do_error("No results found"); 
} 
else 
{ 
    echo "<table border=3 cellspacing=1 cellpadding=1 
    align=center bgcolor=lightblue>\n"; 
    echo "<caption><h2><font color=blue> Members Details  
      </font></h2></caption>\n"; 
    echo "<tr><th>Member Id</th><th>Firstname</th><th>Mark</th></tr>\n"; 
    while ($row = mysql_fetch_array($result)) 
    { 

     echo "<tr>"; 
     echo "<td strong>" . $row['Id'] . "</td>"; 
     echo "<td strong>" . $row['Firstname'] . "</td>";?> 
     <td strong><input type="text" name="<?php echo $row['Id']; ?>" size="20"></td> 
     <tr> 
     <?php 



    } 
    ?><input type="hidden" name="no_of_rows" value="<?php echo $rows; ?>"> 
    <?php 
    echo "</table>\n"; 
} 

mysql_close($db) or do_error("Could not close connection"); 

function do_error($error) 
{ 
    echo $error; 
    die(); 
} 

?> 
<input type="submit" value="Search"> 
<input type="reset" value="Reset"> 

</form> 

</body></html> 
` 

然后,更新都是在这里完成这是我似乎有一个问题:

<html> 
<body> 
<?php 
$db = mysql_connect("localhost","root",""); 
if (!$db) 
{ 
    do_error("Could not connect to the server"); 
} 

mysql_select_db("marks",$db)or do_error("Could not connect to the database"); 

$i=1; 
while ($i <= $_POST["no_of_rows"])// or $_POST["No_of_Rows"] from form 
{ 

    $insertsql = "UPDATE members SET mark = " . $_POST[$i] . " WHERE Id = " . $row['Id'] . ";"; 
    echo $_POST['$i']; 
    $i++; 

} 

?> 

</body></html> 

当我回声$ _ POST [$ I']它显示了正确的值,但不更新数据库,我不准备把我的笔记本电脑扔进垃圾桶!哈!我知道这是可能会愚蠢的我什么都看不到,所以任何帮助将不胜感激。

+0

删除'mysql_ *'并开始使用'PDO',因为它已被弃用... – Houssni 2013-11-06 13:04:21

回答

1

您在更新查询中缺少单引号。这将有助于:

$insertsql = "UPDATE `members` SET `mark` = '" . $_POST[$i] . "' WHERE `Id` = '" . $row['Id'] . "' ;"; 

你还没有为更新

最后您使用的是弃用MySQL的PHP​​命令运行mysql_query查询命令。改用mysqli或pdo。不要忘记在查询逃跑数据,以防止SQL注入

0

问题是这里的单引号,强制文字“$ I”,这大概在$ _ POST

echo $_POST["$i"]; 
0

无需心不是关键使用变量时使用引号: $ _POST [$ id];