When I execute SQL into phpmyadmin, it gives the correct results (as you can see the two order_id's at the first column of the table are different):
However, when I call the SQL into PHP, it displays differently, displaying two rows of order ID #99:
This is the SQL:
SELECT o.order_id,o.farm_id,o.user_id,o.created,u.first_name,u.surname,u.email,
u.telephone_no,ua.user_id,ua.street,ua.town,ua.county,ua.postcode,bc.*
FROM orders o
LEFT JOIN users_address ua
ON ua.user_id = o.user_id
LEFT JOIN users u
ON ua.user_id = u.id
LEFT JOIN basket_checkout bc
ON ua.user_id = bc.user_id
WHERE o.farm_id = 10
AND bc.farm_id = o.farm_id
GROUP BY o.order_id
ORDER BY bc.order_id ASC
This is how I call the SQL into PHP:
<?php $query = "<the query>";
$data_set = mysqli_query($GLOBALS['connection'], $query);
confirm_query2($data_set, $query);
while ($row = mysqli_fetch_array($data_set)) { ?>
<tr>
<!-- Order ID -->
<td class='orders-table' style='font-size:16px;font-weight:bold;'>
<?php echo "<span><a href='{$view_order}.php?id=" . $row['order_id'] . "'>#" . $row['order_id'] . "</a></span>"; ?>
</td>
<!-- Name -->
<td class='orders-table'>
<?php echo "<span>" . $row['first_name'] . " " . $row['surname'] . "</span>"; ?>
</td>
<!-- Email -->
<td class='orders-table' style='word-wrap:break-word;'>
<?php echo "<span>" . $row['email'] . "</span>"; ?>
</td>
<!-- Telephone no. -->
<td class='orders-table' style='width:0px;'>
<?php $telephone_no = substr_replace($row['telephone_no'], '-<br />', 4, 0); ?>
<?php echo "<span>0" . str_replace("+44", "", $telephone_no) . "</span>"; ?>
</td>
<!-- Street -->
<td class='orders-table' style='text-align:left;'>
<?php echo "<span>" . $row['street'] . ",</span>"; ?><br />
<?php echo "<span>" . $row['town'] . ",</span>"; ?><br />
<?php echo "<span>" . $row['county'] . ",</span>"; ?><br />
<?php echo "<span>" . $row['postcode'] . "</span>"; ?>
</td>
<!-- Total -->
<td class='orders-table'>
<?php echo "<span>" . "£" . sprintf("%0.2f", $row['produce_total']) . "</a></span>"; ?>
</td>
<!-- Items -->
<td class='orders-table' style='width:0px;'>
<?php echo "<span>" . $row['total_items'] . "</a></span>"; ?>
</td>
<!-- Order created -->
<td class='orders-table'>
<?php echo "<span>"; if (date('Y-m-d', strtotime($row['created'])) == date('Y-m-d')) { echo "Today<br />" . date('(H:i)', strtotime($row['created'])); } else { echo date('d/m/y (H:i)', strtotime($row['created'])); } echo "</span>"; ?>
</td>
<!-- Processed -->
<?php if ($btn) { ?>
<td class='orders-table' style='width:0px;'>
<input type="submit" name="submit<?php echo $row['order_id']; ?>" value='Process' onclick="return confirm('Do you want to process this order?');" style='margin-left:1px;font-weight:bold;color:green;' />
</td>
<?php } ?>
<?php } ?>
Related
I have a modal with select value and when I post it I want to submit that values together with other values outside of the modal.
Here is the entire code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="myForm">
<table id="example" class="table table-bordered table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th><input name="select_all" value="1" id="example-select-all" type="checkbox" /></th>
<th>Client</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<?php echo '<input type=hidden name=fetched_devices_array[] value=' . $row['device_id'] . '>' ?>
<?php echo '<input type=checkbox name=devices[] value=' . $row['dev_id'] . '>' ?>
</td>
<td>
<?php echo $row["name"]; ?>
</td>
</tr>
<div class="modal" id="acceptModal">
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel">Select the return to manufacturer</h4>
</div>
<div class="modal-body">
<p>
<?php
$sql_return_to = $db->prepare("SELECT
users.id as user_id,
users.full_name,
users.role,
companies.company_name
FROM users
INNER JOIN companies ON users.company_id=companies.id
WHERE (users.role=? OR users.role=? OR users.role=? AND users.active=?)");
$sql_return_to->bind_param("iiii", $usr_type1, $usr_type2, $usr_type3, $active);
$sql_return_to->execute();
$result_ = $sql_return_to->get_result();
$result = [];
if ($result_->num_rows > 0) {
$result = $result_->fetch_all(MYSQLI_ASSOC);
}
$sql_return_to->close();
echo "<select class='device_manufacturer' name='device_manufacturer'>";
$nothing = "Nothing selected";
echo "<option value='" . $nothing . "'>" . $nothing . "</option>";
foreach ($result as $row) {
echo "<option value='" . $row['user_id'] . "'>" . $row['company_name'] . ' (' . explode(' ', trim($row['full_name']))[0] . ')' . "</option>";
}
echo "</select>"; ?>
</p>
<div id="wrapper">
<button type="button" id="buttonConfirm" onclick="SubmitFormData()" name="goback" class="btn">Confirm</button>
</div>
</div>
</div>
</tbody>
</table>
</form>
When I call :
function SubmitFormData() {
$("#myForm").submit(); // Submit the form
}
I am able to receive in PHP all the values outside the modal but not the one from the dropdown device_manufacturer . Why does that happen?
P.S: There are values in the dropdown in case you are wondering if it might be empty.
Interesting issue here...don't know where the problem is because I am using the code from another site that I have. The first site works perfectly and no problems...but when I converted it over to my new site, the total price amount won't calculate properly.
QUESTION: Am I missing something when I switched over my code? If I put the code below into the while loop it works ok with only ONE item, but not multiple and it doesn't look right if I change the location to this.
<div class="column text-lg">Subtotal: <span class="text-medium">$<?php echo $totalamount; ?></span></div>
Here is some images and the code that I have:
OLD WORKING CODE:
<?php
if ( ! isset($totalamount)) {
$totalamount=0;
}
$totalquantity=0;
if (!session_id()) {
session_start();
}
include ('core/connectdb.php');
$sessid = session_id();
$query = "SELECT * FROM cart WHERE cart_sess = '$sessid'";
$results = mysqli_query($connect, $query) or die (mysql_query());
if(mysqli_num_rows($results)==0)
{
echo '<div id="content" class="float_r"><div align="center"><h3>Your cart is empty.</h3> You can find our items on our product page.</div></div><div class="cleaner"></div>';
}
else
{
?>
<div id="content" class="float_r">
<div align="center"><h1>Shopping Cart</h1></div>
<table border="1" align="center" cellpadding="5">
<tr><td> Item Code</td><td>Quantity</td><td>Item Name</td><td>Price</
td><td>Total Price</td>
<?php
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
extract($row);
echo "<tr><td>";
echo $cart_itemcode;
echo "</td>";
echo "<td><form method=\"POST\" action=\"cart.php?action=change&icode=
$cart_itemcode\"><input type=\"text\" name=\"modified_quantity\" size=\"2\"
value=\"$cart_quantity\">";
echo "</td><td>";
echo $cart_item_name;
echo "</td><td>";
echo '$' . $cart_price . '';
echo "</td><td>";
$totalquantity = $totalquantity + $cart_quantity;
$totalprice = number_format($cart_price * $cart_quantity, 2);
$totalamount=$totalamount + ($cart_price * $cart_quantity);
echo '$' . $totalprice . '';
echo "</td><td>";
echo "<input type=\"submit\" name=\"Submit\" value=\"Change quantity\">
</form></td>";
echo "<td>";
echo "<form method=\"POST\" action=\"cart.php?action=delete&icode=$cart_itemcode\">";
echo "<input type=\"submit\" name=\"Submit\" value=\"Delete Item\"></form>
</td></tr>";
}
echo "<tr><td >Total</td><td>$totalquantity</td><td></td><td></td><td>";
$totalamount = number_format($totalamount, 2);
echo '$' . $totalamount . '';
echo "</td></tr>";
echo "</table><br>";
echo "<div style=\"width:400px; margin:auto;\">You currently have " .
$totalquantity . " product(s) selected in your cart</div> ";
?>
<table border="0" style="margin:auto;">
<tr>
<td><button style="font-family:verdana; font-size:150%;" onclick="goBack()">Go Back</button></td>
<td style="padding: 10px;">
<form method="POST" action="cart.php?action=empty">
<input type="submit" name="Submit" value="Empty Cart"
style="font-family:verdana; font-size:150%;" >
</form>
</td><td>
<?php include('cart_upload.php'); ?>
</td></tr></table>
</div>
<div class="cleaner"></div>
<?php
}
?>
NEW NON-WORKING CODE:
<?php
if ( ! isset($totalamount)) {
$totalamount=0;
}
$totalquantity=0;
if (!session_id()) {
session_start();
}
include ('core/connectdb.php');
$sessid = session_id();
$query = "SELECT * FROM cart WHERE cart_sess = '$sessid'";
$results = mysqli_query($connect, $query) or die (mysql_query());
if(mysqli_num_rows($results)==0)
{
echo '<div"><div align="center"><h3>Your cart is empty.</h3> You can find our items on our product page.</div></div>';
}
else
{
?>
<!-- Page Title-->
<div class="page-title">
<div class="container">
<div class="column">
<h1>Cart</h1>
</div>
<div class="column">
<ul class="breadcrumbs">
<li>Home
</li>
<li class="separator"> </li>
<li>Cart</li>
</ul>
</div>
</div>
</div>
<!-- Page Content-->
<div class="container padding-bottom-3x mb-1">
<!-- Shopping Cart-->
<div class="table-responsive shopping-cart">
<table class="table">
<thead>
<tr>
<th>Product Name</th>
<th class="text-center">Quantity</th>
<th class="text-center">Subtotal</th>
<th class="text-center"><a class="btn btn-sm btn-outline-danger" href="#">Clear Cart</a></th>
</tr>
</thead>
<tdbody>
<?php
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
extract($row);
$cart_price = number_format($cart_price);
echo '<tr>';
echo '<td>';
echo '<div class="product-item"><a class="product-thumb" href="shop-single.php?item=' . $cart_itemcode . ' "><img src="' . $cart_imagename . '" alt="' . $cart_item_name . '"></a>';
echo '<div class="product-info">';
echo '<h4 class="product-title">' . $cart_item_name . '</h4>';
echo '</div>';
echo '</div>';
echo '</td>';
echo '<td class="text-center">';
echo '<div class="count-input">';
echo '$' . $cart_price . ' Each';
echo "<form method=\"POST\" action=\"cart.php?action=change&icode=
$cart_itemcode\"><input type=\"text\" name=\"modified_quantity\" size=\"2\"
value=\"$cart_quantity\"><br\><input type=\"submit\" name=\"Submit\" value=\"Update\">
</form>";
echo '</div>';
echo '</td>';
$totalquantity = $totalquantity + $cart_quantity;
$totalprice = number_format($cart_price * $cart_quantity);
$totalamount= number_format($totalamount + ($cart_price * $cart_quantity));
echo '<td class="text-center text-lg text-medium">$' . $totalprice . '</td>';
echo '<td class="text-center"><a class="remove-from-cart" href="cart.php?action=delete&icode=' . $cart_itemcode . '" data-toggle="tooltip" title="Remove item"><i class="icon-cross"></i></a></td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
</div>
<div class="shopping-cart-footer">
<div class="column text-lg">Subtotal: <span class="text-medium">$<?php echo $totalamount; ?></span></div>
</div>
<div class="shopping-cart-footer">
<div class="column"><a class="btn btn-outline-secondary" onclick="goBack()"><i class="icon-arrow-left"></i> Back to Shopping</a></div>
<div class="column"><a class="btn btn-primary" href="#" data-toast data-toast-type="success" data-toast-position="topRight" data-toast-icon="icon-circle-check" data-toast-title="Your cart" data-toast-message="is updated successfully!">Update Cart</a><a class="btn btn-success" href="checkout-address.php">Checkout</a></div>
</div>
</div>
It looks like you're adding together formatted numbers, which is bound to be trouble. Don't do that. Keep your values as raw as possible internally and only format then if and when you display them to the user:
$totalquantity = $totalquantity + $cart_quantity;
$totalprice = $cart_price * $cart_quantity;
$totalamount = $totalamount + ($cart_price * $cart_quantity);
echo '<td class="text-center text-lg text-medium">$' . number_format($totalprice) . '</td>';
Remember, messy code is where bugs hide. Keep things clean, as if you're working in a kitchen. Always, always keep things organized. If you're stuck on a chunk of code and aren't sure why it works, the first thing you should do is clean it up. Then keep cleaning. Sometimes in the process of re-organizing the mistake becomes obvious.
So I found out the problem...at the top of my page I had this code:
if ( ! isset($totalamount)) {
$totalamount=0;
}
APPARENTLY for some reason the code was considering it to have value of 2.
Once I added this down towards the bottom before my while loop:
$totalamount=0;
Like magic it works properly now even with formatted numbers. I wanted to keep the formatted numbers since I didn't want any cents in my prices, just whole dollar amounts.
I finally get reviews to work, which will allow user to post their review about the product and display them in a review page with product details, however I can't get it to work perfectly. When a user posts their review, it will update in the table but only the second post will show up.
The following image is from the test i was running,
Before posting a review
After posting the first review
After posting the second review
As the images display, the first review will never show up, only starting from the second and above,
Here my code for review page updated with full 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>)
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>Home</li>
<li>Products</li>
<li>View Cart</li>
<li>About</li>
<li>Settings</li>
<li>Logoff</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>
and here the php file where I insert the review into the table
<?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();
?>
Problem:
As the images display, the first review will never show up, only starting from the second and above
That's because you're fetching the first row which includes the first review but you don't display it, rather you starting fetching next reviews and display them. Look at the two conditions in while block inside the else block.
Solution:
To display reviews, you should do something like this:
<?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
?>
The problem looks to me to be in your SQL query. It looks as though your SQL query should actually be doing a join on the related column to bring together data across two different tables
$sql="SELECT *
FROM products AS p,
JOIN reviews AS r
ON p.Product_Name = r.Product_Name
WHERE products.Product_Name = '$product'";
But I think the easiest solution would be to run another query within the table output loop where you get the reviews for the product name you are currently outputting and loop over those.
I have two files of php.First file is of seller status report.If I click on any record then a new tab(form) opens in new window.I have used window.open in js file.
Now in second form I have a html form.I want all field fill according to id.I am not familiar how to bind data in this case.
<?php
if
(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"myquery");
if (isset($_POST['from']) && isset($_POST['from']))
{
$a=$_POST['from'];
$b=$_POST['to'];
$result = mysqli_query($con,"myquery'");
}
else {
$result = mysqli_query($con,"myquery");
}
echo "<table id='example' class='display' border='1px' cellspacing='0' width='100%'>
<thead style='background:cadetblue'>
<tr class='rowname'>
<th>Name</th>
<th>email</th>
<th>contact_no</th>
<th>state</th>
<th>city</th>
<th>TargetCity</th>
<th>ProjectName</th>
<th>Price</th>
<th>Size</th>
<th>PropertyDescription</th>
<th>PaymentPlanName</th>
<th>SaleTimeHorizon</th>
<th>PaytmentCompleted_Percentage</th>
<th>CreatedOn</th>
</tr>
</thead>";
echo"<tfoot style='display: table-header-group;'>
<tr>
<th>Name</th>
<th>email</th>
<th>contact_no</th>
<th>state</th>
<th>city</th>
<th>TargetCity</th>
<th>ProjectName</th>
<th>Price</th>
<th>Size</th>
<th>PropertyDescription</th>
<th>PaymentPlanName</th>
<th>SaleTimeHorizon</th>
<th>PaytmentCompleted_Percentage</th>
<th>CreatedOn</th>
</tr>
</tfoot>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)) {
echo "<tr id='".$row['id']."'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['contact_no'] . "</td>";
echo "<td>" . $row['state'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "<td>" . $row['TargetCity'] . "</td>";
echo "<td>" . $row['ProjectName'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "<td>" . $row['Size'] . "</td>";
echo "<td>" . $row['PropertyDescription'] . "</td>";
echo "<td>" . $row['PaymentPlanName'] . "</td>";
echo "<td>" . $row['SaleTimeHorizon'] . "</td>";
echo "<td>" . $row['PaytmentCompleted_Percentage'] . "</td>";
echo "<td>" . $row['CreatedOn'] . "</td>";
echo "</tr>";
}
echo '<a href="download.php"><img src="images/Excel-Logo.jpg">
</a>';
echo"</tbody>";
echo "</table>";
mysqli_close($con);
?>
The second file is
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Buyer Form</title>
<link rel="stylesheet" type="text/css" href="CSS/master.css" />
<link rel="stylesheet" type="text/css" href="CSS/profilepage.css">
<link rel="stylesheet" type="text/css" href="CSS/bootstrap.css">
<link rel="stylesheet" type="text/css" href="CSS/jquery.datetimepicker.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.datetimepicker.js"></script>
<script type="text/javascript" src="js/datetime.js"></script>
</head>
<body>
<header class="full grey-bg btn-gryShdw pageHeader pos-r" id="header">
<div class="mr-r-15 mr-1-15" style="border-bottom:1px solid #ECECEC">
<div class="w100">
<div class="profilePic">
<img src="images/gravatar.jpg">
</div>
<div class="profileInfo w90" style="background-color:#1286f5">
<div class="f1 pos-r">
<div class="name ng-binding fl">Mayank</div>
<ul id="actions">
<li id="service" class="w30 txt-ac">Service</li>
<li id="status" class="w30 txt-ac">Status<br>Open</br></li>
<li id="user" class="w40 txt-ac">User Created On
<div class="date1">12 August</div></li>
</ul>
</div>
</div>
</div>
</div>
</header>
<div id="main" class="fl" style="width:100%">
<div id="content" class="pad5 fl mr-t5 " style="margin-bottom:25px;word-wrap:break-word ;width:20%;">
<form class="pad-l5 mr-t10 ">
<div id="name">Name</div>
<input type="text"/>
<br>
<br>
<div>Email</div>
<input type="text"/>
<br>
<br>
<div>Contact Number</div>
<input type="text"/>
<br>
<br>
<div>City</div>
<input type="text"/>
<br>
<br>
</form></div>
<div id="maindropdown" class="mr-t5 fl pad5" style="width:40%">
<div id="dropstatus" class="mr-t5 fl pad5">
<span>Status</span><br>
<select>
<option value="Gurgaon">Open</option>
<option value="Noida">Pending For Request</option>
<option value="Gurgaon">Close</option>
</select>
</div>
<div id="dropdownsub" class="mr-t5 fl pad5">
<span>SubStatus</span><br>
<select style="width:255px">
<option value="Not Known">Not Known</option>
<option value="Understood">Understood</option>
</select>
</div>
<div id="txtarea" class="mr-t10 pad-t50">Description/Notes<br>
<textarea rows="8" cols="50" style="width:100%"></textarea>
</div>
</div>
<div id="nextaction" class="mr-t6 fl pad5" style="width:35%">Next Action<br>
<div id=nextactiontxt class="mr-t5 fl pad5">
<textarea rows="3" cols="55"></textarea>
</div>
<div class="mr-t6 fl pad5 mr-t30">Next Action Date<br>
<input id="datetimepicker" type="text">
</div>
<div class="mr-t6 fl pad5 mr-t30">
<span>Next Action Responsible</span><br>
<select style="width:170px">
<option value="name1">Rohit Rahav</option>
<option value="name2">Vivek Aggarwal</option>
<option value="name3">Hitesh Singla</option>
<option value="name4">Soni</option>
<option value="name1">Mayank Vashist</option>
</select>
</div>
</div>
</div>
</body>
</html>
<?php
$mysqli=new mysqli("localhost","root","","realitycheck");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!($stmt = $mysqli->prepare("select id,CONCAT_WS(' ', u.firstname,u.lastname) AS Name
from p_sellservices p left join users u
on p.UserId=u.id left join rc_project pt on p.ProjectId=pt.ProjectId left join p_paymentplan pp on
p.PaymentPlanId=pp.PaymentPlanId left join rc_location lc on p.LocationId=lc.LocationId"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$out_id = NULL;
$out_Name = NULL;
if (!$stmt->bind_result($out_id, $out_Name)) {
echo "Binding output parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
while ($row=mysqli_fetch_array($stmt)) {
echo'<input type="text" id="name">';
}
?>
script of window.open is here
$(document).ready(function() {
$('#example').dataTable( {
"order": [[ 3, "desc" ]],
"pageLength": 100
} );
var table = $('#example').DataTable();
$("#example tfoot th").each( function ( i ) {
var select = $('<select><option value=""></option></select>')
.appendTo( $(this).empty() )
.on( 'change', function () {
var val = $(this).val();
table.column( i )
.search( val ? '^'+$(this).val()+'$' : val, true, false )
.draw();
} );
table.column( i ).data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
$(document).ready(function() {
$('#example').dataTable();
$('#example tbody tr').on('click', function () {
var id = $(this).attr("id");
window.open("new.php?uid="+id);
//alert( 'You clicked on '+name+'\'s row' );
} );
} );
} );
First, why are you using different jquery version at one time? That could cause errors because of changing functions from version to version.
For your Problem, you could use AJAX to send your request to your PHP-File and sending your result to Javascript to fill your HTML-Container dynamically.
See here: http://www.w3schools.com/ajax/default.ASP
I have a table like this full of orders, each customer will have multiple orders:
Customer ponumber quantity ..
customer1 234345 56
customer2 343454 34
customer1 w34234 54
customer5 332423 54
I'm trying to loop through each DISTINCT customer and print the corresponding orders with the following code.
<?php
include("php/database_connect.php");
$query = mysql_query("SELECT DISTINCT customer FROM orders");
$customer = mysql_fetch_array($query);
foreach($customer as $customers)
{
echo ' <li><h1>'. $customers . '</h1></li>';
$result = mysql_query("SELECT * FROM orders WHERE misc='new' AND customer='$customers' ORDER BY columnpos ASC ");
while($row = mysql_fetch_array($result))
{
echo'
<li id="id_' . $row['id'] . '">
<div class="card">
<table>
<tr>
<td>' . $row['customer'] . '</td>
<tr>
<td>P/O: ' . $row['ponumber'] . '</td>
</tr>
<tr>
<td>' . $row['partnumber'] . '</td>
</tr>
<tr>
<td><b>' . $row['quantity'] . '</b> x ' . $row['foil'] . '</td>
</tr>
<tr>
<td>' . $row['daterequired'] . '</td>
</tr>
<tr>
<td>' . $row['prep'] . '</td>
</tr>
</table>
<input class="hiddenid" type="hidden" value="' . $row['id'] . '" />
<input class="hiddenquantity" type="hidden" value="' . $row['quantity'] . '" />
<input class="hiddenpartnumber" type="hidden" value="' . $row['partnumber'] . '" />
<input class="hiddenfoil" type="hidden" value="' . $row['foil'] . '" />
</div>
</li>
';
}
}
?>
However the above code currently prints:
customer1 234345
customer1 w34234
customer1 234345
customer1 w34234
which seems odd... its not going through each customer.
any help is greatly appreciated!
Make only one DB query (better performance) but process the results before looping over them:
$result = mysql_query("SELECT * FROM orders WHERE misc='new' ORDER BY customer ASC ");
$ordersByCustomer = array(); // nested array. 1. level: customers, 2. level: orders
while(($row = mysql_fetch_assoc($result))) {
if(!array_key_exists($row['customer'], $ordersByCustomer)) {
$ordersByCustomer[$row['customer']] = array();
}
$ordersByCustomer[$row['customer']][] = $row;
}
foreach($ordersByCustomer as $customer=>$orders) {
echo ' <li><h1>'. $customer . '</h1></li>';
foreach($orders as $order) {
// rest of HTML code
}
}
I also encourage you to use a better separation of HTML and PHP, like so, using the alternative syntax for control structures:
<?php foreach($ordersByCustomer as $customer=>$orders): ?>
<li><h1><?php echo $customer; ?></h1></li>
<?php foreach($orders as $order): ?>
<li id="id_<?php echo $row['id'];?>">
<div class="card">
<table>
<tr><td><?php echo $order['customer']; ?></td></tr>
<!-- and so forth -->
<?php endforeach; ?>
<?php endforeach; ?>
Btw, you are not generating valid HTML. li element must be contained in ul or ol elements.
use
while($customer = mysql_fetch_array($query){
instead of
$customer = mysql_fetch_array($query);
foreach($customer as $customers)
{