MrDaisy Posted December 2, 2015 Share Posted December 2, 2015 Dear all, i have been working in my college project and i reached a point were i can't get my cart orders into Order history, as it's not working and keep giving me the following error page, Error : INSERT INTO `cib4003_h00233671_at`.`orderhistory`(`order_id`, `Product_ID`, `Product_Name`, `client_ID`, `quantity`) VALUES ('', '', '', '2', '');Duplicate entry '0' for key 'PRIMARY' ^ i checked the databse and all values are 0 except the Client_ID... thats why i am getting Duplicate entry, however, i tried to fix the problem for the past few hours and i can't find the issue, here my cart page code <?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>)--> <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"; </script> <script type="text/javascript"> // 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><!-- start with main tags which will include the php and tables --> <h3>Order Check Out</h3><!-- text above the table using style to move it --> <?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 // run sql $sql="SELECT * FROM products,clientscarts WHERE products.Product_Name=clientscarts.Product_Name AND clientscarts.client_ID=".$_SESSION['client_ID']; $result = mysqli_query($con,$sql); //output if(mysqli_num_rows($result)==0) //no records found { header("Location: products.php" ); } else // records were found in DB { //echo "<p>You have: ".mysqli_num_rows($result)." pizza(s)</p>"; // echo "<p>You have: ".$totalPizza." pizza(s)</p>"; ?> <?php ?> <table class="table-style-one" align="center"> <tr> <th>Order ID</th> <th>Product Name</th> <th>Product Image</th> <th>Price ($)</th> <th>quantity</th> </tr> <?php while ($row =mysqli_fetch_array($result)){ echo "<tr>"; echo "<td size=2>".$row['Order_ID']."</td>"; echo "<td><center><img src='".$row['picture']."'</center>"; echo "<td size=2>".$row['Product_Name']."</td>"; if ($_SESSION['User_Type'] == "VIP" && $row['Discount_VIP'] < 1 ){ echo "<td>".($row['Price'] * $row['Discount_VIP'] )."$<h4 style=font-size:3> After Discount</h1></td>"; } else if ($_SESSION['User_Type'] == "Platinum" && $row['Discount_Platinum'] < 1 ){ echo "<td>".($row['Price'] * $row['Discount_Platinum'] )."$<h4 style=font-size:3> After Discount</h1></td>"; } else if ($_SESSION['User_Type'] == "Gold" && $row['Discount_Gold'] < 1 ){ echo "<td>".($row['Price'] * $row['Discount_Gold'] )."$<h4 style=font-size:3> After Discount</h1></td>"; } else if ($_SESSION['User_Type'] == "Silver" && $row['Discount_Silver'] < 1 ){ echo "<td>".($row['Price'] * $row['Discount_Silver'] )."$<h4 style=font-size:3> After Discount</h1></td>"; } else { echo "<td>".$row['Price']."$ </td>"; } echo "<td><center><a href='increasequantity.php?PID=".$row['Order_ID']."'/><h4>Increase ➕</h4></a>".$row['quantity']."<a href='decreasequantity.php?PID=".$row['Order_ID']."'/><h4>Decrease ➖</h4></a></center></td>"; $total=$total+($row['Price']*$row['quantity']); $totalGames=$totalGames+($row['quantity']); } echo "<center>"; echo "<tr><td colspan='5'><center>Total of<b> ".$totalGames."</b> Game's with total of <b>".$total."$</b> </center></td>"; // echo "<form method=POST action=OrderHistory.php?HID='".$row['order_id']."'>"; echo "<tr> <th>Payment option:</th> <td><select name='paymentoption'><option>MasterCard</option><option>Visa</option><option>Pay in delivery</option></select></td> <td><img src=Images/CC.gif alt=CC></td> </tr>"; echo "<tr> <th>Name of Card Holder: </th> <td><input type=text size=35 maxlength=35 name=NCH required placeholder=Enter Card holder name></td> <td rowspan='3'><img src=Images/Front-of-Card.png alt=CCFront></td> </tr>"; echo "<tr> <th>Card Number: </th> <td><input type=text size=19 name=CardN placeholder=1234-5678-9012-3456 pattern=[0-9]* maxlength=19 required title=19 characters Maximum> </td> </tr>"; echo "<tr> <th>Expiration date: </th> <td> <input type=text size=2 maxlength=2 name=YED pattern=.{2,} required title=2 characters Maximum placeholder=Month> <input type=text size=4 maxlength=4 name=YED pattern=.{4,} required title=4 characters Maximum placeholder=Year> </td> </tr>"; echo "<tr> <th>CCV: </th> <td> <input type=text size=3 maxlength=3 name=CardN pattern=.{3,} required title=3 characters Maximum placeholder=CCV> </td> <td><img src=Images/Back-of-Card.png alt=CC></td> </tr>"; echo "<td colspan=3 align=center><a href='OrderHistory.php?HID='".$row['order_id']."'><img width=200 height=96 src=Images/checkout.png></a></td>"; //echo "<td align=center colspan=3><input type=submit value=submit></td>"; echo "</center"; echo "</tr>"; echo "</table> "; } ?> </h2> </main> </body> <!-- main tag closed followed by closing body tag --> <footer><!-- footer start here with in-line style plus using underline for website link HCT Portal --> <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><!-- Close footer --> </html><!-- close HTML tag --> and here my history php where i do the insert part <?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 if (!isset($_GET['HID'])) { header("Location: index.html" ); } //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 // run sql $sql ="INSERT INTO `cib4003_h00233671_at`.`orderhistory`(`order_id`, `Product_ID`, `Product_Name`, `client_ID`, `quantity`) VALUES ('".$_GET['HID']."', '".$_GET['Product_ID']."', '".$_GET['Product_Name']."', '".$_SESSION['client_ID']."', '".$_GET['qty']."');"; if ($con->query($sql) === TRUE) {echo "<h3> New record created successfully</h3>"; header("Location: Products.php" ); } else { echo "Error : " . $sql . "<br>" . $con->error; } $con->close(); ?> Link to comment Share on other sites More sharing options...
justsomeguy Posted December 2, 2015 Share Posted December 2, 2015 You need to give each record a unique primary key, that's the point of a primary key. If your primary key is an autoincrement field then just leave it out of the insert query and the database will assign the next ID. Link to comment Share on other sites More sharing options...
MrDaisy Posted December 2, 2015 Author Share Posted December 2, 2015 i did the following, added a primary key for OrderHistoryID and change the insert into, $sql ="INSERT INTO `cib4003_h00233671_at`.`orderhistory`(`OrderHistoryID`,`order_id`, `Product_ID`, `Product_Name`, `client_ID`, `quantity`) VALUES (NULL, '".$_GET['HID']."', '".$_GET['Product_ID']."', '".$_GET['Product_Name']."', '".$_SESSION['client_ID']."', '".$_GET['qty']."');"; however, still the database empty after the insert Link to comment Share on other sites More sharing options...
justsomeguy Posted December 3, 2015 Share Posted December 3, 2015 You already had a primary key: Duplicate entry '0' for key 'PRIMARY'But whatever. You should switch your queries to use prepared statements, when you put data directly in your query it's bound to cause a problem. Many web sites get compromised because that's what the programmer did, and it can also cause queries to fail. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php You should create a prepared statement with placeholders for the data, and then pass the data directly to MySQL when you execute the statement. MySQL will handle the data correctly. The query that you prepare should look like this: $sql ="INSERT INTO `cib4003_h00233671_at`.`orderhistory`(`order_id`, `Product_ID`, `Product_Name`, `client_ID`, `quantity`) VALUES (?, ?, ?, ?, ?);";Placeholders for the data, and then you pass the values to MySQL using bind_param like the manual shows. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now