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
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>
I have a mysql table structure like this (lets say tableA):
unitID, Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8.
I create a data table using the following code.
<html>
<head>
<style>
.tbstyle {
border: 1px solid #CCC;
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
border-collapse: collapse;
float: left;
}
.tbstyle td {
padding: 3px;
margin: 2px;
border: 1px solid #ccc;
text-align: center;
height: 13px;
}
</style>
</head>
<body>
<table class="tbstyle" id="">
<?php
include ("config.php");
$sql = "SELECT Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8 FROM tableA ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc())
{
echo "</td><td>". $row["Value1"] . "</td><td>" . $row["Value2"]. "</td><td>" . $row["Value3"]."</td><td>" . $row["Value4"]."</td><td>" . $row["Value5"].
"</td><td>" . $row["Value6"]."</td><td>" . $row["Value7"]."</td><td>" . $row["Value8"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
</table>
</body>
</html>
I have another mysql table (lets say tableB) which has saleID. I would like to generate above table side by side as many as the number of saleIDs on tableB.
and I need to make each generated <table id=""> to have a unique saleID. I mean table IDs should be named with saleID. I left the table id in the code blank. <table class="tbstyle" id="">
I'd really appreciate any help I can get. Thanks.
Here is my current code which is not complete and doesn't give the expected result:
<table class="tbstyle" id="">
<?php
$conn=mysqli_connect("localhost","root","","mydb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT saleID FROM tableB";
if ($result=mysqli_query($conn,$sql))
{
$rowcount=mysqli_num_rows($result);
}
$sql = "SELECT Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8 FROM tableA ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc())
for ($x = 0; $x <= $rowcount; $x++)
{
echo "</td><td>". $row["Value1"] . "</td><td>" . $row["Value2"]. "</td><td>" . $row["Value3"]."</td><td>" . $row["Value4"]."</td><td>" . $row["Value5"].
"</td><td>" . $row["Value6"]."</td><td>" . $row["Value7"]."</td><td>" . $row["Value8"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
</table>
Ok, so here is my suggestion.
SELECT saleID FROM tableB ORDER BY saleID.
loop on the results. For each saleID, do...
echo the start your table (<table>, <thead> ... </thead><tbody>)
SELECT * FROM tableA.
Loop on these results. For each row, echo one row of the table (<tr><td>...</td>...</tr>).
Close your table (</tbody></table>).
So you loop twice, once for tableB, again for tableA. Each saleID is a new table, in the inner loop.
One detail which is still unclear to me, is where is the link between tableA and tableB. How do you know the values in tableA apply to the saleID you just read? Anyway my answer is strictly or the HTML-PHP version, no database logic here.
Hello everyone I am trying to write a PHP code that reads the information from my database, unfortunately I got the following error message:
Notice: Undefined index: numcontrat in C:\wamp\www\test\crud-php-simple-master\crud-php-simple-master\index.php on line 46 and
Notice: Undefined index: dnotification in C:\wamp\www\test\crud-php-simple-master\crud-php-simple-master\index.php on line 51
I share with you my source code:
<?php`
//including the database connection file
include_once("config.php");
?>
<html>
<head>
<title>Homepage</title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td style="background-color:#57D251; "> <b> N Contrat</b></td>
<td style="background-color:#57D251; " ><b> Avenant</b></td>
<td style="background-color:#57D251; " ><b> Discription</b></td>
<td style="background-color:#57D251; " ><b> Fournisseur</b></td>
<td style="background-color:#57D251; " ><b> Delai</b></td>
<td style="background-color:#57D251; " ><b> Date de notification</b></td>
<td style="background-color:#57D251; " ><b> Date envigyeur</b></td>
<td style="background-color:#57D251; " ><b> Date de fin caution</b></td>
<td style="background-color:#57D251; " ><b> Avance forfaitaire</b></td>
</tr>
<?php
//fetching data in descending order (lastest entry first)
$sql= 'SELECT * FROM contrats ';
$result = mysql_query($sql);
if (! $result){
echo('Database error: ' . mysql_error());
}
echo $result;
while($res = mysql_fetch_assoc ($result)) {
echo "<tr>";
echo "<td>" .$res['numcontrat']."</td>" ;
echo "<td>" .$res['avenant']."</td>" ;
echo "<td>" .$res['discription']."</td>" ;
echo "<td>" .$res['fournisseur']."</td>" ;
echo "<td>" .$res['delai']."</td>" ;
echo "<td>" .$res['dnotification']."</td>" ;
echo "<td>" .$res['denvigyeur']."</td>" ;
echo "<td>" .$res['dcaution']."</td>" ;
echo"<td>" .$res['aforfaitaire']."</td>" ;
echo "<tr>";
//echo "<td>Edit | Delete</td>";
}
?>
</table>
</body>
</html>
thank you for your answer
According to your exception, dnotification column doesn't exist in your table contrats.
Create this column in your Database table and then try.
In your Comment you have mentioned
//fetching data in descending order (lastest entry first)
$sql= 'SELECT * FROM contrats ';
But it will fetch in the order it is stored.To fetch in descending order, Use query something like this...
SELECT * FROM contrats order by id DESC
where id is the autoincremented field.
<?php require_once('../includes/connection.php');?>
<?php require_once('../includes/header.php');?>
<?php
$color="1";
$respo = $_GET['respo'];
$data = explode("+", $respo);
$month = date("m", strtotime($data[1])) . "<br />";
$year = date("Y", strtotime($data[1])) . "<br />";
**$viewrecord = "SELECT *, (pr.roll1 + pr.roll2 + pr.roll3 + pr.roll4 + pr.roll5 + pr.roll6) AS rolls FROM tbl_payroll dv join tbl_payroll pr on pr.dv_id = dv.dv_id WHERE dv.respo='".mysql_real_escape_string($data[0])."' && year(dv.date_added)='$year' && month(dv.date_added)='$month'";**
$run_viewrecord = mysql_query($viewrecord) or die(mysql_error());
{
echo "<table border='1' width='100%' style='border:1px solid silver' cellpadding='5px' cellspacing='0px'>
<tr bgcolor='#666666' style='color:#FFFFFF'>
<th>Date Encoded</th>
------------HEADER--------- etc....
-------THERE SHOULD BE A IF STATEMATE HERE-----------------
(where if no records match "dv.dv_id=pr.pr.dv_id". It would still display records from tbl_dv..)
while ($row = mysql_fetch_row($run_viewrecord)) {
if($color==1){
echo "<tr bgcolor='#ffffff'>";
echo "<td align='center'>" .date_format(date_create($row[17]), "m/d/y")."</td>
**--------- I WANT TO DISPLAY THE ROLLS HERE --------------------**
echo "</td></tr>";
$color="2";
} else {
echo "<tr bgcolor='#ebeaea'>";
echo "<td align='center'>" .date_format(date_create($row[17]), "m/d/y")."</td>
**--------- I WANT TO DISPLAY THE ROLLS HERE --------------------**
echo "</td></tr>";
$color="1";
}
}
echo '</table>';
echo '<td><tr><table><br /><br />';
}
?>
I was hoping to add an IF statement before WHILE. Which will still display records even there is no match dv_id on both table2. It should still display records.. The COLUMN ROLLS IF No match it will display a 0.00 value. LINK>> http://i599.photobucket.com/albums/tt79/emcevo/viewphpdisplay_zpsfc6a8174.jpg
//Total NET
<?php
$qry2 = "SELECT *, SUM(net) as sum_net FROM tbl_dv";
$run2 = mysql_query($qry2) or die(mysql_error());
while ($row = mysql_fetch_array($run2)) {
?>
<tr>
<td colspan="5" style="text-align:right;" /><b>TOTAL NET</b></td>
<td colspan="6" style="text-align:left;font-size: 14px;" /><b><?php echo number_format($row['sum_net'],2); ?></b></td>
</tr><?php }?>
</td></tr></table>
How can I display the TOTAL NET below code:
$qry2 = "SELECT *, SUM(net) as sum_net FROM tbl_dv";.
I top codes are all working.. The bold Section BUTTOM code is the Problem.
I guess you get downvotes because your whole php code-block is unnecessary as far I can see. Your query "$qry2" is incorrect; you can't sum without a group by (unless you only do a sum). eg:
select dv_id, sum(net) as sum_net from tbl_dv group by dv_id
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.