【问题标题】:Not sure why posts aren't inserting into my database不知道为什么帖子没有插入我的数据库
【发布时间】:2013-07-15 14:12:17
【问题描述】:

我已经检查了我能想到的所有内容,但无法弄清楚为什么我的代码会创建错误消息并且没有插入数据库,我什至输入了 echo "
Select SQL = ".$sql2."
";在我的结果查询之前并得到以下数据...

Select SQL = INSERT INTO `posts`(post_topic, post_id, post_content, post_date, post_by)VALUES('3', '2', 'me too', '15/07/13 22:04:00', '1'
ERROR

检查值,一切正常,帖子加入的主题是 3,它是帖子表中的第二个帖子,“我也是”是正确的帖子内容,数据很好,会话 user_id 是1、不知所措,这里是页面的完整代码。

<?php
include 'core/init.php';
include 'includes/overall/header.php'; 

// Get value of id that sent from hidden field 
$id=$_POST['id'];

// Find highest answer number. 
$sql="SELECT MAX(post_id) AS Maxa_id FROM `posts` WHERE post_topic='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);

// add + 1 to highest answer number and keep it in variable name "$Max_id". if there no answer yet set it = 1 
if ($rows) {
$Max_id = $rows['Maxa_id']+1;
}
else {
$Max_id = 1;
}

// get values that sent from form 

$post_content=$_POST['post_content']; 

$datetime=date("d/m/y H:i:s"); // create date and time

// Insert answer 
$sql2="INSERT INTO `posts`(post_topic, post_id, post_content, post_date, post_by)VALUES('$id', '$Max_id', '$post_content', '$datetime', '" . $_SESSION['user_id'] . "'";
echo "<BR>Select SQL = ".$sql2."<BR>";
$result2=mysql_query($sql2);

if($result2){
echo "Successful<BR>";
echo "<a href='view_topic.php?topic_id=".$id."'>View your answer</a>";

// If added new answer, add value +1 in reply column 

$sql3="UPDATE `topics` SET reply='$Max_id' WHERE topic_id='$id'";
echo "<BR>Select SQL = ".$sql3."<BR>";
$result3=mysql_query($sql3);
}
else {
echo "ERROR";
}

// Close connection
mysql_close();
?>
<?php include 'includes/overall/footer.php'; ?>

【问题讨论】:

  • Please, don't use mysql_* functions in new code。它们不再维护and are officially deprecated。看到red box?改为了解prepared statements,并使用PDOMySQLi - this article 将帮助您决定哪个。如果选择 PDO,here is a good tutorial
  • 当你输入 "INSERT INTO posts(post_topic, post_id, post_content, post_date, post_by)VALUES('$id', '$Max_id', '$post_content', '$datetime', '" . $_SESSION['user_id'] . "'" 进入你的 phpmyadmin 你得到什么错误?
  • #1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以获取正确的语法,以便在第 1 行的 '"INSERT INTO posts(post_topic, post_id, post_content, post_date, post_by)VALUES(' 附近使用
  • 运行查询时,您似乎在 INSERT 语句之前包含了一个双引号。要对此进行调试,请获取 PHP 将运行的查询的内容,并在另一个环境中运行完全相同的语句。 (此外,您的日期时间格式对于 MySQL DATETIME 或 TIMESTAMP 不正确,日期部分的格式应为 YYYY-MM-DD,而不是 dd/mm/yy。

标签: php mysql insert


【解决方案1】:

在您缺少的 VALUES 语句的末尾),您现在只有“;”。

【讨论】:

    【解决方案2】:

    $sql2 末尾缺少右括号。没关系,每个人都会遇到。

    【讨论】:

    • 谢谢,虽然没有解决我的问题:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多