使用php将数据插入MySQL数据库的问题

时间:2016-04-07 12:37:09

标签: php mysql

我试图使用php将数据插入表中。我这样做是为了注册用户而且工作正常,但我现在正试图提交评论并且我一直都会收到错误。我试图寻找答案,但我似乎无法弄清问题是什么。

我做了一些调试,我知道变量存储了正确的数据,并且php正在连接到正确的表,但是当我尝试将变量插入到表中时,它不起作用。< / p>

这是我的PHP:

 <?php
session_start();
$dbhost = 'localhost';
$dbuser = 'rlr17';
$dbpass = 'rlr17';
$dbname = 'rlr17';
$dbtable = 'bookclubreviews';

// connect to the database
$db = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql database '. mysql_error());

 $bookID=$_GET["bookID"];
 $userID=$_GET["userID"];
 $reviewTitle=$_GET["reviewTitle"];
 $reviewContent=$_GET["reviewContent"];
 $rating=$_GET["ratingToSubmit"];
 $reviewID= uniqid($id).date("ymd");               

if (!$db) {
    die('Not connected : ' . mysql_error());
} else {

}

// select the table
$dbselect = mysql_select_db($dbname);


if (!$dbselect) {
    die ('Can\'t use $dbname : ' . mysql_error());
} else {
    echo "connected to $dbname";
}

if ($bookID=='') {
    $bookID="empty";
}
if ($userID=='') {
    $userID="empty";
}
if ($reviewTitle=='') {
    $reviewTitle="empty";
}

if ($reviewContent=='') {
    $reviewTitle="empty";
}
if ($rating=='') {
    $rating="empty";
}

//the next 4 lines are to test that the right table is being connected to - it is, this works
$sql1="SELECT * FROM $dbtable WHERE userID='$userID'";
$result1 = mysql_query($sql1,$db);
$result4 = mysql_num_rows($result1);
echo "worked - $result4 <br>";

//This is the bit that I can't get to work. 
$insert = "INSERT INTO  $dbtable VALUES('$userID','$bookID','$reviewTitle','$reviewContent','$rating')";
$result=mysql_query($insert,$db); 

if ($result) {
    echo "review submitted". ".<br>"; 
    $data = '';
    include( 'home.php' ) ;

} else {  
    echo 'Error with submitting data <br>' . $bookID . $userID . $reviewTitle . $reviewContent . $rating . $reviewID . "<br> db: " .$db;  
} 
mysql_close($db);
?>

这是一个 screenshot of how my table is set up

这是我工作的链接 - http://itsuite.it.brighton.ac.uk/rlr17/bookClub/insertReview.php?bookID=5&userID=rlr17&reviewTitle=Test&reviewContent=test&ratingToSubmit=4

任何提示都将不胜感激!

1 个答案:

答案 0 :(得分:1)

您的表有6个字段,并且您尝试仅插入5个字段值。

如果您未在INSERT查询中提及字段列表,则表示您正在插入所有列。

试试这个(插入所有列):

$ratingId = '';
$insert = "INSERT INTO  $dbtable VALUES('$userID','$bookID','$reviewTitle','$reviewContent','$rating','$ratingId')";

或指定列名称

$insert = "INSERT INTO  $dbtable (userID,bookID,reviewTitle,reviewContent,rating)VALUES('$userID','$bookID','$reviewTitle','$reviewContent','$rating')";