PHP / SQL表单:插入不正确

时间:2016-11-27 03:18:37

标签: php sql

我是PHP / SQL的新手,我正在尝试创建一个将给定数据插入格式化表格的表单。在摆弄了一下之后,我已经设法让主要功能正常工作,但是,似乎我的脚本正在插入一列数据,而我不能为我的生活理解为什么。这是我制作的剧本:

#!/usr/local/bin/php -d display_errors=STDOUT
<?php
  // begin this XHTML page
  print('<?xml version="1.0" encoding="utf-8"?>');
  print("\n");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
<title>Accessing a SQLite 3 Database using PHP</title> 
</head>
<body>
<p>
<?php 


$database = "students.db";          


try  
{     
     $db = new SQLite3($database);
}
catch (Exception $exception)
{
    echo '<p>There was an error connecting to the database!</p>';

    if ($db)
    {
        echo $exception->getMessage();
    }

}


// define tablename + fieldnames
$table = "bruins";
$field1 = "name";
$field2 = "sid";
$field3 = "gpa";


// Create the table
$sql= "CREATE TABLE IF NOT EXISTS $table (
$field1 varchar(100),
$field2 int(9),
$field3 decimal(3,1)
)";
$result = $db->query($sql);

print "<h3>Creating the table</h3>";
print "<p>$sql</p>";

// Extract SID and GPA from the $_GET data.
$name = $_GET['name'];

$SID = $_GET['SID'];

$GPA = $_GET['GPA'];


//  Insert a new record to DB with name = $name, sid = $SID and gpa = $GPA 
$sql = "INSERT INTO $table ($field1, $field2, $field3) 
  VALUES ('$name', '$SID', '$GPA')";


print "Inserting a new record to the bruins table the command I am using is:</br>";
print "$sql";
$result = $db->query($sql);


// print an XHTML table to display the current table
$sql = "SELECT * FROM $table";
$result = $db->query($sql);


print "<table border='border'>\n";
print "  <tr>\n";
print "     <th>" . $field1 . "</th>\n";
print "     <th>" . $field2 . "</th>\n";
print "     <th>" . $field3 . "</th>\n";
print "  </tr>\n";

// obtain the results from the SELECT query as an array holding a record
while($record = $result->fetchArray())
{  
  print "  <tr>\n";
  print "  <td>" . $record[$field1] . "<td>\n";
  print "  <td>" . $record[$field2] . "<td>\n";
  print "  <td>" . $record[$field3] . "<td>\n";
  print "  </tr>\n";
}

print "</table>\n";
?>
</body>
</html>

提交数据后,将创建表,但所有SID字符串都在GPA列中,GPA字符串将放入其自己的空白列中。任何建议/见解都会很棒: - )

1 个答案:

答案 0 :(得分:0)

我只是再次在这里发布答案,以防有人在评论中没有看到。 在代码末尾正确关闭s解决了问题:)