回复发布两次所需的两个表问题(mysql,php)

时间:2015-12-01 17:46:28

标签: php mysql

我终于得到了评论工作,这将允许用户发布他们对产品的评论,并将其显示在带有产品详细信息的评论页面中,但是我无法让它完美地运作。当用户发布他们的评论时,它将在表格中更新,但只会显示第二篇文章。 以下图片来自我正在运行的测试,

当图像显示时,第一次检查将永远不会显示,仅从第二次及以上开始,

此处我的评论页面的代码已更新为完整代码

<?php
if (!isset($_SESSION)) {session_start();}  //start session
if (!isset($_SESSION['client_ID'])) {
	//echo "<script>alert('not logged in');</script>";
	header("Location: index.html"  );
	}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="keywords" content="Games, Gaming, PS4, PS3, XBOX, Video games">
<meta name="description" content="Games 4 You">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Games 4 You</title>
<link rel="stylesheet" type="text/css" href="Styles/ProductsStyle.css">
    <!-- javascript/jQuery -->
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

</head>
<body>
<!--Add the following script at the bottom of the web page (before </body></html>)
Support system using MyLiveChat.com
-->
<script type="text/javascript" async="async" defer="defer" data-cfasync="false" src="https://mylivechat.com/chatinline.aspx?hccid=42206151"></script>
 <script>// disable zoom to keep image fit and always in position
  document.firstElementChild.style.zoom = "reset";
// the above script will disable zoom in and out
  </script>

<script type="text/javascript">
// this will auto change the background image to the following 7 images which are in the root Images/
// this is set to change every five second
    // declare list of backgrounds
    var images = ['bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg'];

    // declare function that changes the background
    function setRandomBackground() {
        // choose random background
        var randomBackground = images[Math.floor(Math.random() * images.length)];

        // set background with jQuery
        $('body').css('background-image', 'url("Images/' + randomBackground + '")');
    }

    // declare function that sets the initial background, and starts the loop.
    function startLoop() {
        // Set initial background.
        setRandomBackground();

        // Tell browser to execute the setRandomBackground every 5 seconds.
        setInterval(setRandomBackground, 5 * 1000);
    }

    // One the page has finished loading, execute the startLoop function
    $(document).ready(startLoop);

</script>
<header id="header">
  <div class="container">

<center><img src="Images/Title.png" alt="Title"></div>
</center>
</header>
<center>
<nav>
	<?php
echo "<p> Welcome ".$_SESSION['client_name']."</p>";
	//create connection
   $con = new mysqli("localhost", "student", "student", "cib4003_h00233671_at");
	if ($con->connect_errno) { //failed
    echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
	}?>
	<div class="wrapper">
	<ul id="category" >
  <li><a href="Products.php">Home</a></li>
  <li><a href="Products.php">Products</a></li>
  <li><a href="Productscart.php">View Cart</a></li>
  <li><a href="About.php">About</a></li>
  <li><a href="Settings.php">Settings</a></li>
  <li><a href="logout.php">Logoff</a></li>
</ul>
</nav>
</div>
</center>
<main>

<h3>Available Products</h3>

	<?php
	
	$product = $_GET["RID"];
	$_SESSION["product_name_RID"] = $_GET["RID"];
	$sql="SELECT * FROM  products,reviews WHERE products.Product_Name = '$product' AND reviews.Product_Name = '$product'";
	//$sql="SELECT * FROM  reviews WHERE Product_Name = '$product'";
//		$sql="SELECT * FROM pizza,pizzacart WHERE pizza.Pizza_ID=pizzacart.Pizza_ID AND pizzacart.client_ID=".$_SESSION['client_ID'];

	
	//echo "connected to DB"; 
	//run SQL query
	$result = mysqli_query($con,$sql);
	//output result
	if(mysqli_num_rows($result)==0) //no records found
		{
				$sql="SELECT * FROM  products WHERE Product_Name = '$product'";
				$result = mysqli_query($con,$sql);
	//	echo "<p>no records in DB".mysqli_num_rows($result)."</p>";
	//	echo "<p><a href=products.php></a>"; 
	// link has been disable because i am using the <a for something else so i can't force the image to be in the center when using <a
	// so the result will only be image that tell the customers no products found click all or search with different data
		?>
		
		<table class="table-style-one">
		<tr>
		<th>Product Image</th>
		<th>Product Name</th>
		<th>Description</th>
		<th>Product Type</th>
		<th>Console Type</th>
		
		</tr>
		<?php
		
		while($row = mysqli_fetch_array($result)) { //loops through records
            echo "<tr>";
            echo "<td><img src='".$row['picture']."'/>";
            echo "<td>".$row['Product_Name']."</td>";
            echo "<td>".$row['Description']."  <center><b><br>".$row['Trailer']."<br></b></center></td>";
            echo "<td>".$row['Product_Type']."</td>";
			echo "<td>".$row['Console_Type']."</td>";
            echo "</tr>";
            }
			
		
			//end of loop 
            echo "</table>";
            echo "<p>No Reviews available for this product.<br> To post a review of this product, fill up the below form.</p>";
			
		 //end of else
			 }
				
		
		
		else
		{
		?>
		
		<table class="table-style-one">
		<tr>
		<th>Product Image</th>
		<th>Product Name</th>
		<th>Description</th>
		<th>Product Type</th>
		<th>Console Type</th>
		</tr>
		
		<?php
		
		while($row = mysqli_fetch_array($result)) { //loops through records
            echo "<tr>";
            echo "<td><img src='".$row['picture']."'/>";
            echo "<td>".$row['Product_Name']."</td>";
            echo "<td>".$row['Description']."  <center><b><br>".$row['Trailer']."<br></b></center></td>";
            echo "<td>".$row['Product_Type']."</td>";
			echo "<td>".$row['Console_Type']."</td>";
            echo "</tr>";
			echo "<br>";
			?>

		
		<?php
		while($row = mysqli_fetch_array($result)) {
		 echo "<table class=table-style-one align=center>";
     //       echo "<tr><th>Review ID</th><td>".$row['Review_ID']."</td></tr>";
			echo "<tr><th>Review By:</th><td>".$_SESSION['client_name']."</td></tr>";
            echo "<tr><th>Review Title</th><td>".$row['Review_Title']."</td></tr>";
			echo "<tr><th>Rate:</th><td>".$row['Review_Rate']."/5</td></tr>";
			echo "<tr><th>Review</th><td colspan=2>".$row['Review']."</td></tr>";
			echo "<tr><th>Submitted On</th><td>".$row['Review_Date']."</td></tr>";
			echo "<br>";
			?>
			<?php
            }
			
		
			//end of loop 
            echo "</table>";
            
		 //end of else
		}
		}
		
	
	?>
	
	<table class="table-style-one" align="center">
<tr>
<form method="POST" action="submitreview.php">
		<!--<th>Product Name:</th><td> <input type="text" size="30" id="ReviewTitle" name="ReviewTitle"  pattern=".{5,}"  required title="5 characters minimum" placeholder="Review Title"></td> -->
		<th>Review Title:</th><td> <input type="text"  required size="30" id="ReviewTitle" name="ReviewTitle"  pattern=".{5,}"  required title="5 characters minimum" placeholder="Review Title">  </td>
		<th>Rate: </th>		
		<td>
		<select name="Review_Rate" required>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
	</select>
		</td>
	<tr>
	<td colspan="4">
	<textarea name="WriteReview" id="WriteReview" required rows="10" cols="50" wrap="physical" placeholder="Write your Review here" style="margin: 0px; width: 437px; height: 150px;"></textarea>
	</td>
	</tr>
		<td align="center" colspan="2"><input type="submit" value="submit"></td>
		<td  colspan="2"><input type="Reset"></td>
  </form> </tr>
</table>
 </h2>
<br>
<br>
<br>
</main>
</body>
<footer>
<p>Made by Humaid Al Ali - H00233671</p>
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL, multilanguagePage: true}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
        
</footer>
</html>

这里是php文件,我把评论插入表格

<?php
if (!isset($_SESSION)) {session_start();}  //start session
if (!isset($_SESSION['client_ID'])) {
	//echo "<script>alert('not logged in');</script>";
	header("Location: index.html"  );
	}
?>

<?php
   //new connection
   $con = new mysqli("localhost", "student", "student", "cib4003_h00233671_at");
	if ($con->connect_errno) { //failed
    echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
	}

 //success 
//if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	// run sql 
	
	$sql ="INSERT INTO `cib4003_h00233671_at`.`reviews`(`Review_ID`, `Product_Name`, `client_ID`,  `Review_Title`, `Review_Rate`, `Review`) VALUES (NULL, '".$_SESSION['product_name_RID']."', '".$_SESSION['client_ID']."', '".$_POST["ReviewTitle"]."', '".$_POST['Review_Rate']."', '".$_POST['WriteReview']."');";
	if ($con->query($sql) === TRUE) {echo "<h3> New record created successfully</h3>";
	header('Location: '. $_SERVER['HTTP_REFERER']  );
	} else {
		echo "Error : " . $sql  . "<br>" . $con->error;
	}
	$con->close();
	
	
?>

2 个答案:

答案 0 :(得分:0)

问题在我看来是在你的SQL查询中。看起来您的SQL查询实际上应该在相关列上进行连接,以将数据汇集到两个不同的表中

     $sql="SELECT * 
     FROM products AS p,
     JOIN reviews AS r
     ON p.Product_Name = r.Product_Name
     WHERE products.Product_Name = '$product'";

但我认为最简单的解决方案是在表格输出循环中运行另一个查询,您可以在其中获取当前正在输出的产品名称的评论并循环显示。

答案 1 :(得分:0)

<强>问题:

  

当图像显示时,第一次检查将永远不会显示,仅从第二次及以上

开始

那是因为您正在获取包含第一个评论的第一行但您没有显示它,而是您开始获取下一个评论并显示它们。查看while块内else块中的两个条件。

<强>解决方案:

要显示评论,您应该执行以下操作:

<?php

    // your code

    if(mysqli_num_rows($result)==0){

        // your code

    }else{

        echo "<table class='table-style-one'>";
            echo "<tr>";
                echo "<th>Product Image</th>";
                echo "<th>Product Name</th>";
                echo "<th>Description</th>";
                echo "<th>Product Type</th>";
                echo "<th>Console Type</th>";
            echo "</tr>";

            // fetch first row, which also contains first review
            $row = mysqli_fetch_array($result);
            echo "<tr>";
                echo "<td><img src='" . $row['picture'] . "'/>";
                echo "<td>" . $row['Product_Name'] . "</td>";
                echo "<td>" . $row['Description'] . "<center><b><br>" . $row['Trailer'] . "<br></b></center></td>";
                echo "<td>" . $row['Product_Type'] . "</td>";
                echo "<td>" . $row['Console_Type'] . "</td>";
            echo "</tr>";
        echo "</table>";

        echo "<table class=table-style-one align=center>";
            echo "<tr>";
                echo "<th>Review ID</th>";
                echo "<th>Review By:</th>";
                echo "<th>Review Title</th>";
                echo "<th>Rate:</th>";
                echo "<th>Review</th>";
                echo "<th>Submitted On</th>";
            echo "</tr>";
        do{
            // display first review and then fetch rest of the reviews
            echo "<tr>";
                echo "<td>" . $row['Review_ID'] . "</td>";
                echo "<td>" . $_SESSION['client_name'] . "</td>";
                echo "<td>" . $row['Review_Title'] . "</td>";
                echo "<td>" . $row['Review_Rate'] . "/5</td>";
                echo "<td colspan=2>" . $row['Review'] . "</td>";
                echo "<td>" . $row['Review_Date'] . "</td>";
            echo "</tr>";
        }while($row = mysqli_fetch_array($result));
        echo "</table>";
        ?>
        </table>
        <?php
    }


    // your code

?>