因此,正如标题所述,如果表单通过了一些条件(用户已登录,用户之前没有对该产品投票,所有字段都已填写),我将尝试将数据插入 2 个表中.
当条件只是:
$sql = "SELECT productid FROM votes WHERE username='$username' LIMIT 1";
但我意识到,如果用户对任何产品进行了投票,他们的用户名就会出现在表格中,并且他们会在没有对产品投票的情况下失败。所以我只是补充说:
$sql = "SELECT productid FROM votes WHERE username='$username' AND productid='$id' LIMIT 1";
现在,如果我尝试将数据提交到数据库,它总是返回“插入投票表时出错”消息,但不返回 mysql_error() 并且显然不会在投票表中插入新行,但奇怪的是它确实更新了产品表。
我只是无法弄清楚发生了什么,所以如果有人可以帮助我诊断问题,我将非常感激!这是代码:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_POST['slider_surface'] !== "0" && $_POST['slider_edgewear'] !== "0" && $_POST['slider_centering'] !== "0" && $_POST['slider_corners'] !== "0"){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$slider_surface = $_POST['slider_surface'];
$slider_edgewear = $_POST['slider_edgewear'];
$slider_centering = $_POST['slider_centering'];
$slider_corners = $_POST['slider_corners'];
$id = preg_replace('#[^a-z0-9]#i', '', $_GET['id']);
session_start();
$username = $_SESSION['username'];
//check if user has already voted
mysql_select_db('products');
$sql = "SELECT productid FROM votes WHERE username='$username' AND productid='$id' LIMIT 1";
$query = mysql_query( $sql, $conn );
$uname_check = mysql_num_rows($query);
if ($username){
if ($uname_check < 1) {
$sql = "INSERT INTO votes ".
"(username,productid,votesurface,voteedgewear,votecentering,votecorners,datetime) ".
"VALUES('$username','$id','$slider_surface','$slider_edgewear','$slider_centering','$slider_corners', now())";
$retval = mysql_query( $sql, $conn );
$id='';
// Make sure the _GET product ID is set, and sanitize it
$id = preg_replace('#[^a-z0-9]#i', '', $_GET['id']);
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM products WHERE id='$id'") or die(mysql_error());
$product = mysql_fetch_array( $data );
$newvotecount = $product['votecount'] + 1;
$newsum_surface = $product['sumsurface'] + $slider_surface;
$newsum_edgewear = $product['sumedgewear'] + $slider_edgewear;
$newsum_centering = $product['sumcentering'] + $slider_centering;
$newsum_corners = $product['sumcorners'] + $slider_corners;
$sql = "UPDATE products SET votecount='{$newvotecount}', sumsurface='{$newsum_surface}', sumedgewear='{$newsum_edgewear}', sumcentering='{$newsum_centering}', sumcorners='{$newsum_corners}' WHERE id='$id'";
$retval2 = mysql_query( $sql, $conn );
if(! $retval){
die('Error inserting into votes table: ' . mysql_error());
}
else if(! $retval2){
die('Error inserting into products table: ' . mysql_error());
}
$grading_error = 'success';
mysql_close($conn);
} else
$grading_error = 'duplicateuser';
} else
$grading_error = 'nouser';
}
else
$grading_error = 'emptyfields';}
?>