表单提交后更新sql

时间:2016-09-08 23:49:52

标签: php sql forms

好的伙计们,我是新手,但是 1.我想在文本框中输入数字后更新我的sql。它正确回声,但不会改变数据库。 2.我想删除第一个提交按钮并将其设为onchange事件。

我真的很困惑。多谢你们!这项工作差不多完成了。已经做了很长时间了。我还在学习php,请耐心等待我。感谢

<?php

$conn = new mysqli('localhost', 'root', 'jared17', 'hbadb') 
or die ('Cannot connect to db');

$result = $conn->query("select * from english");

echo "<html>";
echo "<body>";
echo "<form name='form' method = POST>";
echo "<select name = 'Students'>";
while ($row = $result->fetch_assoc()) {
$LRN = $row['LRN'];
$Last = $row['Last_Name']; 
$First = $row['First_Name'];
echo '<option value="'.$LRN.'">'.$Last.', '.$First.'</option>';

}
echo "</select>";
echo "<input type='submit' name='submit' value='Show'>";


if (isset($_POST['Students'])) {
$lrn = $_POST['Students'];
$stmt = $conn->prepare("SELECT Last_Name, First_Name, Level, Q1, Q2, Q3, Q4, FINAL FROM english WHERE LRN = ?");
$stmt->bind_param('i', $lrn);
$stmt->execute();
$stmt->bind_result($last, $first, $level, $q1, $q2, $q3, $q4, $final);
$stmt->fetch();
   echo "<table><tr><th>LRN</th><th>Name</th><th>Level</th><th>Q1</th><th>Q2</th><th>Q3</th><th>Q4</th><th>Final</th></tr>";
echo "<tr><td>$lrn</td><td>$last, $first</td><td>$level</td><td>$q1</td><td>$q2</td><td>$q3</td><td>$q4</td><td>$final</td></tr></table>";
}



///////////EDIT DATA
echo "Edit Data: ";
echo "<select name = 'Edit'>";

echo '<option value=Q1>Q1</option>';
echo '<option value=Q2>Q2</option>';
echo '<option value=Q3>Q3</option>';
echo '<option value=Q4>Q4</option>';
echo '<option value=FINAL>FINAL</option>';
echo '<input type="number" name="editdata">';
echo "</select>";
echo "<input type='submit' name='submit2' value='Edit Now'>";


if (isset($_POST['Edit'])) {
$upd = $_POST['Edit'];
$txt = $_POST['editdata'];
$now = "UPDATE english SET $upd=$txt WHERE LRN=$lrn";
$result2 = $conn->query($now);
echo $now;
    }



echo "</form>";



echo "</body>";
echo "</html>";
?>

1 个答案:

答案 0 :(得分:0)

您需要将输入包装在引号中,否则SQL会认为您尝试引用列而不是字符串。

$now = "UPDATE english SET $upd=\"$txt\" WHERE LRN=\"$lrn\"";

或者如果您更喜欢单引号以避免转义反斜杠,那么这应该是相同的:

$now = "UPDATE english SET $upd='$txt' WHERE LRN='$lrn'";

此外,这不是最佳做法,正如chris85所述,您受到注射攻击,如果您想要最佳实践,那么您想要使用它:http://php.net/manual/en/mysqli-stmt.bind-param.php