我想在表格中插入一些信息,但它不起作用。这是代码。
<?php
$con=mysql_connect("localhost","Chew","*****","Birthdays");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Name="Something";
$Desc="Something";
$Lang="En";
$D="1";
$M="1";
echo "<br>";
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, Day, Month) VALUES ('".$Name."', '".$Desc."', '".$Lang."', '".$D."', '".$M."' );";
$qr= mysql_query($con, $sql) or die("Error: " . mysql_error());
mysql_close($con);
?>
答案 0 :(得分:1)
MONTH
和DAY
是MySQL functions的名称。如果您要使用这些名称命名列,则必须使用ticks转义它们:
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, `Day`, `Month`) VALUES ('".$Name."', '".$Desc."', '".$Lang."', '".$D."', '".$M."' );";
答案 1 :(得分:0)
$qr= mysql_query($sql, $con) or die("Error: " . mysql_error());
注意:不推荐使用mysql_ *,请使用mysqli_ *或pdo
答案 2 :(得分:0)
如果D和M是数字,那么SQL不应该在SQL的VALUES部分使用引号(')
答案 3 :(得分:0)
您应该使用面向对象机制在MySQLi类
的帮助下与MySQL建立连接例如
// The var's in complete caps means they might be defined as constant variable
// DB_HOST - database hostname
// DB_USER - database user
// DB_PASS - database password
// DB_NAME - database instance name
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($db -> connect_error){
// in case there are errors
die("Connect Error (" . $db -> connect_errno . ") " . $db -> connect_error);
}
$Name= mysql_real_escape_string("Something"); // helps to escape special characters like quotes
$Desc= mysql_real_escape_string("Something");
$Lang="En";
$D="1";
$M="1";
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, `Day`, `Month`) VALUES ('".$Name."', '".$Desc."', '".$Lang."', $D, $M );";
$db -> query($sql) or die("Error: " . $db -> error_msg);
echo "Insert id: " . $db -> insert_id;
编辑:从数据库中获取数据的代码
C_Chewbacc,
我建议你阅读有关使用面向对象机制的PHP-MySQL连接的更多内容 http://in2.php.net/mysqli
请尝试以下代码
$sql = "SELECT * FROM Birthdays";
$result = $db -> query($sql); // SELECT query returns result object here
// We iterate over this result object and fetch each row on every iteration
// When the resultant object has nothing to return, NULL is initialised in $row
// When $row = NULL becomes the exit point of WHILE loop
while($row = $db -> fetch_array($result)){
var_dump($row); // This will display every row of data
}