我已经验证post方法实际上是使用echo来显示变量,但是当我使用下面的Insert查询时它不会添加行。
你有什么想法吗?
<?php
// 1. CReate a DB connection
$connection = mysql_connect("localhost","root","P@ssword");
if(!$connection){
die("Database connection failed: " . mysql_error());
}
?>
<?php
$menu_name = $_POST['menu_name'];
$position = $_POST['position'];
$visible = $_POST['visible'];
?>
<?php
$query = "INSERT INTO subjects (menu_name, position, visible) VALUES ('{$menu_name}', {$position}, {$visible})";
$result = mysql_query($query, $connection);
if ($result){
header("Location:staff.php");
exit;
} else {
echo "<p> There was an error when creating the subject </p>";
"<p>". mysql_error()."</p>" ;
}
&GT;
答案 0 :(得分:2)
令人困惑的代码o.O!。很长一段时间以来,我的代码看起来像这样。所以很难弄清楚,哈哈。但是,当涉及到mysql错误时 - 当某些东西没有正确地给我提供错误时(当调试时看起来像这样) - 我逐行阅读。然后我回显查询,并使用mysqladmin或其他sql工具进行测试。我也会跑 $ query = mysql_query($ query)或die(mysql_error()); 在同一行上进行快速调试。
a)切换到mysqli以备将来的PHP更改。如果你喜欢mysql,请熟悉mysqli。
为什么('{$ menu_name}',{$ position},{$ visible})不是('{$ menu_name}','{$ position}','{$ visible}')?代替。
<?
$host = "localhost"; // hostname
$user = "root"; // username
$pass = "P@ssword"; // password
$db = ""; // database name
$connection = mysql_connect($host,$user,$pass) or die("Database connection failed: ".mysql_error());
$database = mysql_select_db($db,$connection) or die("DB Selection Error: ".mysql_error());
$menu_name = mysql_real_escape_string($_POST['menu_name']);
$position = mysql_real_escape_string($_POST['position']);
$visible = mysql_real_escape_string($_POST['visible']);
$query = "INSERT INTO `subjects` (`menu_name`, `position`, `visible`) VALUES ('{$menu_name}', '{$position}', '{$visible}')";
$result = mysql_query($query, $connection) or die(mysql_error());
if ($result){ // I would usually use mysql_insert_id as a validation from auto_increment tables.
header("Location:staff.php");
exit;
} else {
echo "<p> There was an error when creating the subject </p>
<p>". mysql_error()."</p>" ;
}
?>
答案 1 :(得分:1)
您没有选择数据库。
<?php
// 1. CReate a DB connection
$connection = mysql_connect("localhost","root","P@ssword");
if(!$connection){
die("Database connection failed: " . mysql_error());
}
mysql_select_db("DB_NAME", $connection);
?>
答案 2 :(得分:0)
您是否注意到了自己的价值观('{$menu_name}', {$position}, {$visible})
,它们都应引用('{$menu_name}', '{$position}', '{$visible}')
。