Update & delete MySQL from modal bootstrap - php

I´m trying to delete and/or update data from form inside a modal window .For create it I haven´t problem but with the others actions (delete and update) I always have a problem,I think the key is the "id" it seems take the last value and not the value that I want to delete or update.
I know my code could be more nice.
<div class="container">
<div class="row espacio">
<p class="col-md-1"><a data-toggle="modal" href="#myModal" class="btn btn-default glyphicon glyphicon-plus"><span></span></a></p>
<p class="col-md-1 col-md-offset-10"><span class="btn btn-default glyphicon glyphicon-envelope"></span></p>
<table class="table table-bordered">
<caption>Bitácora</caption>
<thead>
<tr>
<th>Tecnico</th>
<th>Turno</th>
<th>Información</th>
<th>Estado</th>
<th>Creada</th>
<th>Modificada</th>
</tr>
</thead>
<tbody>
<?php
$txt ="";
$nombres =array();
$turnos = array('Mañana','Tarde','Noche');
$estados =array('Pendiente','Cerrado');
$db = new Db;
$sql = "SELECT * FROM tecnicos";
foreach ($db->consulta($sql) as $row) {
array_push($nombres,$row['Nombre']);
}
$sql = 'SELECT * FROM bitacora ORDER BY Estado DESC';
$consulta = $db->consulta($sql);
while ($row = mysqli_fetch_array($consulta)) {
$tecnico = $turno = $estado = "";
if ($row['Estado'] == "Pendiente"){
$txt .= "<tr class= 'bg-warning'>";
}else{
$txt .= "<tr class= 'bg-success'>";
}
$txt .= "
<td>". $row['Name'] . "</td>
<td>". $row['Turno'] . "</td>
<td>". $row['Info'] . "</td>
<td>". $row['Estado'] . "</td>
<td>". $row['RecordDate'] . "</td>
<td>". $row['ModiDate'] . "</td>
<td class='text-center'><a data-toggle='modal' href='#myModalUpdate".$row['Id']."''><span class='glyphicon glyphicon-pencil'></span></a>
<a data-toggle='modal' href='#myModalDelete".$row['Id']."''><span class='glyphicon glyphicon-remove'></span></a> </td>
</tr>";
//MODAL UPDATE
for ($i=0; $i <sizeof($nombres) ; $i++) {
if ($nombres[$i] == $row['Name'] ) {
$tecnico .= '<option value="'.$nombres[$i].'" selected="selected">'.$nombres[$i].'</option>';
}
else{
$tecnico .= '<option value="'.$nombres[$i].'" >'.$nombres[$i].'</option>';
}
}
for ($i=0; $i <sizeof($turnos) ; $i++) {
if ($turnos[$i] == $row['Turno']) {
$turno .= '<option value="'.$turnos[$i].'" selected="selected">'.$turnos[$i].'</option>';
}
else{
$turno .= '<option value="'.$turnos[$i].'" >'.$turnos[$i].'</option>';
}
}
for ($i=0; $i <sizeof($estados) ; $i++) {
if ($estados[$i] == $row['Estado']) {
$estado .= '<option value="'.$estados[$i].'" selected="selected">'.$estados[$i].'</option>';
}
else{
$estado .= '<option value="'.$estados[$i].'" >'.$estados[$i].'</option>';
}
}
$txt .= " <div class='modal fade' id='myModalUpdate".$row['Id']."' role='dialog'>
<div class='modal-dialog'>
<!-- Modal content-->
<div class='modal-content'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal'>×</button>
<h4 class='modal-title'>Modifica registro en Bitácora</h4>
</div>
<div class='modal-body'>
<form role='form' action='' method='post'>
<div class='form-group'>
<input type='text' name='id' value='".$row['Id']."'>
</div>
<div class='form-group'>
<label>Técnico</label>
<select class='form-control' name='modnombre'>
".$tecnico."
</select>
</div>
<div class='form-group'>
<label>Turno</label>
<select class='form-control' name='modturno'>
".$turno."
</select>
</div>
<div class='form-group'>
<label>Información</label>
<textarea class='form-control' name='modinformacion'>".$row['Info']."</textarea>
</div>
<div class='form-group'>
<label>Estado</label>
<select class='form-control' name='modestado'>
".$estado."
</select>
</div>
<div class='form-group text-center'>
<button type='submit' class='btn btn-warning' name='actualizar'>Actualiza</button>
</div>
</div><!--/modal body-->
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
</div>
</div><!--/modal content-->
</div><!--/modal dialog-->
</div><!--/modal-->";
//MODAL DELETE
$txt .= " <div class='modal fade' id='myModalDelete".$row['Id']."' role='dialog' >
<div class='modal-dialog'>
<!-- Modal content-->
<div class='modal-content'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal'>×</button>
<h4 class='modal-title'>Elemina registro en Bitácora</h4>
</div>
<div class='modal-body'>
<form role='form' action='' method='post'>
<div class='form-group'>
<input type='text' name='id' value='".$row['Id']."'>
</div>
<div class='form-group text-center'>
<button type='submit' class='btn btn-danger' name='eliminar'>Elimina</button>
</div>
</div><!--/modal body-->
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
</div>
</div><!--/modal content-->
</div><!--/modal dialog-->
</div><!--/modal-->";
}//end for principal
echo $txt;
?>
</tbody>
</table>
</div>
<!--MODAL CREATE-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Añade registro en Bitácora</h4>
</div>
<div class="modal-body">
<form role="form" action="" method="post">
<div class="form-group">
<label>Técnico</label>
<select class="form-control" name="nombre">
<?php
$txt ="";
$db = new Db;
$sql = "SELECT * FROM tecnicos";
foreach ($db->consulta($sql) as $row) {
$txt.= "<option value='".$row['Nombre']."'>".$row['Nombre']."</option>";
}
echo $txt;
?>
</select>
</div>
<div class="form-group">
<label>Turno</label>
<select class="form-control" name="turno">
<option value="Mañana">Mañana</option>
<option value="Tarde">Tarde</option>
<option value="Noche">Noche</option>
</select>
</div>
<div class="form-group">
<label>Información</label>
<textarea class="form-control" name="informacion"></textarea>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success" name="crear">Crear</button>
</div>
</form>
</div><!--/modal body-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!--/modal content-->
</div><!--/modal dialog-->
</div><!--/modal-->
</div> <!-- /container -->
And these are the action´s form
enter code //formulario CREATE
if(isset($_POST["crear"])) {
$nombre = $_POST["nombre"];
$turno = $_POST["turno"];
$informacion = $_POST["informacion"];
$sql = "INSERT INTO bitacora (Name,Turno,Info,Estado,RecordDate,ModiDate) VALUES ('" . $nombre . "', '" . $turno . "', '" . $informacion . "','Pendiente',now(),now())";
$db->consulta($sql);
}
//formulario UPDATE
if(isset($_POST["actualizar"])) {
$sql = "UPDATE bitacora SET Name = '" . $_POST["modnombre"] . "', Turno = '" . $_POST["modturno"] . "', Info = '" .$_POST["modinformacion"]. "', Estado = '" . $_POST["modestado"] . "' , ModiDate =now() WHERE Id = '".$_POST["id"]."' ";
$db->consulta($sql);
}
//form DELETE
if(isset($_POST["eliminar"])) {
$id = $_POST["id"];
$sql = "DELETE FROM bitacora WHERE Id = $id";
$db->consulta($sql);
}here

It seems that your input named "id" is not taking the correct value of $row['Id']. Try to inspect it and see if his "value" is not empty.
If the value was empty, your problem is the value of $row['Id'].
Try to replace $row['Id'] by $row['id'] and see the results.

Related

Didn't get the ID from database based on row table

Why I can't get the ID from a row in table when I click Pending
Here is the code:
<!-- ############################################################################################################################################################################################################ -->
<!-- TABLE BUSINESS -->
<div class="row" id="TblBiz" style="display: none;">
<div class="col" style="height: 71px;">
<h1 style="font-family: Roboto, sans-serif; font-weight: 300;">Business</h1>
</div>
<div class="col-md-8 offset-md-2">
<div class="panel" id="main">
<div class="container-fluid container-bg">
<div class="table-responsive">
<table id="myTable4" class="table table-hover table-dark" style="font-size:11px; margin-top:6px;">
<thead style="font-size: 18px;">
<th>#</th>
<th>Business ID</th>
<th>Name</th>
<th>Owner</th>
<th>View</th>
<th>Approval</th>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM mechanic_business";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
$biz_ID = $row['businessID'];
$mech_ID = $row['mechID'];
$mech_name = $row['mech_name'];
$bizName = $row['business_name'];
$bizApprove = $row['business_approval_status'];
$bizStatus = $row['business_status'];
// $dateJoin = $row['DATE_REGISTERED'];
// $dateFormated = date("d M Y", strtotime($dateJoin));
// Color class in PHP color(Pending, Approved, Banned)
$color = ($bizApprove === 'Pending') ? '#f0ad4e' : (($bizApprove === 'Approved') ? '#28a745' : '#dc3545');
echo "<tr style='font-size:18px;'>";
echo "<td class='align-middle'>" . $i; $i++ . "</td>";
echo "<td class='align-middle'>" . $biz_ID . "</td>";
echo "<td class='align-middle'>". $bizName ."</td>";
echo "<td class='align-middle'>". $mech_name ."</td>";
echo "<td class='align-middle'><input type='button' name='view' value='view' id='". $biz_ID ."' class='btn btn-info btn-xs view_biz'></td>";
echo "<td class='align-middle'><a role='button' class='approval-bton' id='". $biz_ID ."' style='color:". $color ."';>". $bizApprove ."</a></td>";
echo "</tr>";
}
} else {
echo "<tr>";
echo "<td colspan='7' class='table-active align-middle'>No Record in Database</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- ############################################################################################################################################################################################################ -->
<!-- ############################################################################################################################################ -->
<!-- UPDATE APPROVE STATUS MODAL -->
<div class="modal fade" id="approveModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"> Update Business Approval Status </h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="" method="post" enctype="multipart/form-data">
<div class="modal-body">
<input type="text" name="businessID" id="" value="<?php echo $biz_ID; ?>">
<div class="form-group">
<div>
<small id="photoHelp" class="form-text text-muted"><span style="color: #FF0000;">*</span><em>320px x 320px is ideal dimension, Format: jpg, png, jpeg, and PDF only</em></small>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" name="updateApprove" class="btn btn-primary">Save Change</button>
</div>
</form>
</div>
</div>
</div>
<!-- ############################################################################################################################################ -->
When I clicked a Pending from each row it suppose to get their ID based on the database but when I clicked from each row they display the same ID as shown picture in the link below.
https://drive.google.com/file/d/1IcfDUs3Q8Wl5vVO3KF793M5noTukLrCL/view?usp=sharing
They both show ORVA01BIZ-00000002 but in database first row is ORVA01BIZ-00000001 and ORVA01BIZ-00000002 is the second row and goes on.
There is very simple logic.
first, your model is not in loop so you can't pass $biz_ID in the model if you want to get each id from the database.
When the loop ends then it will only print the last row biz_id in the model.
The solution is :-
Changes you have to do in your code
You have to do one thing if you want to get each id
This is your second td :-
echo "<td class='align-middle bizzid'>" . $biz_ID . "</td>";
In your model you have to paste this : -
<input type="text" name="businessID" id="businessID" value="">-
This jquery code can help you to get desired result.
var bizid = $(this).closest('tr').find('.bizzid').text();
$('#businessID').val(bizid);
$('#approveModal').modal('show');
});'
Okay, got it
I did what you asked #Gurpreet Kait it really workss.
I put the jquery code inside the initialize modal bootstrap
// Show Modal 1
$(document).ready(function () {
$('.approval-bton').on('click', function() {
var bizid = $(this).closest('tr').find('.bizzid').text();
$('#businessID').val(bizid);
$('#approveModal').modal('show');
});
Thank you very much #Gurpreet Kait for your help.
});

Isset only checks first checkbox from database

I have a component that gets all data from the MySQL database.
<?php
function component($productName, $productPrice, $productImg, $productID)
{
$element = "
<div class='col-md-3 col-sm-6 my-3 my-md-0'>
<form action='index.php' method='post' id='myform'>
<div class='card shadow'>
<img src='{$productImg}' alt='image1' class='img-fluid card-img-top'>
<div class=\"card-body\">
<h5 class='card-title'>{$productName}</h5>
</div>
<p class='card-text'>info goes here lorem ipsum</p>
<span class='price'>{$productPrice}</span>
<span class='price'>{$productID}</span>
<div class='form-check form-switch'>
<input class='form-check-input' type='checkbox' name='checkid[]' value='{$productID}'>
</div>
<input type='hidden' name='product_id' value='{$productID}'>
</div>
</form>
</div>
";
echo $element;
}
I also have submit button for the form.
<button type="submit" name="submit" form="myform">show selected</button>
code to get containers:
<div class="container">
<div class="row text-center py-5">
<?php
$result = $database->getData();
while ($row = mysqli_fetch_assoc($result)) {
component($row['product_name'], $row['product_price'], $row['product_image'], $row['id']);
}
?>
</div>
And PHP code to check whether container is checked and return its value (productID) when submit button is clicked.
if (isset($_POST['submit'])) {
if (!empty($_POST['checkid'])) {
foreach ($_POST['checkid'] as $value) {
echo "value : " . $value . '<br/>';
}
}
}
I have several products in the database, but it only works for first checkbox. Others don't do anything.
You are creating a new form element each loop.
You can change your function like
function component($productName, $productPrice, $productImg, $productID)
{
$element = "
<div class='card shadow'>
<img src='{$productImg}' alt='image1' class='img-fluid card-img-top'>
<div class=\"card-body\">
<h5 class='card-title'>{$productName}</h5>
</div>
<p class='card-text'>info goes here lorem ipsum</p>
<span class='price'>{$productPrice}</span>
<span class='price'>{$productID}</span>
<div class='form-check form-switch'>
<input class='form-check-input' type='checkbox' name='checkid[]' value='{$productID}'>
</div>
<input type='hidden' name='product_id' value='{$productID}'>
</div>
";
echo $element;
}
and code to get your components (function above) and submit button in a single form like
<div class="container">
<div class="row text-center py-5">
<div class='col-md-3 col-sm-6 my-3 my-md-0'>
<form action='index.php' method='post' id='myform'>
<?php
$result = $database->getData();
while ($row = mysqli_fetch_assoc($result)) {
component($row['product_name'], $row['product_price'], $row['product_image'], $row['id']);
}
?>
<button type="submit" name="submit" form="myform">show selected</button>
</form>
</div>
</div>

How to delete a row printed in a while loop using a modal window in PHP, MYSQL

I'm very noob in PHP, but i'm really stuck here trying to figure out how to delete a row printed in a while loop here :
<?php
$sql5 = "SELECT * FROM user_exp WHERE id=".$_SESSION["ID"]."";
$result3 = mysqli_query($conn, $sql5);
if (mysqli_num_rows($result3) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result3)) {
echo "<h4>" . $row["exp_title"]. "<a href='#' title=''><i class='fa fa-pencil'></i><i onclick='location.href='userprofile.php?deleteID=".$row["auto_id"]."';' class='fa fa-minus-square' data-toggle='modal' data-target='#EXPDELModal' value='delete_exp'></i></a></h4>";
echo "<p>" . $row["exp_detail"]. "</p>";
}
}
else
{
echo "<div class='textfaded2'>Add you experience here.</div>";
}
?>
Note: i want to delete the row using a font-awesome icon and i'm using
'auto_id' as the auto_increment, primary key to define the row i want
to delete.
Here is the code for the modal:
<div class="modal fade" id="EXPDELModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Delete Experience</h4>
</div>
<div class="modal-body">
<h3>Are you sure?</h3>
<br>
<br>
</div>
<div class="modal-footer">
<form action="userprofile.php?deleteID=<?php '.$row["auto_id"].';?>"
style="width: 100%;" method="post" value="delete_exp">
<button type="button" name="delete" class="btn btn-default" data-
dismiss="modal">YES</button>
<button type="button" class="btn btn-default" data-
dismiss="modal">NO</button>
</form>
</div>
</div>
</div>
</div>
And finally the query for delete:
<?php
if(isset($_POST['delete']))
{
$sql6="DELETE FROM `user_exp` WHERE auto_id=".$_GET['deleteID']."";
$result=mysqli_query($conn,$sql6) or die();
}
?>
I would like to thank you for taking the time to read this.
<?php
$sql5 = "SELECT * FROM user_exp WHERE id=" . $_SESSION["ID"] . "";
$result3 = mysqli_query($conn, $sql5);
if (mysqli_num_rows($result3) > 0) {
while ($row = mysqli_fetch_assoc($result3)) {
?>
<h4><?php echo $row["exp_title"]; ?>
<a href='#' title=''>
<i class='fa fa-pencil'></i>
<i onclick='setValue("<?php $row["auto_id"]; ?>");' class='fa fa-minus-square' data-toggle='modal'
data-target='#EXPDELModal'></i>
</a>
</h4>
<p><?php echo $row["exp_detail"]; ?></p>;
<?php
}
} else {
echo "<div class='textfaded2'>Add you experience here.</div>";
}
if (isset($_POST['delete'])) {
if($_POST['deleteID']) {
$sql6 = "DELETE FROM `user_exp` WHERE auto_id=" . $_POST['deleteID'] . "";
$result = mysqli_query($conn, $sql6) or die();
}
}
?>
<script>
function setValue(value) {
document.getElementById("deleteId").value = value;
}
</script>
<div class="modal fade" id="EXPDELModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Delete Experience</h4>
</div>
<div class="modal-body">
<h3>Are you sure?</h3>
<br>
<br>
</div>
<div class="modal-footer">
<form action="userprofile.php" style="width: 100%;" method="post" name="delete_exp">
<input type="hidden" value="0" name="deleteID" id="deleteId" readonly/>
<button type="submit" name="delete" class="btn btn-default" data-dismiss="modal">YES</button>
<button type="button" class="btn btn-default" data-dismiss="modal">NO</button>
</form>
</div>
</div>
</div>
</div>

Echo HTML tag problems with quotes

I am trying to put quotes in the php that handles the select tag. I need that the select tag displays the result of the query that is inside. How can I do this correctly?
<?php
$sql1 = mysql_query("SELECT * FROM `metlab`.`cutlog_junta` WHERE `finalizado` = 0")or die (mysql_error());
$idtimeleft= 0;
while($array = mysql_fetch_array($sql1, MYSQL_BOTH)){
$idtimeleft++;
$idprueba = $array[0];
$id_log = $array["id_log"];
$id_operador = $array["id_operador"];
$started = $array["started"];
$finished = $array["finished"];
date_default_timezone_set("America/Mexico_City");
$tiempo1 = new DateTime('now');
$tiempo2 = new DateTime($finished);
if ($tiempo1 < $tiempo2){
$tiemporestante = date_diff($tiempo2,$tiempo1 );
$timeleft = $tiemporestante->format("%h:%i:%s");
}else{
$timeleft = "00:00:00";
}
$sql = mysql_query("SELECT r.job AS JOB,p.heat_code AS HEAT_CODE,p.probeta AS PROBETA,p.id_line AS ID_LINE,p.id_box_pin AS ID_BOX_PIN,p.id_conexion AS ID_CONEXION
FROM metlab.prueba_junta p
INNER JOIN metlab.requerimientos_junta r ON p.id_job=r.id WHERE p.id='".$id_log."'")or die (mysql_error());
$mhs = mysql_fetch_array($sql);
echo (" <tr id='row". $idtimeleft ."'>
<td><input type='checkbox' name='record'></td>
<td>" . $id_log . "</td>
<td>" . $mhs['JOB'] . "</td>
<td>" . $mhs['ID_BOX_PIN'] . "</td>
<td>" . $mhs['ID_CONEXION'] . "</td>
<td>" . $mhs['HEAT_CODE'] . "</td>
<td>" . $mhs['PROBETA'] . "</td>
<td>" . $mhs['ID_LINE'] . "</td>
<td>" . $started . "</td>
<td><div id='idtimeleft" . $idtimeleft ."'>" . $timeleft . "</div></td>
<td><button type='button' class='btn btn-primary' data-toggle='modal' data-target='#cut_process'><i class='fa fa-cog fa-spin'></i>CUT</button>
<div id='cut_process' class='modal fade' role='dialog'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<button type='button'class='close' data-dismiss='modal'>×</button>
<h4 class='modal-title'>CUT PROCESS</h4>
</div>
<div class='modal-body'>
<input type='text' placeholder='INSERT COMMENT' class='form-control'><br>
<label>Supervisor:</label>
<select class='btn btn-primary'>
<?php //////////////////////////////problem
$query='SELECT nombre
FROM metlab.supervisores';
$result1=mysql_query($query);
while($row1=mysql_fetch_array($result1)):;?>
<option><?php echo $row1[0];?>
</option>
<?php endwhile;?>
</select> /////////////////////////////end problem
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-success' data-dismiss='modal'><i class='fa fa-paper-plane'></i>SEND COMMENT</button>
</div>
</div>
</div>
</div>
</td>
<td>
<button type='button' class='btn btn-warning' data-toggle='modal' data-target='#milling_process'><i class='fa fa-cog fa-spin'></i>MILLING</button>
<div id='milling_process' class='modal fade' role='dialog'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<button type='button'class='close' data-dismiss='modal'>×</button>
<h4 class='modal-title'>MILLING PROCESS</h4>
</div>
<div class='modal-body'>
<input type='text' placeholder='INSERT COMMENT' class='form-control'>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-success' data-dismiss='modal'><i class='fa fa-paper-plane'></i>SEND COMMENT</button>
</div>
</div>
</div>
</div>
</td>
<td>
<button type='button' class='btn btn-success' data-toggle='modal' data-target='#rectified_process'><i class='fa fa-cog fa-spin'></i>RECTIFIED</button>
<div id='rectified_process' class='modal fade' role='dialog'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<button type='button'class='close' data-dismiss='modal'>×</button>
<h4 class='modal-title'>RECTIFIED PROCESS</h4>
</div>
<div class='modal-body'>
<input type='text' placeholder='INSERT COMMENT' class='form-control'>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-success' data-dismiss='modal'><i class='fa fa-paper-plane'></i>SEND COMMENT</button>
</div>
</div>
</div>
</div>
</td>
<td>
<button type='button' class='btn btn-danger' data-toggle='modal' data-target='#machined_process'><i class='fa fa-cog fa-spin'></i>MACHINED</button>
<div id='machined_process' class='modal fade' role='dialog'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<button type='button'class='close' data-dismiss='modal'>×</button>
<h4 class='modal-title'>MACHINED PROCESS</h4>
</div>
<div class='modal-body'>
<input type='text' placeholder='INSERT COMMENT' class='form-control'>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-success' data-dismiss='modal'><i class='fa fa-paper-plane'></i>SEND COMMENT</button>
</div>
</div>
</div>
</div>
</td>
<td>" . $finished . "</td>
<td>" . $idprueba . "</td>
</tr>");
}
?>
I think you should write directly HTML code inside the page avoiding PHP echo function.
In this example you use PHP short tag only when you need it:
<tr id="row<?=$idtimeleft?>">
And when you need to perform some action you just open PHP tag and write your code.
<select>
<?php
$query='SELECT nombre FROM metlab.supervisores';
$result1=mysql_query($query);
while($row1=mysql_fetch_array($result1)):
?>
<option><?=$row1[0]?></option>
<?php endwhile;?>
</select>
You don't need semicolon after "while(...):"
Anyway you should read something about Twig to use template engine to write cleaner code.
Bye!!

Bootstrap-table - Modify fields with bootstrap modal

I continue with my new website and I'm trying the bootstrap framework and I would like modify a row, its fields, from a bootstrap modal window. At moment I show a modal windows with fields but I don't know to include the data from the row of the table :(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AddCloud - Producció</title>
<!-- INCLUDES -->
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/bootstrap-table/dist/bootstrap-table.css">
<link rel="stylesheet" href="assets/bootstrap-editable/css/bootstrap-editable.css">
<script src="assets/jquery/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/bootstrap-table/dist/bootstrap-table.js"></script>
<script src="assets/bootstrap-editable/js/bootstrap-editable.js"></script>
</head>
<body>
<!-- SESSION PHP OK -->
<?php
session_start();
if(isset($_SESSION['username']) and $_SESSION['username'] <> ''){
?>
<!-- NAVIGATION -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar1"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button>
<a class="navbar-brand" href="http://www.addvantage.es"><font color=#8abe44>AddCloud</font></a></div>
<div class="collapse navbar-collapse" id="defaultNavbar1">
<ul class="nav navbar-nav">
<li class="active">Producció<span class="sr-only">(current)</span></li>
<li>Menu2</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-expanded="false"><span class="glyphicon glyphicon-user"></span> <?php echo $_SESSION['username'] ?></a>
<ul class="dropdown-menu" role="menu">
<li><span class="glyphicon glyphicon-wrench"></span> preferències</li>
<li><span class="glyphicon glyphicon-lock"></span> canviar password</li>
<li class="divider"></li>
<li><span class="glyphicon glyphicon-log-out"></span> log out</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<!-- TABLE -->
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="text-center">Miquel Alimentació</h1>
</div>
</div>
<hr>
</div>
<div class="container">
<div class="row text-center">
<div class="col-md-6 col-md-offset-3"><h3>Edició 12</h3></div>
</div>
<hr>
<div class="row">
<?php
// Conexió a la base de dades
include("connect.php");
$conn = Conectarse("localhost", "5432", "dbname", "dbuser", "dbpass");
//query
$query = "SELECT * FROM produccion.ma_origen ORDER BY id_articulo ASC";
$result = pg_query($conn, $query);
//se despliega el resultado
echo "<table id='tableprod'
data-toggle='table'
data-toolbar='#toolbar'
data-show-refresh='true'
data-show-toggle='true'
data-sort-name='name'
data-sort-order='desc'
data-show-columns='true'
data-pagination='true'
data-search='true'
data-click-to-select='true'>";
echo "<thead class='thead-inverse'>";
echo "<tr>";
echo "<th data id='seleccion' data-switchable='false' data-checkbox='true'></th>";
echo "<th data id='pagina' data-sortable='true'>pagina</th>";
echo "<th data id='codigo' data-sortable='true' data-switchable='false'>codigo</th>";
echo "<th data id='descripcion' data-sortable='true' data-switchable='false'>descripcion</th>";
echo "<th data id='pvp-cat' data-sortable='true'>pvp-cat</th>";
echo "<th data id='pvp-lev' data-sortable='true'>pvp-lev</th>";
echo "<th data id='pvp-and' data-sortable='true'>pvp-and</th>";
echo "<th data id='pvp-cen' data-sortable='true'>pvp-cen</th>";
echo "<th data id='pvp-nor' data-sortable='true'>pvp-nor</th>";
echo "<th data id='pvp-vas' data-sortable='true'>pvp-vas</th>";
echo "<th data id='fecha-mod' data-sortable='true'>fecha-mod</th>";
echo "<th data id='user' data-sortable='true' data-visible='false'>user</th>";
echo "<th data id='edit' data-sortable='false' data-switchable='false'>edit</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($row = pg_fetch_row($result)){
echo "<tr>";
echo "<td></td>";
echo "<td>$row[2]></td>";
echo "<td>$row[3]</td>";
echo "<td>$row[4]</td>";
echo "<td>$row[5]</td>";
echo "<td>$row[6]</td>";
echo "<td>$row[7]></td>";
echo "<td>$row[8]</td>";
echo "<td>$row[9]</td>";
echo "<td>$row[10]</td>";
echo "<td>$row[11]</td>";
echo "<td>$row[12]</td>";
echo "<td><p data-placement='top' data-toggle='tooltip' title='Edit'><button class='btn btn-primary btn-xs' data-title='Edit' data-toggle='modal' data-target='#edit' ><span class='glyphicon glyphicon-pencil'></span></button></p></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
</div>
</div>
<hr>
<div class="row">
<div class="text-center col-md-6 col-md-offset-3">
<p>Copyright © 2016 · All Rights Reserved · <a href="http://www.addvantage.es/" >http://www.addvantage.es</a></p>
</div>
</div>
<hr>
</div>
<!-- MODAL MENU -->
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
<h4 class="modal-title custom_align" id="Heading">Editar registre</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input class="form-control " type="text" placeholder="Pàgina">
</div>
<div class="form-group">
<input class="form-control " type="text" placeholder="Codi">
</div>
<div class="form-group">
<input class="form-control " type="text" placeholder="Descripció">
</div>
<div class="form-group">
<input class="form-control " type="text" placeholder="pvp-cat">
</div>
<div class="form-group">
<input class="form-control " type="text" placeholder="pvp-lev">
</div>
<div class="form-group">
<input class="form-control " type="text" placeholder="pvp-and">
</div>
<div class="form-group">
<input class="form-control " type="text" placeholder="pvp-cen">
</div>
<div class="form-group">
<input class="form-control " type="text" placeholder="pvp-nor">
</div>
<div class="form-group">
<input class="form-control " type="text" placeholder="pvp-vas">
</div>
</div>
<div class="modal-footer ">
<button type="button" class="btn btn-warning btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Update</button>
</div>
</div>
</div>
</div>
<!-- SESSION PHP ERROR -->
<?php
} else{
?><p>La sesión no está activa, por favor ingrese aquí</p>
<?php
}?>
</body>
</html>
I use php to connect to database and add data into the table. My idea is from a edit button can modify this fields from a modal window. After that I would like to update database.
I'm not sure if this is the best way, I haven't a experience programming from web environment.
Please Could you help me to modify this data-fields from windows modal?
Thanks!
The way to try to do is correct. What you have to do is on clicking Edit link find the closest tr and find all the td that tr contain. Read td one by one the assign it to the text box.
Below is the code:
$('.edit').click(function(){
var $row = $(this).closest("tr"), $tds = $row.find("td"); //This will all the tds we need.
$.each($tds, function() {
$('#txtbox').val($(this).text()); //textbox in the modal window
});
});
The above code will fill all the values from the row to modal window after that you can modify and submit the form.
First step - identify row somehow. I'm working under assumption that $row[0] is the id of that row in the database. If it isn't change the code accordingly.
index.php
while ($row = pg_fetch_row($result)){
echo "<tr id="{$row[0]}">"; // assign id that corresponds to database id to each row
echo "<td></td>";
echo "<td class="pagina">$row[2]></td>";
echo "<td class="codigo">$row[3]</td>";
echo "<td class="descripcion">$row[4]</td>";
echo "<td class="pvp-cat">$row[5]</td>";
echo "<td class="pvp-lev">$row[6]</td>";
echo "<td class="pvp-and">$row[7]></td>";
echo "<td class="pvp-cen">$row[8]</td>";
echo "<td class="pvp-nor">$row[9]</td>";
echo "<td class="pvp-vas">$row[10]</td>";
echo "<td class="fecha-mod">$row[11]</td>";
echo "<td class="user">$row[12]</td>";
echo "<td>
<p data-placement='top' data-toggle='tooltip' title='Edit'>
<button class='edit' class='btn btn-primary btn-xs' data-title='Edit' data-toggle='modal' data-target='#edit'>
<span class='glyphicon glyphicon-pencil'></span>
</button>
</p>
</td>";
echo "</tr>";
}
Second, set jquery click event to copy values from rows and fill the modal input fields with correct values:
JQUERY
$('.edit').click(function(){
var row = $(this).closest("tr"), // edit button is in the same row as data you want to change
tds = row.find("td"); // get all table cells in that row
$.each(tds, function(index) {
if( $.inArray(index, [0, 10, 11, 12]) ) { // indexes of cells not to be used when getting data from table cells to edit
return; // skip to next loop iteration if one of these indexes
}
var input_name = $(this).attr("class"); // get name of cell we are evaluating (pagina, codigo, descripcion etc)
$([name='"' + input_name + '"']).val($(this).text()); //input name in the modal window
});
});
I've changed the modal to reflect changes in code above.
MODAL
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
<h4 class="modal-title custom_align" id="Heading">Editar registre</h4>
</div>
<form action="/store.php">
<div class="modal-body">
<input type="hidden" name="id" type="text"> <!-- hidden input for id -->
<div class="form-group">
<input class="form-control" name="pagina" type="text" placeholder="Pàgina">
</div>
<div class="form-group">
<input class="form-control" name="codigo" type="text" placeholder="Codi">
</div>
<div class="form-group">
<input class="form-control" name="descripcion" type="text" placeholder="Descripció">
</div>
<div class="form-group">
<input class="form-control" name="pvp-cat" type="text" placeholder="pvp-cat">
</div>
<div class="form-group">
<input class="form-control" name="pvp-lev" type="text" placeholder="pvp-lev">
</div>
<div class="form-group">
<input class="form-control" name="pvp-and" type="text" placeholder="pvp-and">
</div>
<div class="form-group">
<input class="form-control" name="pvp-cen" type="text" placeholder="pvp-cen">
</div>
<div class="form-group">
<input class="form-control" name="pvp-nor" type="text" placeholder="pvp-nor">
</div>
<div class="form-group">
<input class="form-control" name="pvp-vas" type="text" placeholder="pvp-vas">
</div>
</div>
<div class="modal-footer ">
<input type="submit" class="btn btn-warning btn-lg" style="width: 100%;" value="Update">
</div>
</form>
</div>
</div>
</div>
File for storing edited values to the database:
store.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['id'];
$pagina = $_POST['pagina'];
$codigo = $_POST['codigo'];
$descripcion = $_POST['descripcion'];
$pvp-cat = $_POST['pvp-cat'];
$pvp-lev = $_POST['pvp-lev'];
$pvp-and = $_POST['pvp-and'];
$pvp-cen = $_POST['pvp-cen'];
$pvp-nor = $_POST['pvp-nor'];
$pvp-vas = $_POST['pvp-vas'];
$sql = "UPDATE produccion.ma_origen SET pagina='{$pagina}',codigo='{$codigo}',descripcion='{$descripcion}',
pvp-cat='{$pvp-cat}', pvp-lev='{$pvp-lev}',pvp-and='{$pvp-and}',
pvp-cen='{$pvp-cen}',pvp-nor='{$pvp-nor}',pvp-vas='{$pvp-vas}'
WHERE id={$id}";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Since this was a lot of code to change and I don't have the time and all the data to test this properly you'll have to do it, but this is one of the ways you could solve your problem. Hope it helps.

Categories