I want when I click on a button to send an Ajax 'update' request to my database.
I am well connected to my database which creates me a table with the data of my BDD (only 'SELECT').
mines.php :
<?php
include("mines.html");
echo "<html style='background-color: white;'>";
echo "<head>";
echo "<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>";
echo "<script src='https://code.jquery.com/jquery-3.5.1.slim.min.js' integrity='sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj' crossorigin='anonymous'></script>";
echo "<script src='https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js' integrity='sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo' crossorigin='anonymous'></script>";
echo "<script src='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js' integrity='sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI' crossorigin='anonymous'></script>";
echo "<script src='https://code.jquery.com/jquery-3.6.0.min.js'></script>";
echo "</head>";
echo "<table width= '700' border='1' align='center' id='tab_general' style='background-color: #F7741A;'
<caption align:'center';></caption>";
echo "<tr align='center'>";
echo "<TD style='padding:10px; font-size:15px;'>REMORQUE</TD>";
echo "<TD style='padding:10px; font-size:15px;'>PASSAGE AUX MINES</TD>";
echo "<TD style='padding:10px; font-size:15px;'>HDUC. 69</TD>";
echo "<TD style='padding:10px; font-size:15px;'>PASSAGE EFFECTUE LE</TD></TR>";
$date_jour = date("Y-m-d", strtotime("-12 month"));
$date_limite = date("Y-m-d", strtotime("+1 month"));
$date_jour2 = date("d-m-Y");
$date_jour3 = date("Y-m-d");
$requete_test="SELECT suivi_remorques.suivi_r.remorque, suivi_remorques.suivi_r.mines FROM suivi_remorques.suivi_r WHERE mines BETWEEN '$date_jour' AND '$date_limite' ORDER BY mines ASC";
$res_test = pg_Exec($database,$requete_test) or die("Erreur Requete $requete_test : ". pg_last_error());
$requete_lyon ="SELECT remorque as rem1, date as date1, situation FROM suivi_remorques.suivi_rem
INNER JOIN
(
SELECT max(date) AS papa, remorque as rem2 FROM suivi_remorques.suivi_rem
GROUP BY rem2
) AS req ON date = papa and remorque = rem2
WHERE situation = 'Dispo CMA'";
$res_lyon = pg_Exec($database,$requete_lyon) or die("Erreur Requete $requete_lyon : ". pg_last_error());
$requete_lyon_mine ="SELECT remorque as rem1, date as date1, situation FROM suivi_remorques.suivi_rem
INNER JOIN
(
SELECT max(date) AS papa, remorque as rem2 FROM suivi_remorques.suivi_rem
GROUP BY rem2
) AS req ON date = papa and remorque = rem2
WHERE situation = 'Mines CMA'";
$res_lyon_mine = pg_Exec($database,$requete_lyon_mine) or die("Erreur Requete $requete_lyon_mine : ". pg_last_error());
$id = 1;
for($k=0;$k<pg_NumRows($res_test);$k++) {
if($k % 2 == 0) {
echo "<tr align='center' style='background-color: #EDEDED;' id='row_".$row['id']."'>";
}
else {
echo "<tr align='center' id='row_".$row['id']."'>";
}
$rem = pg_Result($res_test,$k,"remorque");
$mines = pg_Result($res_test,$k,"mines");
$mines_jour = substr($mines, 8, 2);
$mines_mois = substr($mines, 5, 2);
$mines_annee= substr($mines, 0, 4);
echo "<td nowrap style='padding:10px;'>";
echo $rem;
echo "</td><td nowrap>";
echo "$mines_jour/$mines_mois/$mines_annee";
echo "</td>";
echo "<td nowrap style='padding:10px;'>";
$lyon_match = '';
for ($j = 0; $j < pg_NumRows($res_lyon); $j++) {
if($rem == pg_Result($res_lyon, $j, "rem1")) {
//$lyon_match = pg_Result($res_lyon, $j, "remorque");
echo "Dispo CMA";
}
}
for ($m = 0; $m < pg_NumRows($res_lyon_mine); $m++) {
if($rem == pg_Result($res_lyon_mine, $m, "rem1")) {
//$lyon_match = pg_Result($res_lyon, $j, "remorque");
echo "Mines CMA";
}
}
echo $lyon_match;
echo "</td>";
echo "<td class='px-4 py-2'>";
echo "<button type='button' class='btn btn-primary' data-toggle='modal' data-target='#editModal'>";
echo "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-pencil-square' viewBox='0 0 16 16'>";
echo "<path d='M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z'/>";
echo "<path fill-rule='evenodd' d='M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z'/>";
echo "</svg>";
echo "</button>";
echo "</td>";
echo "</tr>";
$id++;
echo "<!-- Modal -->";
echo "<div class='modal fade' id='editModal' tabindex='-1' role='dialog' aria-labelledby='editModalLabel' aria-hidden='true'>";
echo " <div class='modal-dialog' role='document'>";
echo " <div class='modal-content'>";
echo " <div class='modal-header'>";
echo " <h5 class='modal-title' id='editModalLabel'>Modification</h5>";
echo " <button type='button' class='close' data-dismiss='modal' aria-label='Close'>";
echo " <span aria-hidden='true'>×</span>";
echo " </button>";
echo " </div>";
echo " <div class='modal-body text-center'>";
echo " <p>La remorque est passee le :</p>";
echo " $date_jour2";
echo " <br><br>";
echo " <button type='button' name='update' class='btn btn-primary' id='validate'>Valider</button>";
echo " </div>";
echo " <div class='modal-footer'>";
echo " <button type='button' class='btn btn-secondary' data-dismiss='modal'>Fermer</button>";
echo " </div>";
echo " </div>";
echo " </div>";
echo "</div>";
}
echo "</table>";
echo "</html>";
$update = $_POST['query'];
$result = pg_query($conn, $update);
if (pg_affected_rows($result) > 0) {
echo "Update OK";
} else {
echo "Erreur lors de l'exécution de la requête : " . pg_last_error($conn);
}
pg_close($conn);
?>
I generate the 'trailer' column in this way which works well:
I assign an id for each line generated
for($k=0;$k<pg_NumRows($res_test);$k++) {
if($k % 2 == 0) {
echo "<tr align='center' style='background-color: #EDEDED;' id='row_".$row['id']."'>";
}
else {
echo "<tr align='center' id='row_".$row['id']."'>";
}
$rem = pg_Result($res_test,$k,"remorque");
$mines = pg_Result($res_test,$k,"mines");
$mines_jour = substr($mines, 8, 2);
$mines_mois = substr($mines, 5, 2);
$mines_annee= substr($mines, 0, 4);
echo "<td nowrap style='padding:10px;'>";
echo $rem;
echo "</td><td nowrap>";
File mines.html :
<script src='https://code.jquery.com/jquery-3.6.0.min.js'></script>
<script>
$(document).ready(function() {
$('#validate').click(function() {
var row_id = $(this).closest('tr').attr('id');
var rem = $('#' + row_id + ' td:first').text();
var update = "UPDATE suivi_remorques.suivi_rem SET situation = 'Mine CMA' WHERE remorque = '" + rem + "'";
$.ajax({
type: 'POST',
url: 'mines.php',
data: {query: update},
success: function(data) {
alert( "Update OK");
}
});
});
});
</script>
I have the 'Update OK' alert displayed but no database update.
I tried with a select instead of an 'update' for the query and display it in the alert, it doesn't work either.
The queries are correct
Related
As you can view in the image here, I am using a form which has check-boxes and a select option. Upon import of my CSV files using PHP, it displays the data correctly with the column headers. It also displays the CHECKED-boxes with its selected option only.
my csv file:
year, Exports of goods(F.O.B), Domestic exports, Re-exports.
1, 5, 10,20
1, 5, 10, 20
1, 5, 10, 20
1, 5, 10, 20
Thank you.
<!DOCTYPE html>
<html>
<head>
<title>Start1</title>
</head>
<body>
<table border="0" cellspacing="1" cellpadding="1" class="sortable" >
<?php #read CSV file
if (($handle = fopen("sample1.csv", "r")) !== false) {
$mycsv = array();
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$mycsv[] = $data;
}
fclose($handle);
#Find the length of the transposed row
$row_length = count($mycsv);
echo "<form method='post' action=''><table><tr>";
echo "<th><input type='checkbox' onClick='toggle(this)' /> Select/Deselect All<br/>
</th>";
echo "<th>Column</th>";
echo "<th>Filter</th>";
echo "</tr>";
#Loop through each row (or each line in the csv) and output all the columns for that row
foreach ($mycsv[0] as $col_num => $col) {
echo "<tr>";
for ($x = 0; $x < 1; $x++) {
echo "<td><input type='checkbox' name='lang[]' value='" . $mycsv[$x][$col_num] . "' ></td>";
echo "<td align='center'>" . $mycsv[$x][$col_num] . "</td>";
echo "<td>
<select name='method[]' >
<option value=''>Choose</option>
<option value='sum'>Sum</option>
<option value='mean'>Mean</option>
<option value='average'>Average</option>
<option value='highest'>Highest Value</option>
<option value='lowest'>Lowest Value</option>
</select>
</td>";
echo "</tr>";
}
}
echo "<tr>";
echo "<td><input type='checkbox' name='lang[]' ></td>";
echo "<td align='center'><input type='text' name='own_column' placeholder='Type your new column here'><br></td>";
echo "<td><input type='text' name='own_column' placeholder='Own formula'><br></td>";
echo "</tr>";
//echo "<tr>";
//echo "<td colspan='3' align='center'><input type='submit' name='Order'/></td>";
//echo "</tr>";
echo "<tr>";
echo "<td colspan='3'><div class='wrapper'><br/><br/><input type='button' class='button' value='Input Button'>
</div></td>";
echo "</tr>
<tr><td><input type='submit' value='submit' name='submit'</td></tr><table></form>";
$post_data = $_POST["lang"];
//$SelectedOption = $_POST['demo'];
for ($i = 0; $i < count($post_data); $i++) {
//echo "Selected : " . $post_data[$i]."</br>" ;
}
$row_length = count($mycsv);
$col_length = count($post_data);
$flag = true;
$sum = array();
foreach ($mycsv[0] as $key => $value) {
foreach ($post_data as $search_term) {
if (strcasecmp(trim($value), trim($search_term)) == 0) {
for ($row = 0; $row < $row_length; $row++) {
array_push($sum, $mycsv[$row][$key]);
if ($row == 0) {
echo "<tr>";
echo "<th colspan=100%>" . $mycsv[0][$key] . "</th>";
echo "</tr>";
} elseif ($row == 1) {
//echo "<td>" . $mycsv[$row][$key] . "</td>";
//echo "array sum =".array_sum($sum)."";
}
//echo " array sum =".array_sum($sum)."] ";
}
$method = $_POST["method"];
$method = $method[$key];
echo "<tr><td>";
if ($method == 'sum') {
echo "Sum of " . $value;
} elseif ($method == 'mean') {
echo "mean of " . $value;
} elseif ($method == 'average') {
echo "average of " . $value;
} elseif ($method == 'highest') {
echo "highest value of " . $value;
} elseif ($method == 'lowest') {
echo "lowest value of " . $value;
} else {
echo " Choose a method ";
echo "</td></tr>";
}
}
}
}
} ?>
</table>
</body>
</html>
First post so be gentle :) I've spent many hours getting my basic crud functions working. I can create, read, update and delete. YAY!
But when I have a second form on another tab - it doesn't work :(
I have tried to base as much of this on template functions as I can, so the two tabs are running the exact same code.
In fact, if I delete the content of the first tab - the form on the second tab starts working perfectly. So i'm thinking its something that should be unique to each form that isn't.
So to the code... Each tab has its own php. Clients.php and Contacts.php
<?PHP //clients.php
showTable(client,'Clients',true);
echo "<center><div class=\"btn-group\">\n";
echo "<button type=\"button\" class=\"btn btn-success\" data-toggle=\"modal\" data-target=\"#client_add\">Add</button>\n";
echo "<button type=\"button\" class=\"btn btn-primary UpdateButton\" data-toggle=\"modal\" data-source=\"client\" data-table=\"table_client\" data-ID=\"1\" data-OrgID=\"".$orgid."\" data-target=\"#client_modify\">Modify</button>";
echo "<button type=\"button\" value=\"Delete\" class=\"btn btn-danger delButton\" data-toggle=\"modal\" data-table=\"table_client\" data-ID=\"1\" data-OrgID=\"".$orgid."\" data-target=\"#client_del\">Delete</button>";
echo "</div></center>";
echo "</form>";
displayModals('client');
?>
<?PHP // contacts.php
showTable(contact,'Contacts',true);
echo "<center><div class=\"btn-group\">\n";
echo "<button type=\"button\" class=\"btn btn-success\" data-toggle=\"modal\" data-target=\"#contact_add\">Add</button>\n";
echo "<button type=\"button\" class=\"btn btn-primary UpdateButton\" data-source=\"contact\" data-toggle=\"modal\" data-table=\"table_contact\" data-ID=\"1\" data-OrgID=\"".$orgid."\" data-target=\"#contact_modify\">Modify</button>";
echo "<button type=\"button\" value=\"Delete\" class=\"btn btn-danger delButton\" data-toggle=\"modal\" data-table=\"table_contact\" data-ID=\"1\" data-OrgID=\"".$orgid."\" data-target=\"#contact_del\">Delete</button>";
echo "</div></center>";
echo "</form>";
displayModals('contact');
}?>
The below includes the displayModals function, my Jquery for the button clicks, and the showForm and showTable functions:
function displayModals($table){
echo "<div id=\"".$table."_add\" class=\"modal fade\" role=\"dialog\">\n";
echo " <div class=\"modal-dialog\">\n";
echo " <div class=\"modal-content\">\n";
echo " <div class=\"modal-header\">\n";
echo " <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n";
echo " <h4 class=\"modal-title\">Add ".ucfirst($table)."</h4>\n";
echo " </div>\n";
echo " <div class=\"modal-body\">\n";
showForm ($table,ucfirst($table)."s");
echo " </div>\n";
echo " <div class=\"modal-footer\">\n";
echo " Save\n";
echo " Close\n";
echo " </div>\n";
echo " </div>\n";
echo " </div>\n";
echo "</div>";
echo "<div id=\"".$table."_modify\" class=\"modal fade\" role=\"dialog\">\n";
echo " <div class=\"modal-dialog\">\n";
echo " <div class=\"modal-content modify-content\">\n";
echo " <div class=\"modal-header\">\n";
echo " <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n";
echo " <h4 class=\"modal-title\">Modify ".ucfirst($table)."</h4>\n";
echo " </div>\n";
echo " <div class=\"modal-body\">\n";
echo " </div>\n";
echo " <div class=\"modal-footer\">\n";
echo " Save\n";
echo " Close\n";
echo " </div>\n";
echo " </div>\n";
echo " </div>\n";
echo "</div>";
echo "<div id=\"".$table."_del\" class=\"modal fade\" role=\"dialog\">\n";
echo " <div class=\"modal-dialog\">\n";
echo " <div class=\"modal-content modify-content\">\n";
echo " <div class=\"modal-header\">\n";
echo " <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n";
echo " <h4 class=\"modal-title\">Delete ".ucfirst($table)."</h4>\n";
echo " </div>\n";
echo " <div class=\"modal-body\">\n";
echo " </div>\n";
echo " <div class=\"modal-footer\">\n";
echo " Yes\n";
echo " No\n";
echo " </div>\n";
echo " </div>\n";
echo " </div>\n";
echo "</div>";
?>
<script>
$('.UpdateButton').click(function(){
selected = [];
var tab=$(this).attr('data-table');
$.each($("#"+tab+" input[name='checkbox[]']:checked"), function(){
selected.push($(this).val());
});
if (selected.length===1) {
var Id=$(this).attr('data-ID');
var OrgId=$(this).attr('data-OrgID');
var chkBox=selected[0];
var table=$(this).attr('data-source');
$.ajax({url:"../functions/form-edit-ajax.php?table="+table+"&chkBox="+chkBox+"&OrgID="+OrgId+"&Id="+Id,cache:false,success:function(result){
$(".modify-content .modal-body").html(result);
}});
} else { $(".modify-content .modal-body").html("Please select one record to modify."); };
delete selected;
});
$('.delButton').click(function(){
var table=$(this).attr('data-table');
var data = $("#"+table).serialize();
$.ajax({
url: "../functions/form-edit-ajax.php", // link of your "whatever" php
type: "POST",
async: true,
cache: false,
data: data, // all data will be passed here
success: function(data){
$(".modify-content .modal-body").html(data); // The data that is echoed from the ajax.php
}
});
});
</script><?PHP
}
?>
function showTable($table=NULL,$tabname=NULL,$sel=NULL,$rows=NULL) {
$connection = dbConnect();
$excludes = array("id", "org_id", "client_id", "status");
//if ($rows) {die(print_r($rows));};
//echo "<div class=\"container\">\n";
echo ("</br></br>");
echo "<form action=\"/functions/form-edit.php";
if ($rows) echo "?act=delete";
echo "\" method=\"post\" id=\"table_";
if ($rows) echo "del_";
echo $table."\" class=\"form-horizontal\">\n";
/* show tables */
$result = mysqli_query($connection, 'SHOW TABLES') or die('cannot show tables');
if (!$table) {
while($tableName = mysqli_fetch_row($result)) {
$table = $tableName[0];
echo " <h3>",$table,"</h3>\n";
$result2 = mysqli_query($connection, 'SHOW COLUMNS FROM '.$table) or die('cannot show columns from '.$table);
if(mysqli_num_rows($result2)) {
echo " <table class=\"table table-striped\">\n";
echo " <thead>\n";
echo " <tr>\n";
while($row2 = mysqli_fetch_row($result2)) {
echo '<th>',$row2[0],'</th>';
}
echo "</tr>\n";
echo " </thead>\n";
}
if (!$rows) {
$result2 = mysqli_query($connection, 'SELECT * FROM '.$table) or die('cannot show data from '.$table);
} else {
$result2 = mysqli_query($connection, 'SELECT * FROM '.$table.' WHERE id IN ('.implode(",",$rows).')') or die('cannot show data from '.$table);
}
if(mysqli_num_rows($result2)) {
echo " <tbody>\n";
echo " <tr>\n";
$row2 = mysqli_fetch_row($result2);
foreach ($row2 as $row) {
echo '<td>',$row,'</td>';
}
echo " </tr>\n";
echo " </tbody>\n";
}
echo " </table>\n";
} // END OF WHILE LOOP
}
else {
if ($tabname) { echo " <h3>",$tabname,"</h3>\n"; } else { echo " <h3>",$table,"</h3>\n"; };
$org=$_SESSION[userData][org_id];
$result2 = mysqli_query($connection, 'SHOW COLUMNS FROM '.$table) or die('cannot show columns from '.$table);
if(mysqli_num_rows($result2) > 0) {
echo " <table class=\"table table-striped\">\n";
echo " <thead>\n";
echo " <tr>\n";
if (!$rows) {
while($row2 = mysqli_fetch_row($result2)) {
if (!in_array($row2[0], $excludes)) {
echo '<th>',ucwords(preg_replace( '/_+/', ' ', $row2[0])),'</th>';
}
}
} else { echo '<th>Title</th>';};
if ($sel=='1') { echo ('<th>Select</th>'); };
echo " </tr>\n";
echo " </thead>\n";
}
mysqli_free_result($result2);
if (!$rows) {
$result2 = mysqli_query($connection, 'SELECT * FROM '.$table.' WHERE org_id='.$_SESSION[userData][org_id]) or die('cannot show data from '.$table);
} else {
$result2 = mysqli_query($connection, 'SELECT title,id FROM '.$table.' WHERE org_id='.$_SESSION[userData][org_id].' AND id IN ('.implode(",",$rows).');') or die('cannot show data from '.$table);
}
if(mysqli_num_rows($result2) > 0) {
echo " <tbody>\n";
foreach ($result2 as $row) {
foreach ($excludes as $exc) {
if ($exc=='id') {$row_id=$row[$exc];};
unset($row[$exc]);
}
echo " <tr>\n";
mysqli_fetch_field($result2);
foreach ($row as $element) {
echo ("<td>".$element."</td>");
}
if ($sel) {echo ('<td><input type="checkbox" name="checkbox[]" value="'.$row_id.'"></td>');};
if ($rows) {echo ('<input type="hidden" name="checkbox[]" value="'.$row_id.'">');};
echo " </tr>\n";
unset ($row_id);
}
echo " </tbody>\n";
}
mysqli_free_result($result2);
echo ("<input type=\"hidden\" name=\"table\" value=\"$table\">");
echo " </table>\n";
}
// echo "</form>";
// echo "</div>";
}
function showForm($table=NULL,$tabname=NULL,$orgid=NULL,$rec=NULL) {
$connection = dbConnect();
$excludes = array("id", "org_id", "client_id", "status");
if ($table) {
echo "<form action=\"/functions/form-edit.php";
if ($rec) {echo "?act=update"; };
echo "\" method=\"post\" id=\"f".$table;
if ($rec) {echo "_modify"; };
echo "\" class=\"form-horizontal\">\n";
$result2 = mysqli_query($connection, 'SHOW COLUMNS FROM '.$table) or die('cannot show columns from '.$table);
if ($rec) {
$record = mysqli_query($connection, 'SELECT * from '.$table.' WHERE org_id='.$orgid.' AND id='.$rec.' LIMIT 1');
$row = mysqli_fetch_array($record, MYSQLI_BOTH);
}
$results3=array();
if(mysqli_num_rows($result2)) {
while($row2 = mysqli_fetch_row($result2)) {
foreach ($excludes as $exc) {
if ($row2[0]==$exc) {array_push($results3, $row2[0]); unset ($row2[0]);};
}
if ($row2[0]) {
echo " <div class=\"form-group\">\n";
echo " <label class=\"control-label col-sm-3\" for=\"".$row2[0]."\">".ucwords(preg_replace( '/_+/', ' ', $row2[0])).":</label>\n";
echo " <div class=\"col-sm-9\">\n";
if ($rec) {
if (is_array($row) && array_key_exists($row2[0],$row)) {
echo " <input type=\"text\" class=\"form-control\" name=\"".$row2[0]."\" value=\"".$row[$row2[0]]."\" placeholder=\"Enter ".ucwords(preg_replace( '/_+/', ' ', $row2[0]))."\">\n";
}
} else {
echo " <input type=\"text\" class=\"form-control\" name=\"".$row2[0]."\" placeholder=\"Enter ".ucwords(preg_replace( '/_+/', ' ', $row2[0]))."\">\n";
}
echo " </div>\n";
echo " </div>\n";
}
}
foreach ($results3 as $element) {
echo ("<input type=\"hidden\" name=\"".$element."\" value=\"".$row[$element]."\">");
}
echo ("<input type=\"hidden\" name=\"table\" value=\"$table\">");
}
echo "</form>";
} // END OF WHILE LOOP
else {
echo " <h3>No form selected</h3></br><h4>table=".$table."</br>\n";
}
unset($result2);
unset($result3);
unset ($row,$element,$table,$row2,$record);
}
So on the first tab with the Clients, I can add/modify/delete without any trouble. On the second tab, I can add and delete, but modify just seems to submit the unedited fields back to the database.
Oddly if I wipe out the contents of clients.php for testing, the second tab works perfectly? I can't help thinking its some sort of duplication somewhere that needs to be made unique.
Any pointers or guidance would be greatly appreciated.
Thanks everybody :)
Hi i am trying to submit the multiple form values only from one button i have 10 records and one record has one button of submit and 10 records have 10 buttons of submit what i want there should be only one button of submit and i can submit he whole 10 records from one button:
echo "<table class='table table-hover table-responsive table-bordered'>";
// our table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price</th>";
echo "<th style='width:5em;'>Quantity</th>";
echo "<th>Image</th>";
echo "<th>Action</th>";
echo "</tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>";
echo "<div class='product-id' style='display:none;'>{$id}</div>";
echo "<div class='product-name'>{$name}</div>";
echo "</td>";
echo "<td>$" . number_format($price, 2, '.' , ',') . "</td>";
if(isset($quantity)){
echo "<td>";
echo "<input type='text' name='quantity' value='{$quantity}' disabled class='form-control' />";
echo "</td>";
echo "<td>";
echo "<td>";
echo "<button class='btn btn-success' disabled>";
echo "<span></span> Submitted!";
echo "</button>";
echo "</td>";
echo "</td>";
}else{
echo "<td>";
echo "<input type='number' name='quantity[]' value='1' class='form-control'/>";
echo "</td>";
echo "<td><img src='product-images/{$image}' width='60' height='60'</td>";
echo "<td>";
echo "<button class='btn btn-primary add-to-cart'>";
echo "<span></span>Submit to cart";
echo "</button>";
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
}
what i want only one button from i can submit all my values: Any help would be high appreciated:
$action = isset($_GET['action']) ? $_GET['action'] : "";
$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "1";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "1";
$image = isset($_GET['image']) ? $_GET['image'] : "1";
if($action=='added'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> added to your cart!";
echo "</div>";
}
else if($action=='failed'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> failed to add to your cart!";
echo "</div>";
}
// left join to select products
$query = "SELECT p.id, p.name, p.price, p.image, ci.quantity
FROM products p
LEFT JOIN cart_items ci
ON p.id = ci.product_id
ORDER BY p.name";
$stmt = $con->prepare( $query );
$stmt->execute();
// count number of products returned
$num = $stmt->rowCount();
HTML CODE
<?php
// connect to database
include 'config/db_connect.php';
// page headers
$page_title="Cart";
include 'layout_head.php';
// parameters
$action = isset($_GET['action']) ? $_GET['action'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$image = isset($_GET['image']) ? $_GET['image'] : "";
// display a message
if($action=='removed'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> was removed from your cart!";
echo "</div>";
}
else if($action=='quantity_updated'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> quantity was updated!";
echo "</div>";
}
else if($action=='failed'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> quantity failed to updated!";
echo "</div>";
}
else if($action=='invalid_value'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> quantity is invalid!";
echo "</div>";
}
// select products in the cart
$query="SELECT p.id, p.name, p.price, p.image, ci.quantity, ci.quantity * p.price AS subtotal
FROM cart_items ci
LEFT JOIN products p
ON ci.product_id = p.id";
$stmt=$con->prepare( $query );
$stmt->execute();
// count number of rows returned
$num=$stmt->rowCount();
if($num>0){
//start table
echo "<table class='table table-hover table-responsive table-bordered'>";
// our table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price</th>";
echo "<th style='width:15em;'>Quantity</th>";
echo "<th>Sub Total</th>";
echo "<th>Action</th>";
echo "</tr>";
$total=0;
while( $row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<tr>";
echo "<td>";
echo "<div class='product-id' style='display:none;'>{$id}</div>";
echo "<div class='product-name'>{$name}</div>";
echo "</td>";
echo "<td>$" . number_format($price, 2, '.', ',') . "</td>";
echo "<td>";
echo "<div class='input-group'>";
echo "<input type='number' name='quantity[]' value='{$quantity}' class='form-control'>";
echo "<span class='input-group-btn'>";
echo "<button class='btn btn-default update-quantity' type='button'>Update</button>";
echo "</span>";
echo "</div>";
echo "</td>";
echo "<td>$" . number_format($subtotal, 2, '.', ',') . "</td>";
echo "<td>";
echo "<a href='remove_from_cart.php?id={$id}&name={$name}' class='btn btn-danger'>";
echo "<span></span> Delete from cart";
echo "</a>";
echo "</td>";
echo "</tr>";
$total += $subtotal;
}
echo "<tr>";
echo "<td><b>Total</b></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td>$" . number_format($total, 2, '.', ',') . "</td>";
echo "<td>";
echo "</a>";
echo "</td>";
echo "</tr>";
echo "</table>";
}else{
echo "<div class='alert alert-danger'>";
echo "<strong>No products found</strong> in your cart!";
echo "</div>";
}
include 'layout_foot.php';
?>
Use name quantity[] instead of quantity.By this way you can receive post data as an array. After the loop use only one submit button.
echo "<input type='number' name='quantity[]' value='1' class='form-control'/>";
Then receive it by using foreach
foreach($_POST['quantity'] as $qty)
{
echo $qty;
//Here you will receive all the quantities one by one.
}
Form the code
<?php
echo "<table class='table table-hover table-responsive table-bordered'>";
// our table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price</th>";
echo "<th style='width:5em;'>Quantity</th>";
echo "<th>Image</th>";
echo "</tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>";
echo "<div class='product-id' style='display:none;'>{$id}</div>";
echo "<div class='product-name'>{$name}</div>";
echo "</td>";
echo "<td>$" . number_format($price, 2, '.' , ',') . "</td>";
if(isset($quantity)){
echo "<td>";
echo "<input type='text' name='quantity[]' value='{$quantity}' disabled class='form-control' />";
echo "</td>";
echo "<td>";
echo "</td>";
echo "<td>";
echo "</td>";
}else{
echo "<td>";
echo "<input type='number' name='quantity[]' value='1' class='form-control'/>";
echo "</td>";
echo "<td><img src='product-images/{$image}' width='60' height='60'</td>";
echo "<td>";
echo "</td>";
}
echo "</tr>";
}
echo "<tr><td colspan='4'>";
echo "<button class='btn btn-primary add-to-cart' type='submit'>";
echo "<span></span>Submit to cart";
echo "</button>";
echo "</td></tr>";
echo "</table>";
I'm getting all rows from mysql database. Now I want to highlight only first row in php while loop with class name keywordHighlight.
How do I highlight only first row in php while loop result ?
if($numSearch > 0){
echo "<font color='green'>We found $numSearch result(s).</font>";
echo "<table width='100%' cellpadding='0' cellspacing='0'>";
echo "<thead>";
echo "<tr>";
echo "<td class='' valign='top' width='200'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($resGetSearch = mysql_fetch_array($getSearch)){
$SearchCdid = $resGetSearch['cdid'];
$SearchFamilyName = $resGetSearch['family_name'];
$SearchGivenName = $resGetSearch['given_name'];
$SearchCompamyCid = $resGetSearch['cid'];
$SearchDepartment = $resGetSearch['department'];
$SearchTitle = $resGetSearch['title'];
$SearchComapnyName = mysql_query("SELECT company_name FROM company WHERE cid = '$SearchCompamyCid' ");
$resSearchCompanyName = mysql_fetch_array($SearchComapnyName);
$companyName = $resSearchCompanyName['company_name'];
if (strlen($companyName) >= 20) {
$companyName = substr($companyName, 0, 10). "" . substr($companyName, -5);
}else{
$companyName = $companyName;
}
// my Highlighted class = keywordHighlight";
echo "<tr onclick='getDetails($SearchCdid);' >";
echo "<td valign='top' >$companyName</td>";
echo "<td valign='top'>$SearchFamilyName</td>";
echo "<td valign='top'>$SearchGivenName</td>";
echo "<td valign='top'>$SearchDepartment</td>";
echo "<td valign='top'>$SearchTitle</td>";
echo "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
echo "<hr/>";
echo "<br/>";
}//elseif is not empty search
elseif($numSearch === 0){
echo "<font color='red'>No Matches.</font>";
}
Do it like this
$i = 1;
while($resGetSearch = mysql_fetch_array($getSearch)){
$highlight = $i == 1 ? 'keywordHighlight' : '';
echo "<tr class='{$highlight}' onclick='getDetails($SearchCdid);' >";
---------------
-------------
-------------
$i++;
}
Only with CSS
or you can highlight it only with css
#highlight tbody tr:nth-child(1){
background: #ff6600;
}
There is more and elegant way to highlight only first row with only css not need to code, consider the example http://jsbin.com/soravuzakahu/1/
You could just add a boolean outside the loop. Like so:
$first = true;
while($resGetSearch = mysql_fetch_array($getSearch)){
if(first == true){
// Add code here that only applies to the first iteration.
}
$first = false;
}
<?php
if($numSearch > 0){
echo "<font color='green'>We found $numSearch result(s).</font>";
echo "<table width='100%' cellpadding='0' cellspacing='0'>";
echo "<thead>";
echo "<tr>";
echo "<td class='' valign='top' width='200'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
$i = 0;
while($resGetSearch = mysql_fetch_array($getSearch)){
++$i;
$SearchCdid = $resGetSearch['cdid'];
$SearchFamilyName = $resGetSearch['family_name'];
$SearchGivenName = $resGetSearch['given_name'];
$SearchCompamyCid = $resGetSearch['cid'];
$SearchDepartment = $resGetSearch['department'];
$SearchTitle = $resGetSearch['title'];
$SearchComapnyName = mysql_query("SELECT company_name FROM company WHERE cid = '$SearchCompamyCid' ");
$resSearchCompanyName = mysql_fetch_array($SearchComapnyName);
$companyName = $resSearchCompanyName['company_name'];
if (strlen($companyName) >= 20) {
$companyName = substr($companyName, 0, 10). "" . substr($companyName, -5);
}else{
$companyName = $companyName;
}
// my Highlighted class = keywordHighlight";
if($i == 1)
echo "<tr onclick='getDetails($SearchCdid);' >";
else
echo "<tr class='keywordHighlight' onclick='getDetails($SearchCdid);' >";
echo "<td valign='top' >$companyName</td>";
echo "<td valign='top'>$SearchFamilyName</td>";
echo "<td valign='top'>$SearchGivenName</td>";
echo "<td valign='top'>$SearchDepartment</td>";
echo "<td valign='top'>$SearchTitle</td>";
echo "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
echo "<hr/>";
echo "<br/>";
}//elseif is not empty search
elseif($numSearch === 0){
echo "<font color='red'>No Matches.</font>";
}
Use a flag and set its value to true and while in loop check its value , if its true then print class name and set its value to false. Like $flag=true; then inside while loop check
if($flag==true) {
<td class='yourclassname';
$flag= false;
}
put some flag $f=0;
if f==0 then do something like this:
$highlight="<div class='keywordHighlight'>valur of first row</div>";// instead of dive you can use table also it depends on how you want to display.
$f=$f+1;
and rest in else part.
$first = true;
while ( $resGetSearch = mysql_fetch_array($getSearch) )
{
if ( $first == true )
{
// Add code here that only applies to the first iteration.
$first = false;
}
else
{
// Add code here that only applies to the 2, 3, and so on.
}
}
Here i don't have any coding related problem. I'm trying to fetch the details from multiple database tables. fetch results working fine. But alignment is my problem here.
You can see a image.. In that image voucher status column is working fine. But, another two column ( room status & meal status values ) is always on the last row. How to align those (room and meal status) values properly (like voucher status column)? i hope you can understand my problem...
<?php
echo "<table width=1090 border=1 style=\"border: #ddd;\" align=center cellspacing=4 cellpadding=10>";
echo "<tr class=thvoucher>";
echo "<th width=30>Voucher Number</th>";
echo "<th width=80>Reference Number</th>";
echo "<th width=200>Guest Name</th>";
echo "<th width=150>Voucher Status</th>";
echo "<th width=150>Room Status</th>";
echo "<th width=150>Meal Status</th>";
echo "</tr>";
for($i = $start; $i < $end; $i++)
{
if ($i == $total_results)
{
break;
}
while($row = $stmt->fetch())
{
$voucherid = $row['VoucherID'];
$ref = $row['VoucherReference'];
$gname = $row['GuestName'];
$vstatus = $row['ActiveStatus'];
echo "<tr class=voucherstyle" . $cls . ">";
echo "<td>$voucherid</td>"; **// FIRST TD**
echo "<td>$ref</td>"; **// SECOND TD**
echo "<td>$gname</td>"; **// THIRD TD**
if( $vstatus != 'empty' ) **// FOURTH TD**
{
if( $vstatus == 'Y' )
{
echo "<td class=green >Active</td>";
}
else if( $vstatus == 'N' )
{
echo "<td class=red >Inactive</td>";
}
}
else
{
echo "<td><form method=post onsubmit=\"return mstatusvalidate(this)\"; action='voucherstatus_update.php?id_meal= $voucherid '><select name=mealstatus><option value=empty></option><option value=active>Active</option><option value=inactive>Inactive</option></select><input type=submit class=update_status title=\"Update $gname voucher status\" value=Update></form></td>";
}
}
while($r_row = $r_stmt->fetch())
{
$rstatus = $r_row['ActiveStatus'];
// same like above if else statement **// FIFTH TD**
}
while($m_row = $m_stmt->fetch())
{
$mstatus = $m_row['ActiveStatus'];
// same like above if else statement **// SIXTH TD**
}
echo "</tr>";
}
echo "</table>";
?>
You have 6 th elements in your first row, but I only see 3 td elements and no tr closing tags on subsequent rows. This is likely your issue.
I would suspect that a cursory inspection of your source output would have made this pretty clear.
try this
<?php
echo "<table width=1090 border=1 style=\"border: #ddd;\" align=center cellspacing=4 cellpadding=10>";
echo "<tr class=thvoucher>";
echo "<th width=30>Voucher Number</th>";
echo "<th width=80>Reference Number</th>";
echo "<th width=200>Guest Name</th>";
echo "<th width=150>Voucher Status</th>";
echo "<th width=150>Room Status</th>";
echo "<th width=150>Meal Status</th>";
echo "</tr>";
for($i = $start; $i < $end; $i++)
{
if ($i == $total_results)
{
break;
}
while($row = $stmt->fetch())
{
$voucherid = $row['VoucherID'];
$ref = $row['VoucherReference'];
$gname = $row['GuestName'];
$vstatus = $row['ActiveStatus'];
echo "<tr class=voucherstyle" . $cls . ">";
echo "<td>$voucherid</td>"; **// FIRST TD**
echo "<td>$ref</td>"; **// SECOND TD**
echo "<td>$gname</td>"; **// THIRD TD**
if( $vstatus != 'empty' ) **// FOURTH TD**
{
if( $vstatus == 'Y' )
{
echo "<td class=green >Active</td>";
}
else if( $vstatus == 'N' )
{
echo "<td class=red >Inactive</td>";
}
}
else
{
echo "<td><form method=post onsubmit=\"return mstatusvalidate(this)\"; action='voucherstatus_update.php?id_meal= $voucherid '><select name=mealstatus><option value=empty></option><option value=active>Active</option><option value=inactive>Inactive</option></select><input type=submit class=update_status title=\"Update $gname voucher status\" value=Update></form></td>";
}
while($r_row = $r_stmt->fetch())
{
$rstatus = $r_row['ActiveStatus'];
// same like above if else statement **// FIFTH TD**
}
while($m_row = $m_stmt->fetch())
{
$mstatus = $m_row['ActiveStatus'];
// same like above if else statement **// SIXTH TD**
}
echo "</tr>";
}
}
echo "</table>";
?>
I got it working using this while condition while(($row = $stmt->fetch()) && ($r_row = $r_stmt->fetch()) && ($m_row = $m_stmt->fetch())). Before i've used three separate while loops. Now, i've some other ideas. i tried it, now its working fine and alignment also perfect. Before i didn't post my if else statement code. So, everyone thought i've used just 3 td's. Sorry for confused everyone... I've posted my correct coding below..
<?php
echo "<table width=1090 border=1 style=\"border: #ddd;\" align=center cellspacing=4 cellpadding=10>";
echo "<tr class=thvoucher>";
echo "<th width=30>Voucher Number</th>";
echo "<th width=80>Reference Number</th>";
echo "<th width=200>Guest Name</th>";
echo "<th width=150>Voucher Status</th>";
echo "<th width=150>Room Status</th>";
echo "<th width=150>Meal Status</th>";
echo "</tr>";
for($i = $start; $i < $end; $i++)
{
if ($i == $total_results)
{
break;
}
while(($row = $stmt->fetch()) && ($r_row = $r_stmt->fetch()) && ($m_row = $m_stmt->fetch()))
{
$voucherid = $row['VoucherID'];
$ref = $row['VoucherReference'];
$gname = $row['GuestName'];
$vstatus = $row['ActiveStatus'];
echo "<tr class=voucherstyle" . $cls . ">";
echo "<td>$voucherid</td>"; **1st TD**
echo "<td>$ref</td>"; **2nd TD**
echo "<td>$gname</td>"; **3rd TD**
if( $vstatus != 'empty' ) **4th TD**
{
if( $vstatus == 'Y' )
{
echo "<td class=green >Active</td>";
}
else if( $vstatus == 'N' )
{
echo "<td class=red >Inactive</td>";
}
}
else
{
echo "<td><form method=post onsubmit=\"return mstatusvalidate(this)\"; action='voucherstatus_update.php?id= $voucherid '><select name=mealstatus><option value=empty></option><option value=active>Active</option><option value=inactive>Inactive</option></select><input type=submit class=update_status title=\"Update $gname voucher status\" value=Update></form></td>";
}
$rstatus = $r_row['ActiveStatus'];
// if else statement **5th TD**
$mstatus = $m_row['ActiveStatus'];
// if else statement **6th TD**
echo "</tr>";
}
}
echo "</table>";
?>