I have an html page that gets data from 'hs_hr_employee' table and lays the info in a table on a web page. Then I have another table 'rights' which gets info from 4 columns from the 'hs_hr_employee' table and stores them in columns. In addition to those 4, the 'rights' table has an extra column 'Permissions'.
Now, I have a combobox with 4 options. When I click the 'Save' button I want to store the value select in the combobox and save it in the 'rights' table in relation to the user.
(Each user has a combobox next to it).
Updated code:
<?php
$connection = mysql_connect('localhost','admin','root');
if( isset($_POST['submit']) )
{
if( isset( $_POST['cb_permissions'] ) && is_array( $_POST['cb_permissions'] ))
{
foreach( $_POST['cb_permissions'] as $emp_number => $permission)
{
$sql = "UPDATE `your_permission_table` SET permission='".mysql_real_escape_string($permission)."' WHERE emp_number='".mysql_real_escape_string($emp_number)."'";
echo __LINE__.": sql: {$sql}\n";
mysql_query( $sql );
}
}
}
?>
<p style="text-align: center;">
<span style="font-size:36px;"><strong><span style="font-family: trebuchet ms,helvetica,sans-serif;"><span style="color: rgb(0, 128, 128);">File Database - Administration Panel</span></span></strong></span></p>
<p style="text-align: center;">
</p>
<head>
<style type="text/css">
table, td, th
{
border:1px solid #666;
font-style:Calibri;
}
th
{
background-color:#666;
color:white;
font-style:Calibri;
}
</style>
</head>
<form method="post" action="admin.php">
<?php
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('users', $connection);
$result = mysql_query("SELECT emp_number, employee_id, emp_lastname, emp_firstname FROM hs_hr_employee");
echo "<center>";
echo "<table >
<tr>
<th>Employee Number</th>
<th>Employee ID</th>
<th>Surname</th>
<th>Name</th>
<th>Permissions</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['emp_number'] . "</td>";
echo "<td>" . $row['employee_id'] . "</td>";
echo "<td>" . $row['emp_lastname'] . "</td>";
echo "<td>" . $row['emp_firstname'] . "</td>";
echo "<td> <select name='cb_permissions['".$row['emp_number']."'><option value='all'>All</option> <option value='remote'>Remote Gaming</option> <option value='landbased'>Landbased Gaming</option> <option value='general'>General Gaming</option> </select> </td>";
echo "</tr>" ;
}
echo "</table>";
echo "</center>";
echo mysql_query('INSERT into rights(Emp_num, ID, Name, Surname) SELECT emp_number, employee_id, emp_firstname, emp_lastname FROM hs_hr_employee');
$_POST['cb_permissions'];
mysql_close($connection);
?>
<p style="text-align: center;">
</p>
<p style="text-align: center;">
</p>
<p style="text-align: right;">
<input name="Save_Btn" type="button" value="Save" />
</p>
</form>
Any help on how I can do it?
Screenshot to get a basic idea of what I'm doing:
First of all, you should move connection code at the very top of your documents:
$connection = mysql_connect('localhost','admin','root');
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('users', $connection);
Next, you have to wrap your table inside tag:
<form method="post" action="target_url.php>
<table>
...
</table>
<input type="submit" name="submit" value="Save"/>
</form>
After that, you would store employee_id or emp_number (depending on what table key you will use for setting permission) somewhere on your form:
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['emp_number']; ?></td>
<td><?php echo $row['employee_id']; ?></td>
<td><?php echo $row['emp_lastname']; ?></td>
<td><?php echo $row['emp_firstname']; ?></td>
<td><select name="cb_permissions['<?php echo $row['emp_number']; ?>']">
<option value='all'>All</option>
<option value='remote'>Remote Gaming</option>
<option value='landbased'>Landbased Gaming</option>
<option value='general'>General Gaming</option>
</select></td>
</tr>
<?php
}
Then, on your target_url.php, you will have to do:
If target_url.php is the same as your form, then code below should be placed at the very top of your document.
<?php
if( isset($_POST['submit']) )
{
if( isset( $_POST['cb_permissions'] ) && is_array( $_POST['cb_permissions'] ))
{
foreach( $_POST['cb_permissions'] as $emp_number => $permission)
{
$sql = "UPDATE `your_permission_table` SET permission='".mysql_real_escape_string($permission)."' WHERE emp_number='".mysql_real_escape_string($emp_number)."'";
echo __LINE__.": sql: {$sql}\n";
mysql_query( $sql );
}
}
}
?>
That's it.
i suggest:
Use require_once( "db_connect.php" ) <- in this file make connection
Use smarty & html_options to show this drop down.
1 time your will learn this, next - using. Code will start be organized ...
Maybe to complex for starter. But this is right Way.
Related
i need to get the counting of the table rows in order as a column in column "N"
also i need to make the column"N" width looks smaller than others columns
i think i have done everything but this is the only point i couldn't achieved
the output should be as the picture :
i hope you could help me guys, thank you
here is my codes :
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
// DataBase connection
$host = "localhost";
$user = "root";
$password = "";
$db = "worksheet9";
$con = mysqli_connect($host, $user, $password, $db);
//verfiy Connection
if( mysqli_connect_errno()) {
echo " Connection Error:" . mysqli_connect_error();
}
if(isset($_POST['submit'])) {
$task=$_POST['task'];
// insert sql query
$sql = "INSERT INTO dolist (task) VALUES ('$task')";
$result=mysqli_query($con, $sql);
// verify query
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
<form method='POST'>
<input type="text" name="task" id="task" required
placeholder="add task" oninvalid="this.setCustomValidity('you must fill the task')"
oninput="this.setCustomValidity('')">
<input type="submit"name="submit"value="add task" ><!-- comment -->
</form>
<table border="1">
<tr>
<th> N </th>
<th>ID </th>
<th>task</th>
<th>delete</th><!-- comment -->
<th>update</th>
</tr>
<?php
// Select sql query
$sql = "SELECT ID,task FROM dolist";
$result = mysqli_query($con, $sql);
while ($rows = mysqli_fetch_array($result)) {
echo"<form method ='POST'>";
echo "<tr>";
echo "<td>" . "<input type='number' readonly name='number' value='" . $rows[''] . "'></td>";
echo "<td>" . "<input type='text' readonly name='id' value='" . $rows['ID'] . "'></td>";
echo "<td>" . "<input type='text' name='task' value= '" . $rows['task'] . "'></td>";
echo "<td>" . "<input type='submit' name='delete' value='x'>" . "</td>";
echo "<td>" . "<input type='submit' name='update' value='update'>" . "</td>";
echo "</tr>";
echo "</form>";
}
if(isset($_POST['update'])) {
$sql = "UPDATE dolist SET task='$_POST[task]'WHERE ID=$_POST[id]";
$result = mysqli_query($con,$sql) or die(mysqli_connect_errno());
if($result){
echo "updated";
} else {
echo "update faild";
}
}
//perform only when the user click on Delete
if(isset($_POST['delete'])) {
$sql = "DELETE FROM dolist WHERE ID=$_POST[id]";
$result = mysqli_query($con,$sql) or die(mysqli_connect_errno());
if($result){
echo "DELETED";
}else{
echo "delete faild";
}
}
?>
</table>
</body>
</html>
For row numbering add a counter to your PHP code:
$rowNumber = 1;
while ($rows = mysqli_fetch_array($result)){
echo"<form method ='POST'>";
echo "<tr>";
echo "<td>" . $rowNumber++. "</td>";
// echo other fields...
echo"</tr>";
For formatting, give your table an ID (not essential but it makes the CSS styling more specific)
This should then generate HTML like this:
<table id="results">
<tr><th>N</th><th>ID</th><th>task</th><th>Delete</th><th>Update</th></tr>
<tr><td>1</td><td>11</td><td>task</td><td>X</td><td>Update</td></tr>
<tr><td>2</td><td>12</td><td>task</td><td>X</td><td>Update</td></tr>
</table>
Now you can style it with CSS:
/* Border around the table */
#results {
border: 1px solid grey;
}
/* Border around the individual cells */
#results th, #results td {
border: 1px solid gray;
}
/* Set the width of the first TH. Also sets the width of the res of the column */
#results th:first-of-type {
width:1em;
}
/* Set the width of the 3rd column (the 'task' column */
#results th:nth-of-type(3) {
width:10em;
}
Output:
Note: you could do this by adding class attributes to the <th> elements and styling those. It makes for easier maintenance later.
Use of formatting attributes in HTML tags (like BORDER="1") is considered bad practice and should be avoided.
Don't use JS or PHP to count something pure CSS can help you with
Use CSS Counters
Use <thead> and <tbody> table elements
Use width: 0%; for the td you want really condensed in width
.tbodyCount {
counter-reset: rowIndex;
}
.tbodyCount tr {
counter-increment: rowIndex;
}
.tbodyCount td:nth-child(1)::before {
width: 0%; /* Make as smaller as possible */
content: counter(rowIndex); /* Learn about counters*/
}
<table>
<thead>
<tr>
<th>N</th>
<th>ID</th>
</tr>
</thead>
<tbody class="tbodyCount">
<tr>
<td></td>
<td>Foo</td>
</tr>
<tr>
<td></td>
<td>Bar</td>
</tr>
<tr>
<td></td>
<td>Baz</td>
</tr>
</tbody>
</table>
My table is not filling all the data i need. Is missing some columns be filled with form multiple. The column where the th is Renault need to be the same for all the rest are empty.
In next picture, you can see when i select options in dynamic selectbox multiple and submit, is only filling in the first column when the expectable is fill all the columns selected.
Next is the code where is giving the value of the select box multiple.
if ($consulta !=0) {
}//
else{
echo "";
}
#$s1= $_POST['s1'];
if( is_array($s1)){
while (list ($key, $val) = each ($s1)) {
}
}//
else{
echo "";
}
/////////////////
#$s2= $_POST['s2'];
if( is_array($s2)){
?>
Next is the code where data is filled in the html table. That line of code<td align=\"center\" bgcolor='FFFFFF'> need to be associate the result of: <?php echo "$key => $val1\n";?> to which form:
The result of <?php echo "$key => $val1\n";?>
0 => Renault 1 => Opel 2 => Mercedes 3 => Audi
The expected output is missing.
Renault
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
Opel
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
Mercedes
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
Audi
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
That is dynamic, will get the values from mysql database and i can select which i want.
There is all the table where is filled the data. Static and dynamic.
<table>
<tbody>
<tr>
<th>Parametro:</th>
<?php
while (list($key, $val1) = each ($s2)) {
?>
<th><?= htmlspecialchars($val1, ENT_HTML5 | ENT_COMPAT, 'UTF-8') ?></th>
<?php
echo "$key => $val1\n";
?>
<?php
}
?>
The values down of the Parametro:
{
echo("<tr>
<td align=\"center\" bgcolor='FFFFFF'>$utilizador</td>
<td align=\"center\" bgcolor='FFFFFF'>
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
");
Code from the form:
$con = mysqli_connect( "localhost","root","","teste" ); // ◄■ CONNECT TO DATABASE.
$dat_menuid = mysqli_query( $con,"SELECT * FROM menu WHERE menuId = '".$menuId."'" ) // ◄■ MENUIDs.
or die( mysqli_error($con) );
$con1 = mysqli_connect( "localhost","root","","teste" ); // ◄■ CONNECT TO DATABASE.
$idtem = mysqli_query($con1, "SELECT MAX(id_tem) as id_tem FROM tem")
or die( mysqli_error($con) );
// Print out result
while($row = $idtem->fetch_assoc())
$toEcho = $row["id_tem"];
//echo $toEcho;
$toEchosave = $toEcho + 1;
$_SESSION['myvar'] = $toEchosave;
$options = array( "0.00","0.05","0.10","0.15","0.20","0.25","0.30","0.35","0.40","0.45","0.50","0.55","0.60","0.65","0.70","0.75","0.80","0.85","0.90","0.95","1" ); // ◄■■ OPTIONS ARE STATIC (ALWAYS THE SAME).
while ( $row_menuid = mysqli_fetch_array( $dat_menuid ) ) // ◄■ DISPLAY <SELECT>s.
{ echo "<select class='sumselect' name='corp_resp&{$row_menuid['menuId']}&{$_SESSION['UtilizadorID']}&{$dateTime}&{$toEchosave}' multiple>"; // ◄■■ CORP_RESP&1,CORP_RESP&2.
foreach ($options as $opt)
echo "<option value='$opt'>$opt</option>\n";
echo "</select>\n";
} ?>
</form>
</td>
</tr>
<?php } ?>
<?php }
}
}
?>
<div id='sum'></div>
<br><br><br>
</tbody>
</table>
follow this code
<?php
$sql = "SELECT * FROM menu WHERE $id = menuIdPai ORDER BY menuId ";
$consulta = mysql_query($sql);
while ($mostrar = mysql_fetch_array($consulta)) {
$id = $mostrar['menuId'];
$utilizador = $mostrar['menuNome'];
?>
<tr>
<td align=\"center\" bgcolor='FFFFFF'>Test1</td>
<td align=\"center\" bgcolor='FFFFFF'>Test2</td>
<td align=\"center\" bgcolor='FFFFFF'>Test3</td>
<td align=\"center\" bgcolor='FFFFFF'>Test4</td>
</tr>
<?php
}
?>
this is main format if work then update your code . you add 2 td but your main th 4 so need 4 td
your this tag not close
<td align="center" bgcolor='FFFFFF'>
<form onsubmit="return validate();" id="teste" method="post" action="teste.php">
so close this in your script
<div id='sum'></div>
<br><br><br>
</form>
</td>
</tr>
move this code before end loop
foreach ($options as $opt)
echo "<option value='$opt'>$opt</option>\n";
echo "</select>\n";
} ?>
</form>
</td>
</tr>
<?php } ?>
<?php }
}
}
?>
<div id='sum'></div>
<br><br><br>
</tbody>
</table>
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 a table with the table headings below. Each row of that table populates info from a database. One of those columns (category) is a drop down menu (with a LOT of entries), so I've used a separate table to pull the values from. When a user submits the page with the drop down value selected, I want them to see the value they chose last time, as they may have to come back to this form multiple times. If you look at where the var_dump is, I can see that it's pulling the previously selected values from the database, but when I try to use the very same $row["category"] entry in the selected = $row["category"] I get the first entry in the drop down list, NOT the selected value (which was again verified as existing with the var_dump). I have no idea why this is happening and have spent DAYS trying to figure this out before asking the community here. Thanks for any help you can provide.
<body>
<table>
<tr>
<th scope="col">Date</th>
<th scope="col">Amount</a></th>
<th scope="col">Vendor</th>
<th scope="col">Description</th>
<th scope="col">Category</th>
<th scope="col">Notes</th>
<th scope="col">Bind Values?</th>
<th scope="col">Trip</th>
<th scope="col">Last Updated</th>
<th scope="col">Updated By</th>
<th scope="col">Done</th>
</tr>
<?php
$category_query = "SELECT * FROM category order by category_name ASC";
$category_result = mysqli_query($connection, $category_query);
$category_options = NULL;
while ($category = mysqli_fetch_assoc($category_result)) {
$category_options .= sprintf("<option value='%s'>%s</option>".PHP_EOL, $category["category_name"], $category["category_name"]);
}
?>
<form action="process_table.php" method="post">
<?php
$transactions_query = "SELECT transactions_id, `date`, amount, vendor, description, category , trip, last_updated, last_updated_by, done, notes\n"
. "FROM users, transactions\n"
. "WHERE users.user_name = '{$_SESSION["user"]}' AND users.users_id = transactions.users_id";
$transactions_result = mysqli_query($connection, $transactions_query);
while ($row = mysqli_fetch_assoc($transactions_result)) {
$id = $row["transactions_id"];
var_dump($row["category"]);
?>
<tr>
<td><?php echo date("F d, Y", strtotime($row["date"]));?></td>
<td><?php echo number_format($row["amount"], 2);?></td>
<td><?php echo $row["vendor"];?></td>
<td><?php echo $row["description"];?></td>
<td> <?php
if ($row["done"] == "checked") {
echo '<select selected ="'.$row["category"].'" name="expense['.$id.'][category]">'.$category_options.'</select>';
} else {
echo "DUMB"/*'<select name="expense['.$id.'][category]">'.$category_options.'</select>'*/;
}
?>
</td>
<td><?php echo "<textarea name='expense[" . $id . "][notes]'>" . $row["notes"] . "</textarea>";?></td>
<td><input name="bind" type="checkbox" value="YES"></td>
<td nowrap="nowrap">Trip place holder</td>
<td><?php echo date("m/d/Y")?></td>
<td>
<?php
if (!isset($_SESSION["user"])) {
echo "temp" ;
} else {
echo $_SESSION["user"];
}
?>
</td>
<td><?php echo "<input name='expense[" . $id . "][done]' type='checkbox'"?> <?php if($row["done"] == "checked") {
echo "checked = 'checked'>";
} else {
echo ">";
}
?>
</td>
</tr>
<?php
}
?>
</table>
<input name="submit" type="submit" id="submit" >
</form>
</body>
To show a option as selected, you need to apply the attribute selected="selected" to the <option> not the <select> element - The attribute as you currently have it will just be ignored, where most browsers will default to the first item in the list.
Change this:
<select selected ="'.$row["category"].'"
To this:
<select name="name">
<option value="option1">Value 1</option>
<option value="option2" selected="selected">Value 2</option>
</select>
In the above example the option2 option will be selected.
(edit) Using your own code:
<select name="<?php echo sprintf('expense[%s][%s]', $id, $category); ?>">
<option value="">Please select…</option>
<?php
foreach($category = mysqli_fetch_assoc($category_result)) :
if ($row["category"] == $category['category_name']) {
echo '<option value="'. $category['category_name'] .'" selected="selected">'. $category['category_name'] . "</option>";
} else {
echo '<option value="'. $category['category_name'] .'">'. $category['category_name'] . "</option>";
}
endforeach;
?>
</select>
Is there a PHP code that let's you compare 2 MySQL tables with each other and lets you add missing entries into one?
I have two tables. hs_hr_employee and rights. I want to add data from certain columns from the hs_hr_employee table so that they would be the same in the rights tables.
hs_hr_employee has multiple rows, whereas the rights table has 5 rows. The rights table gets the info from 4 columns from the hs_hr_employee table, emp_number, employee_id, emp_firstname, emp_lastname
Below is the code:
<?php
$connection = mysql_connect('localhost','admin','root');
if( isset($_POST['submit']) )
{
if( isset( $_POST['cb_change'] ) && is_array( $_POST['cb_change'] ))
{
foreach( $_POST['cb_change'] as $emp_number => $permission)
{
$sql = "UPDATE `rights` SET Permission='".mysql_real_escape_string($permission)."' WHERE emp_number='".mysql_real_escape_string($emp_number)."'";
echo __LINE__.": sql: {$sql}\n";
mysql_query( $sql );
}
}
}
?>
<p style="text-align: center;">
<span style="font-size:36px;"><strong><span style="font-family: trebuchet ms,helvetica,sans-serif;"><span style="color: rgb(0, 128, 128);">File Database - Administration Panel</span></span></strong></span></p>
<p style="text-align: center;">
</p>
<head>
<style type="text/css">
table, td, th
{
border:1px solid #666;
font-style:Calibri;
}
th
{
background-color:#666;
color:white;
font-style:Calibri;
}
</style>
</head>
<form method="post" action="admin.php">
<?php
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('users', $connection);
//mysql_query('INSERT into rights(Emp_num, ID, Name, Surname) SELECT emp_number, employee_id, emp_firstname, emp_lastname FROM hs_hr_employee');
$result = mysql_query("SELECT emp_number, employee_id, emp_firstname, emp_lastname, Permissions FROM rights");
mysql_query("INSERT INTO rights (emp_number, employee_id, emp_firstname, emp_lastname)
SELECT emp_number, employee_id, emp_firstname, emp_lastname
FROM hs_hr_employee
ON DUPLICATE KEY UPDATE employee_id = VALUES(employee_id), emp_number = VALUES(emp_number)
");
echo "<center>";
echo "<table >
<tr>
<th>Employee Number</th>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
<th>Permissions</th>
<th>Change</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['emp_number'] . "</td>";
echo "<td>" . $row['employee_id'] . "</td>";
echo "<td>" . $row['emp_firstname'] . "</td>";
echo "<td>" . $row['emp_lastname'] . "</td>";
echo "<td>" . $row['Permissions'] . "</td>";
echo "<td> <select name='cb_change[]'><option value='all'>All</option> <option value='remote'>Remote Gaming</option> <option value='landbased'>Landbased Gaming</option> <option value='general'>General Gaming</option> </select> </td>";
echo "</tr>" ;
}
#echo "<td>" . $row['Change'] . "</td>";
echo "</table>";
echo "</center>";
#$_POST['cb_permissions'];
mysql_close($connection);
?>
<p style="text-align: center;">
</p>
<p style="text-align: center;">
</p>
<p style="text-align: right;">
<input name="Save_Btn" type="button" value="Save" />
</p>
</form>
Any idea how to do it?
Thanks,
Brian
I'd go with an INSERT INTO SELECT here.
Assume you recognize an employee by the Social Security Number (ssn), and you use this value to update, for instance, name and birthyear:
mysql_query("
INSERT INTO hs_hr_employee (ssn, name, birthyear)
SELECT ssn, name, birthyear
FROM hs_hr_rights
ON DUPLICATE KEY UPDATE name = VALUES(name), birthyear = VALUES(birthyear)
");
You can also add a WHERE in between FROM and ON DUPLICATE. Like so:
...
FROM hs_hr_rights
WHERE birthyear IS NULL
ON DUPLICATE KEY UPDATE name = VALUES(name), birthyear = VALUES(birthyear)
...
Although, I don't see the need of copying values since in most cases you can fetch them through JOINs.
select * from table a where a.common not in (select b.common from table b where a.common = b.common)
And run this as well
select * from table b where b.common not in (select a.common from table a where a.common = b.common)
Not possible in php but in mysql its ans is as above