How to bind data of html form using PHP - php

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

Related

How to submit values of a modal and values outside of modal at the same time?

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.

Why does my SQL query differ when displayed in PHP?

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 } ?>

How can I put a form for each row of a table

Here's the thing, I need to update a selected row from a table, so I'm putting a form for each row of it (Every single row has an update button) and when I click update, it doesn't submit, actually, doesn't do anything.
Here's my code, I'll be grateful with the solution.
<div class="table-responsive">
<table class="table table-condensed">
<thead class="">
<tr>
<th>ID</th>
<th>Project</th>
<th>Type</th>
<th>Kick-Off Date</th>
<th>Deadline Date</th>
<th>Current Ninja</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$q = $_GET['q'];
$sql="SELECT pr.project_name, pr.project_type, pr.project_start_date, pr.project_end_date, us.nombre, st.id_status, pr.id_project FROM NT_Projects as pr LEFT JOIN Project_Status as st on st.id_status = pr.id_status LEFT JOIN NT_Clients as cl on cl.id_client = pr.id_client LEFT JOIN usuarios as us on us.username = pr.username WHERE cl.id_client = $q";
$result = mysql_query($sql) or die(mysql_error());
$upt = 1;
while($row = mysql_fetch_array($result)) {
echo '
<div id="update-project">
<form method="post" action="sistema/_actions/updateProject.php" id="res-update-proj-'.$upt.'">';
$kickoff = date('m/d/Y', strtotime($row[2]));
$deadline = date('m/d/Y', strtotime($row[3]));
echo '<tr>';
echo '<td width="95px">
<input class="form-control" name="id_Proj" type="text" value="'.$row[6].'" readonly>
</td>';
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $kickoff . "</td>";
echo "<td>" . $deadline . "</td>";
echo "<td>" . $row[4] . "</td>";
echo '<td width="225px">';
echo '<select class="form-control" name="proj_Status">';
$qStatus = "SELECT * FROM Project_Status;";
$exStatus = mysql_query($qStatus);
while($rStatus = mysql_fetch_array($exStatus))
{
if($row[5] == $rStatus[0])
echo '<option value="'.$rStatus[0].'" selected>'.$rStatus[1].'</option>';
else
echo '<option value="'.$rStatus[0].'">'.$rStatus[1].'</option>';
}
echo '</select>
</td>
<td class="text-center">
<button type="submit" class="btn btn-sm btn-primary btn-UProj" value="res-update-proj-'.$upt.'">Update</button>
<div id="res-update-proj-'.$upt.'" style="width: 100%; margin:0px; padding:0px;"></div>
</td>
</tr>
</form>
</div>';
$upt = $upt + 1;
}
?>
</tbody>
</table>
</div>
That code is being called from another HTML with ajax
You cannot mix table tags with divs and forms according to the web standards. If you do, browser's HTML-parser will mix your tags in unpredictable way.
The only solution I know is to utilize CSS:
<div style="display: table">
<form style="display: table-row">
<div> style="display: table-cell"></div>
</form>
</div>

echo two tables issues required to post twice (mysql, php)

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.

jquery tablesorter problem

hello
i get some help here yesterday for a problem i was having tablesorter. if i run the backend query on its own it displays the results ok. but i call it from another page from dropdown it displays all records and no errors are being seen in firebug. where am i going wrong? thanks
this code works on its own.
getuserlog.php
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sample", $con);
$sql="SELECT * FROM logger_log WHERE idusr_log = '".$q."' order by datein_log desc";
$result = mysql_query($sql);
echo "<table id=\"userlog\" class=\"tablesorter\" cellspacing=\"1\">
<thead>
<tr>
<th align=\"left\">Ip Address</th>
<th align=\"left\">Date In</th>
<th align=\"left\">Date Out</th>
</tr>
</thead>";
echo "<tbody>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ip_log'] . "</td>";
echo "<td>" . date('d/m/Y H:i:s',strtotime($row['datein_log'])) . "</td>";
echo "<td>" . date('d/m/Y H:i:s',strtotime($row['dateout_log'])) . "</td>";
echo "</tr>";
}
echo"</tbody>";
echo "</table>";
mysql_close($con);
?>
<div id="pager" class="pager">
<form>
<img src="css/blue/first.png" class="first"/>
<img src="css/blue/prev.png" class="prev"/>
<input type="text" class="pagedisplay"/>
<img src="css/blue/next.png" class="next"/>
<img src="css/blue/last.png" class="last"/>
<select class="pagesize">
<option selected="selected" value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>
</form>
</div>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
<link href="css/blue/style.css" rel="stylesheet" type="text/css" />
<script>
$(function() {
$("#userlog")
.tablesorter({widthFixed: true, widgets: ['zebra']})
.tablesorterPager({container: $("#pager")});
});
</script>
and this is the page i am calling it from.
userlog.php
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuserlog.php?q="+str,true);
xmlhttp.send();
}
</script>
<div class="spacer"></div>
<div class="userlogTxt">This report shows all users who have logged in up until: <?php echo date("d/m/Y H:i:s"); ?></div>
<br />
<?php
$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db("sample") or die(mysql_error());
$result2 = mysql_query('SELECT * FROM user_usr ORDER BY name_usr ASC', $conn);
echo '<select name="users" onchange="showUser(this.value)">';
echo '<option value="selected">'. 'Select a user' . '</option>';
while ($row = mysql_fetch_assoc($result2))
{
echo '<option value="'.$row['id_usr'].'">'.$row['name_usr'].'</option>';
}
echo '</select>';
?>
<br /><br />
<div id="txtHint" class="userlogTxt">Logging information will be shown here.</div></div>
#inti
it is not pulling any date from the db. just displaying header and pager.
userlog.php
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
<link href="css/blue/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function showUser(str)
{
$.get("getuserlog.php?q="+str,function(response) {
$("#txtHint").html(response);
// Tablesorter will run, just after you loaded the ajax response
$("#userlog").tablesorter({widthFixed: true, widgets: ['zebra']})
.tablesorterPager({container: $("#pager")
});
});
}
</script>
<div class="spacer"></div>
<div class="userlogTxt">This report shows all users who have logged in up until: <?php echo date("d/m/Y H:i:s"); ?></div>
<br />
<?php
$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db("sample") or die(mysql_error());
$result2 = mysql_query('SELECT * FROM user_usr ORDER BY name_usr ASC', $conn);
echo '<select name="users" onchange="showUser(this.value)">';
echo '<option value="selected">'. 'Select a user' . '</option>';
while ($row = mysql_fetch_assoc($result2))
{
echo '<option value="'.$row['id_usr'].'">'.$row['name_usr'].'</option>';
}
echo '</select>';
?>
<br /><br />
<div id="txtHint" class="userlogTxt">Logging information will be shown here.</div></div>
getuserlog.php
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sample", $con);
$sql="SELECT * FROM logger_log WHERE idusr_log = '".$q."' order by datein_log desc";
$result = mysql_query($sql);
echo "<table id=\"userlog\" class=\"tablesorter\" cellspacing=\"1\">
<thead>
<tr>
<th align=\"left\">Ip Address</th>
<th align=\"left\">Date In</th>
<th align=\"left\">Date Out</th>
</tr>
</thead>";
echo "<tbody>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ip_log'] . "</td>";
echo "<td>" . date('d/m/Y H:i:s',strtotime($row['datein_log'])) . "</td>";
echo "<td>" . date('d/m/Y H:i:s',strtotime($row['dateout_log'])) . "</td>";
echo "</tr>";
}
echo"</tbody>";
echo "</table>";
mysql_close($con);
?>
<div id="pager" class="pager">
<form>
<img src="css/blue/first.png" class="first"/>
<img src="css/blue/prev.png" class="prev"/>
<input type="text" class="pagedisplay"/>
<img src="css/blue/next.png" class="next"/>
<img src="css/blue/last.png" class="last"/>
<select class="pagesize">
<option selected="selected" value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>
</form>
</div>
where have i gone wrong? thanks
I recommend you, to use the jQuery Ajax functions in userlog.php, and since the script inside getuserlog.php is constant, move it to the userlog.php, something like this:
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
<link href="css/blue/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function showUser(str)
{
$.get("getuserlog.php?q="+str,function(response) {
$("#txtHint").html(response);
// Tablesorter will run, just after you loaded the ajax response
$("#userlog").tablesorter({widthFixed: true, widgets: ['zebra']})
.tablesorterPager({container: $("#pager")});
});
}
</script>
EDIT: Put all you javascript in the main page. The ajax response should only contain the data you want to get from the server.

Categories