我在这里结束了我的智慧。我已尝试在所有不同的浏览器中仍然得到相同的触发器错误消息Notice: Duplicate entry for key 'PRIMARY'
但是,它仍然插入数据库。我认为该页面同时执行了两次。代码永远不会到达存储会话数据的块。任何见解将不胜感激!
<?php
if($_POST[submit])
{
$username = "";
$password = "";
$hostname = "";
$dbname = "";
//connection to the database:
$db = mysqli_connect($hostname, $username, $password, $dbname, '3306')
or die("Unable to connect to MySQL");
$id = !empty($_POST[id]) ? "'$_POST[id]'" : "NULL";
$fname = !empty($_POST[fname]) ? "'$_POST[fname]'" : "NULL";
$lname = !empty($_POST[lname]) ? "'$_POST[lname]'" : "NULL";
$sql = "INSERT INTO Table(id, fname, lname)
VALUES ($id, $fname, $lname)";
$result = $db->query($sql) OR trigger_error($db->error);
if ($result && $db->affected_rows > 0)
{
// store session data
$_SESSION['fileid']=$id;
echo 'Creating file '.$id.'<br/>
<a href = "partTwo.php" class="button">Continue</a>';
}
else
echo "No changes made.";
}
else
echo '<form method="post" action="createFile.php">
<div><span class = "formlabel">File number:</span><input type="Text" name="id"></div>
<div><span class = "formlabel">First name:</span><input type="Text" name="fname"></div>
<div><span class = "formlabel">Last name:</span><input type="Text" name="lname"></div>
<input class="submit" type="Submit" name="submit" value="Submit">
</form>';
?>
答案 0 :(得分:0)
而不是if($_POST[submit])
使用if(isset($_POST[submit]))
答案 1 :(得分:0)
我已经编辑了你的代码,现在效果很好:)
<?php
//connection to the database:
$username = "";
$password = "";
$hostname = "";
$dbname = "";
$db = mysqli_connect($hostname, $username, $password, $dbname, '3306')
or die("Unable to connect to MySQL");
if(isset($_POST[submit]))
{
if(($id = !empty($_POST['id']) || $fname = !empty($_POST['fname']) || $lname = !empty($_POST['lname']))
{
echo "error msg.";
}else{
$id = "";
$fname = "";
$lname = "";
$sql = "INSERT INTO Table(id, fname, lname)
VALUES ($id, $fname, $lname)";
$result = $db->query($sql) OR trigger_error($db->error);
}
if ($result && $db->affected_rows > 0)
{
// store session data
$_SESSION['fileid']=$id;
echo 'Creating file '.$id.'<br/>
<a href = "partTwo.php" class="button">Continue</a>';
}
else
echo "No changes made.";
}
else
echo '<form method="post" action="createFile.php">
<div><span class = "formlabel">File number:</span><input type="Text" name="id"></div>
<div><span class = "formlabel">First name:</span><input type="Text" name="fname"></div>
<div><span class = "formlabel">Last name:</span><input type="Text" name="lname"></div>
<input class="submit" type="Submit" name="submit" value="Submit">
</form>';
?>