Inserting table data to sql - php

I have a modal that will let user choose an equipment then input the quantity.
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="button-1 btn-lg" data-toggle="modal" data-target="#myModal" style="width: 26%; margin:0; height: 40px; font-size: 100%;">Choose Equipment</button>
<!-- MODAL -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- MODAL CONTENT-->
<div class="modal-content">
<div class="modal-header">
<p>Choose An Equipment Below</p>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>Available Equipments</p>
<div class="form-inline">
<!-- DROPDOWN LIST FROM DATABASE -->
<select id="equipment" name="equipment" class="form-control">
<option selected="" disabled="">Select Equipment</option>
<?php
$sql = mysqli_query($conn, "SELECT resource_name From resources WHERE resource_type = 'EQUIPMENT';");
$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
echo "<option name = 'equipment' value ='". $row['resource_name'] ."'>" .$row['resource_name'] ."</option>" ;
}
?>
</select>
<br><br>
<input type="text" id="qnty-1" class="form-control" placeholder="Quantity" name="quantity" style="width:24%; margin-left: 50px;"><br/>
<br/><br/>
</div>
</div>
<div class="modal-footer">
<input class="submit-3" id="addToTable" type="submit" value="Submit" name="submit-2" onclick="passValue1(); trigData()" data-dismiss="modal" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
When submitted, the modal will disappear and the data that has been selected will display on the table. I can insert the first selected data to the database but if I choose 2 different data or same data, It will just insert one on the database. Is there a way I can insert all selected data to the database?
<div class="b-form-outline">
<h1>Equipment Borrowing Form</h1>
<div class="borrow-list-area">
<table class="container-2" id="container-2">
<thead>
<tr>
<style>
th,
td {
text-align: center;
}
</style>
<th>Equipment</th>
<th>Quantity</th>
<th hidden>Serial No.</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
function passValue1() {
document.getElementById("quantity").innerHTML =
document.getElementById("qnty-1").value;
}
$('#addToTable').click(function() {
var eqpmnt = $('#equipment').val(),
qnt = $('#qnty-1').val();
$('table tbody').append('<tr><td>' + eqpmnt + '</td><td>' + qnt + '</td>
</tr>');
});
I've tried this insert code but again, it will only insert one row of data from the table. If anyone can please help me. Thanks a lot!
<?php
include('dbconnector.php');
$id_num = $_POST['idnumber'];
$s_date = $_POST['startdate'];
$e_date = $_POST['enddate'];
$s_time = $_POST['starttime'];
$e_time = $_POST['endtime'];
$prpse = $_POST['purpose'];
$equipment = $_POST['equipment'];
$qnty = $_POST['quantity'];
$subj = $_POST['subject'];
$onCamp = isset($_POST['check-1']) ? $_POST['check-1'] : "Off-Campus";
// CREATES A NEW TRANSACTION THAT WAS SUBMITTED USING THE BORROW FOWM
$query = "SELECT * FROM resources;"; // ACCESS TABLE RESOURCES
$con = mysqli_query($conn, $query);
if ($con->num_rows > 0){
while($row = mysqli_fetch_array($con)){
$rsname = $row['resource_name'];
if (strcmp($equipment, $rsname) == 0) {
$sql = "INSERT INTO transactions (id_number, start_date, end_date, start_time, end_time, purpose, quantity, subject, use_place) VALUES ('$id_num', '$s_date', '$e_date', '$s_time', '$e_time', '$prpse', '$qnty', '$subj', '$onCamp');";
}
}
}
if (!mysqli_query($conn,$sql)) {
$message = "Error Sending Form";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else {
header("refresh: 1; url=borrow.php");
}
?>
Adjusted for #Jon Stirling
$query = "SELECT * FROM resources;"; // ACCESS TABLE RESOURCES
$con = mysqli_query($conn, $query);
if ($con->num_rows > 0){
while($row = mysqli_fetch_array($con)){
$rsname = $row['resource_name'];
if (strcmp($equipment, $rsname) == 0) {
$sql = "INSERT INTO transactions (id_number, start_date, end_date, start_time, end_time, purpose, quantity, subject, use_place) VALUES ('$id_num', '$s_date', '$e_date', '$s_time', '$e_time', '$prpse', '$qnty', '$subj', '$onCamp');";
if (!mysqli_query($conn,$sql)) {
$message = "Error Sending Form";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else {
header("refresh: 1; url=borrow.php");
}
}
}
}

Related

How to submit just one button from a set of buttons that are displayed using a php while-loop

I am coding a website for an online university portal where I have a programs/courses page in which I am displaying the programs/courses on the page using data from the database in a PHP while-loop I have the enroll buttons also being displayed in that same while loop. but I'm having a bit of difficulty submitting the enroll buttons as when I click one of them all of them get submitted.
can anyone please let me know what I'm doing wrong here or if I have to use any javascript in this case!
<?php
session_start();
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, 'htdatabase');
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$id = $_SESSION['userID'];
$sql = "SELECT * FROM programs";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$i = '';
$progID = $row["progID"];
$name = $row["progName"];
$halfTime = $row["halfTDuration"];
$fullTime = $row["fullTDuration"];
$fee = $row["fee"];
$descrip = $row["description"];
$stringname = strval($name);
$spaceRemoved = str_replace(' ', '', $stringname);
?>
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<?php echo "<button class='btn btn-link' type='button' data-toggle='collapse' data-target='#$spaceRemoved' aria-expanded='false' aria-controls='$spaceRemoved'> $name </button>"; ?>
</h5>
</div>
<?php echo "<div id='$spaceRemoved' class='collapse' aria-labelledby='headingOne' data-parent='#accordionExample'>"; ?>
<div>
<div class="ccard-body col-md-9">
<h6><?php echo $descrip; ?></h6>
<hr>
<h5>Duration:</h5>
<h6>Full time: <?php echo $fullTime; ?></h6>
<h6>Half time: <?php echo $halfTime; echo $i; ?></h6>
<hr>
<h5 style="display: inline-block;">Estimated fees: $</h5><h5 style="display: inline-block;"><?php echo $fee ?></h5>
</div>
<form action="programs.php" method="post">
<div id="enroll" class="col-md-3">
<?php
$sql1 = "SELECT * FROM userprograms WHERE userID = '$id' AND progID = '$progID'";
$result1 = $con->query($sql1);
if ($result1->num_rows > 0) {
echo '<div id="enrolled" name="enrolled">ENROLLED</div>';
} else {
if (isset($_POST["enroll"])) {
$enrollqry = "insert into userprograms (userID, progID) values ('$id' , '$progID')";
mysqli_query($con, $enrollqry);
}
echo "<button name='enroll'type='submit'>ENROLL</button>";
}
?>
</div>
</form>
</div>
</div>
<?php
}
} ?>
You can specify a value for the button. like
<button name='enroll' value="<?php echo $program_id?>" type='submit'>ENROLL</button>
Then when checking for $_POST['enroll'] check the value and also validate it before entry to db.
After clicking the submit button a browser will send a POST request to programs.php with a form data, that includes values of input & button tags.
<input type="submit" name="course1" value="42">Subscribe</input>
<input type="text" name="first_name" placeholder="Your name"/>
Will send
course1=42
first_name=...
So you should either give a unique name to each submit button to be able to distinguish them on the server-side, or set up distinct values, as #mohamed-jailam mentioned above.

How to get ID of item from database in <select><option> Tag

Hello. I have a problem with the more difficult code but here I tried to simplify it a bit just to ask a question ... I have 3 tables in database: cars(cars_id,model), customers(customer_id,name,surname), sales(sales_id,customer_id,cars_id).And I don't know how to get the ID for the selected option in the select option tag. For example, for BMW X6 I want to get to ID = 2 and put this value in the cars_id column in the SALES table to avoid data redundancy. It's about relation. cars_id in the CARS table is the same as cars_id in the SALES table. But I want to do this using PHP MySQL.
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=store", "root", "");
function fill_unit_select_box($connect)
{
$output = '';
$query = "SELECT * FROM cars";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output .= '<option value="'.$row["model"].'">'.$row["model"].'</option>';
}
return $output;
}
?>
<html>
<head>
<title>Sales form</title>
<script src="jquery-3.5.0.min.js" defer></script>
<link rel="stylesheet" href="bootstrap.min.css" />
<script src="jquery-3.5.0.min.js"></script>
</head>
<body>
<div class="container">
<h3 align="center">Sales form</h3><br />
<form method="post" id="insert_form">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th >sales</th>
<th >customer</th>
<th >cars</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus">Add</span></button></th>
</tr>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Send" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td class="lp"></td>';
html += '<td><input type="text" name="customers_name[]"></td>';
html += '<td><select style="backbround-color:white;"name="cars_name[]" class="form-control size_id"><option value=""><?php echo fill_unit_select_box($connect); ?></option></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Usuń</span></button></td></tr>';
$('#item_table').append(html);
var count=0;
$('.lp').each(function(){
count=count+1;
$(this).text(count);
});
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Dane zostały wysłane</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
<?php
//insert.php;
session_start();
if(isset($_POST["customers_name"]))
{
$connect = new PDO("mysql:host=localhost;dbname=store", "root", "");
for($count = 0; $count < count($_POST["customers_name"]); $count++)
{
$query = "INSERT INTO sales
(customer_id,cars_id)
VALUES (:customer_id,:cars_id)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':customer_id' => $_POST["customers_name"][$count],
':cars_id' => $_POST["cars_name"][$count],
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
?>
So, you just have to edit your $output like this.
value="'.$row["model"] to value="'.$row["cars_id"]
change to cars_id only for value, so the user can see the name but you get id on form submit.

Changing form fields with ajax but field values not passing on submit

I have a standard form with a drop down list of customers, using ajax when a customer is selected it calls the load-customers.php page and changes the form fields entirely based on customer_id whilst filling it with the relevant information.
One of these fields is another drop drown called address_id which again allows the user to select from multiple addresses already defined for the selected customer.
The issue is, address_id is not being passed to $_POST on submit, to be fair none of the other fields are either... but the other fields are just placeholders and i only care about the customer_id and address_id.
How do i get around this? This is the only bit of ajax I've ever used.
ajax:
function getCustomer(val) {
$.ajax({
type: "POST",
url: "load-customers.php",
data:'id='+val,
success: function(data){
$("#customer").html(data);
}
});
}
customer:
<div class='form-group row'>
<label class='col-md-4 control-label'>Quick Select</label>
<div class='col-md-8 selectContainer'>
<div class='input-group'>
<span class='input-group-addon'><i class=''></i></span>
<select name='Customer_ID' class='form-control selectpicker' id='Customer_ID'
onChange="getCustomer(this.value);">
<option value='0'>Please create a new Customer</option>
<?php
$sell_type = "Trade";
$getcustomer = $conn->prepare("SELECT * FROM customers WHERE type = :type");
$getcustomer->bindParam(':type', $sell_type);
$getcustomer->execute();
foreach ($getcustomer->fetchAll(PDO::FETCH_ASSOC) as $row) {
$customer_id = $row['id'];
$customer_name = $row['name'];
$customer_company = $row['company'];
if (!empty($customer_company)) {
$customer = $customer_company;
} else {
$customer = $customer_companyname;
}
echo "<option value='$customer_id'>$customer</option> ";
}
?>
</select>
</div>
</div>
</div>
<div id='address'>
// address results go here
</div>
address:
<div class='form-group row'>
<label class='col-md-4 control-label'>Postcode</label>
<div class='col-md-8 selectContainer'>
<div class='input-group'>
<span class='input-group-addon'><i class=''></i></span>
<select id='address_id' class='form-control selectpicker' name='address_id' >
";
$getaddresses = $conn->prepare("SELECT * FROM addresses WHERE customer_id = :id");
$getaddresses->bindParam(':id', $customer_id);
$getaddresses->execute();
foreach ($getaddresses->fetchAll(PDO::FETCH_ASSOC) as $row) {
$address_id = $row['id'];
$postcode = $row['postcode'];
$areacode = $row['areacode'];
echo "
<option value='$address_id'>$postcode</option>
";
}
echo "
</select>
</div>
</div>
</div>
The form itself is quite large but the header is:
<form class="form-horizontal justify-content-center" action="new.php" method="post" id="form">
and submitted with:
<button type="submit" class="btn btn-primary mb-2">Submit</button>

mysql query not getting values from database on selecting radio buttons

I have searched a long way for the result but still no success on this. I am trying to select radio button and hence showing its result on same page but my query somehow not getting records for the same. It says MySQL "QUERY EMPTY". Please let me know where am I doing wrong. Here is my code for that. A help would be highly appreciated.
PHP
<?php
include 'blocks/headerInc.php' ;
$errmsg = $module_id = $query = $date_from = $date_to = $sql1 = "";
//Search section start here
/*$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 ";
if (isset($_REQUEST['submit'])) {
if (!empty($_REQUEST['date_from'])) {
$date_from = date("Y-m-d", strtotime($_REQUEST['date_from']));
}
if (!empty($_REQUEST['date_to'])) {
$date_to = date("Y-m-d", strtotime($_REQUEST['date_to']));
}
if (!empty($date_to) && empty($date_from)) {
$errmsg = "Please select valid date range.";
}
if (!empty($date_to) && (strtotime($date_from) > strtotime($date_to))) {
$errmsg = "Please select valid date range.";
}
if ($errmsg == '') {
if (!empty($date_to) && (strtotime($date_from) <= strtotime($date_to))) {
$sqlQuery .= " AND created_on BETWEEN '$date_from' AND '$date_to'";
}
$sqlQuery .= " order by id DESC";
}
$date_from = date("m/d/Y", strtotime($date_from));
$date_to = date("m/d/Y", strtotime($date_to));
$date_from = $date_from != '01/01/1970' ? $date_from : '';
$date_to = $date_to != '01/01/1970' ? $date_to : '';*/
if (isset($_POST['users']) && $_POST['users'] == 'approved') {
$sql1 = mysql_query("SELECT * FROM tbl_user WHERE type =3 and status = 1");
//$result = ($sql1);
while ($row = $sql1->fetch_assoc()) {
$users[] = $row;
}
} elseif (isset($_POST['users']) && $_POST['users'] == 'unapproved') {
$sql1 = mysql_query("SELECT * FROM tbl_user WHERE type =3 and status = 0");
//$result = mysql_query($sql1);
while ($row = $sql1->fetch_assoc()) {
$users[] = $row;
}
} elseif (isset($_POST['users']) && $_POST['users'] == 'all') {
$sql1 = mysql_query("SELECT * FROM tbl_user WHERE type =3");
//$result = mysql_query($sql1);
while ($row = $sql1->fetch_assoc()) {
$users[] = $row;
}
}
//}
?>
HTML:
<div class="container pagecontainer">
<!-- Static navbar -->
<div class="row row-offcanvas row-offcanvas-right">
<!--/.col-xs-12.col-sm-9-->
<div class="col-sm-3 col-md-3 sidebar" id="sidebar">
<div id="left_panel" class="clearfix left">
<?php include 'blocks/leftnavInc.php' ; ?>
</div>
</div>
<div class="col-xs-12 col-sm-9 page-right">
<div class="panel panel-primary">
<div class="panel-heading">Search Registered Candidate</div>
<div class="panel-body">
<div class="column col-sm-offset-0">
<?php if($errmsg!="") echo "<div class='error'>".ucwords($errmsg)."</div>"; ?>
<form class="form-horizontal" method="get" action="">
<div class="form-group">
<div class="col-md-6">
<div class="col-md-4">
<label for="username" class="control-label">Date From:</label>
</div>
<div class="col-md-8">
<div class="input-group date">
<input class="form-control datepicker" data-val="true" data-val-date="The field Dob must be a date." data-val-required="The Dob field is required." id="Dob" name="date_from" placeholder="Date From" type="text" value="<?php echo $date_from ; ?>" >
</div>
</div>
</div>
<div class="col-md-6">
<div class="col-md-4">
<label for="username" class="control-label">Date To:</label>
</div>
<div class="col-md-8">
<div class="input-group date">
<input class="form-control datepicker" data-val="true" data-val-date="The field Dob must be a date." data-val-required="The Dob field is required." id="Dob" name="date_to" placeholder="Date To" type="text" value="<?php echo $date_to ; ?>" >
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<div class="col-md-8 text-left">
<button type="submit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Search</button>
<button type="reset" onClick="javascript:window.location.href='reportRegisteredUsers.php'" class="btn btn-danger"><i class="glyphicon glyphicon-ban-circle"></i> Cancel</button>
</div>
</div>
<div class="col-md-6">
<div class="col-md-4">
<label for="username" class="control-label"> </label>
</div>
<div class="col-md-8 text-right">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">Report:Registered Candidate</div>
<div class="panel-body">
<input type="radio" name="users" value="all" checked="checked"> All Candidates<br>
<input type="radio" name="users" value="approved"> Approved Candidates<br>
<input type="radio" name="users" value="unapproved"> Unapproved Candidates<br> </form>
<div class="column col-sm-offset-0">
<table id="example" class="table table-striped table-hover table-bordered dataTableReport dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>S.No.</th>
<th>Email ID</th>
<th>SBI Employee ID</th>
<th>Name</th>
<th>Mobile No.</th>
<th>Date of Birth</th>
<th>Registration Date</th>
</tr>
</thead>
<tbody>
<?php
$sqr = $db->query($sql1);
//print_r($sqr);
//$i = 1 ;
//$sq = $db->query($sqlQuery);
$i = 1 ;
if($db->affected_rows > 0)
{
while($row=mysql_fetch_array($sqr))
{
extract($row);
?>
<tr>
<td><?php echo $i ; ?></td>
<td><?php echo $email ; ?></td>
<td><?php echo $employee_id ; ?></td>
<td><?php echo $first_name." ".$middle_name." ".$last_name ; ?></td>
<td><?php echo $mobile ; ?></td>
<td><?php if($dob !='1970-01-01'){echo date("d-m-Y", strtotime($dob)) ; }?></td>
<td><?php echo date("d-m-Y", strtotime($created_on)) ; ?></td>
</tr>
<?php $i++;}} ?>
</tbody>
</table>
</div>
</div>
</div>
<div>
<button type="reset" onClick="javascript:history.go(-1)" class="btn btn-danger"><i class="glyphicon glyphicon-ban-circle"></i> Go Back</button>
</div>
<!--/row-->
</div>
<!--/.sidebar-offcanvas-->
</div>
</div>
<?php include 'blocks/footerInc.php'; ?>
Does this need to be strictly PHP and MySQL? Can we include some JavaScript/jQuery? While this doesn't answer your question directly, I hope it helps.
For your issue, I would detect the change event of your radio field and fire off a quick jQuery $.post to process the selection.
When your JavaScript sends a POST request to your PHP, you would run your PHP logic and return (or echo) the result. This can then be "digested" by your JavaScript. Here is a simple/rough example using jQuery and PHP. Adapt to your needs:
<script>
// # on ready
$(function() {
// # current document - assumes you'll be submitting to self
var self = document.location.href;
// # when changing the user radios
$('input[type=radio][name=users]').change(function() {
// # grab the value of the radio and create a js array to post
var postData = {'users': $(this).val()};
// # post the postData to your PHP
$.post(self, postData).done(function(data, status, xhr) {
// # assumes you're returning JSON data
data = jQuery.parseJSON(data);
// # add your logic here
console.log('POST Response', data);
// # update an element with the returned data or response:
$('#example').before('<div>'+ data +'</div>');
});
});
});
</script>
Regarding your PHP code, as other users have suggested, you're using mysql_ functions that are no longer supported on modern versions of PHP. You're quickest and dirtiest adjustment, without rewriting everything, is to use mysqli_ functions (notice the additional 'i').
You're already listening for the $_POST['users'] parm, so the only addition I would recommend is to actually use that $users[] array. I could get into re-writing the PHP so it makes sense, but here is a quick adjustment to your existing code:
<?php
$users = array();
if(isset($_POST['users']) && $_POST['users'] == 'approved'){
$query = "SELECT * FROM tbl_user WHERE type = 3 AND status = 1";
} else if(isset($_POST['users']) && $_POST['users'] == 'unapproved') {
$query = "SELECT * FROM tbl_user WHERE type =3 and status = 0";
} else if (isset($_POST['users']) && $_POST['users'] == 'all') {
$query = "SELECT * FROM tbl_user WHERE type =3";
}
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$users[] = $row;
}
// # encode your $row array into JSON and echo for JavaScript
echo json_encode($users);
// # free result set
$result->free();
}
?>
While this isn't a complete solution, I hope it points you in the right direction.
A couple things to note - you'll need to adjust your MySQL connection code if you're to use mysqli_ functions. You'll also need to include jQuery (ideally from CDN) for that JavaScript to work (or you could rewrite it to not use a library like jQuery). This should return the results of your query to your JavaScript. The result should be available as "data" in your js. I've added a console.log so you can view the response in your inspector.
Good Luck!

Different Text area for each row

I am working with PHP and I am able to gather the info of my database table and show it into my webpage.
For each row I am displaying a button which leads to a modal popup with a textarea containing a WYSIWYG ( I used TinyMCE ) so that I can add Details about that specific row.
This works just with 1 row when I am using this script
This is my script:
<?php
include("connection.php");
if ($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');
}
if (isset($_POST['savechanges'])) {
$results = $link->query("UPDATE mytalbename SET details='$_POST[textarea]' WHERE id=44");
}
?>
My problem is: how to extend this concept to all the rows in the way that each row has a button. Each button leads to a modal popup with a text area. From each text area I can modify the column "details" referring to that specific row.
And this is the code of the text area into the Form
<div class="modal-body">
<form action="" method="post" name="savechanges">
<textarea name="textarea"></textarea>
<button type="submit" class="btn btn-primary" name="savechanges"> Save changes</button>
</form>
</div>
Here I display the button:
<a class='btn btn-primary btn-sm get_info2' data-toggle='modal' data-target='#myModal2' name='job_id' value='[$job_id]'>Add Details</a>
<a class='btn btn-primary btn-sm get_info3' data-toggle='modal' data-target='#myModal3' name='job_id' value='[$job_id]'>View Details</a>
I Attach picture:
Table
[Modal popup with textarea][2]
----UPDATE 1 ----
$results = $link->query("UPDATE job SET details='$_POST[textarea]' WHERE id='$_POST[hidden]'" );
and
<div class="modal-body">
<form action="" method="post" name="savechanges">
<textarea name="textarea"></textarea>
<button type="submit" class="btn btn-primary" name="savechanges"> Save changes</button>
<input type="hidden" name="hidden" value=" . $row['id'] . ">
</form>
</div>
-----------Update 2---------------
<?php
include("connection.php");
if ($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');
}
if (isset($_POST['savechanges'])) {
$results = $link->query("UPDATE job SET details='$_POST[textarea]' WHERE id='44'" );
}
?>
----------------UPDATE 3--------------------
<div class="modal-body info_data2">
<form action="" method="post" name="savechanges">
<textarea name="textarea"> </textarea>
<button type="submit" class="btn btn-primary" name="savechanges"> Save changes</button>
<input type="hidden" name="hidden" value="<?php echo $row['id'];?>">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div></div></div></div> </div>
<?php
include("connection.php");
if ($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');
}
if (isset($_POST['savechanges'])) {
$results = $link->query("UPDATE job SET details='".$_POST['textarea']."' WHERE id=".$_POST['hidden']);
}
?>
---------------UPDATE 4 ------------ ALL CODE
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.tinymce.com/4/tinymce.min.js"></script>
<script>tinymce.init({ selector:'textarea' }); tinyMCE.activeEditor.getContent();</script>
</head>
<body>
<!-- ------SCRIPT that fetch data from database and show table-->
<?php
include("connection.php");
if ($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');}
if (isset($_POST['update'])) {
$results = $link->query("UPDATE customer SET status='$_POST[status]' WHERE id='$_POST[hidden]'");
}
$sql = "SELECT * from job";
if (!$result = $link->query($sql)) {
die('There was an error running the query [' . $link->error . ']');}
echo "
<table class='table'>
<thead>
<tr>";
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
echo "
<th>" . $finfo->name . "</th>"; }
echo " </tr>
</thead>
<tbody>";
while ($row = $result->fetch_assoc()) {
$job_id = $row['id'];
echo "<form action='' method=post>";
echo "<tr class='info'>
<input type=hidden name=hidden value=" . $row['id'] . ">
<td>" . $row['id'] . "</td>
<td>" . $row['device'] . "</td>
<td>" . $row['model'] . "</td>
<td>" . $row['problem'] . "</td>
<td>
<select class='form-control col-sm-10' id='status' name='status'>
<option value='new' ". ($row['status'] == 'new'? 'selected ': '') .">New</option>
<option value='progress' ". ($row['status'] == 'progress'? 'selected ': '') .">Progress</option>
<option value='wait' ". ($row['status'] == 'wait'? 'selected ': '') .">Wait</option>
<option value='done' ". ($row['status'] == 'done'? 'selected ': '') .">Done</option>
<option value='close' ". ($row['status'] == 'close'? 'selected ': '') .">Close</option>
</select>
</td>
<td>
<button type='submit' class='btn btn-primary btn-sm' name='update'>Update</button>
</td>
<td>
<a class='btn btn-primary btn-sm get_info' data-toggle='modal' data-target='#myModal' name='job_id' value= '[$job_id]'>Customer Info</a>
<a class='btn btn-primary btn-sm get_info2' data-toggle='modal' data-target='#myModal2' name='job_id' value= '[$job_id]'>Add Details</a>
</td>
</tr>";
echo "</form>"; }
echo "
</tbody>
</table>";
?>
<!-- ------SCRIPT FOR BUTTON "CUSTOMER INFO"-->
<script>
$(document).ready(function(){
$('.get_info').click(function(){
var job_id = $(this).parent().siblings('input[name=hidden]').val();
$.ajax({
url: 'responses.php',
data: 'job_id=' + job_id,
type: 'POST',
success: function(data){
// console.log(data);
$('.info_data').html(data);
}
});
});
});
</script>
<!-- MODAL THAT SHOW UP AFTER CLICKING ON "CUSTOMER INFO"-->
<div class="container">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Customer Information</h4>
</div>
<div class="modal-body info_data">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<!-- ---SCRIPT FOR BUTTON "ADD DETAILS" -->
<script>
$(document).ready(function(){
$('.get_info2').click(function(){
var job_id = $(this).parent().siblings('input[name=hidden]').val();
$.ajax({
url: 'responses2.php',
data: 'job_id=' + job_id,
type: 'POST',
success: function(data){
// console.log(data);
$('.info_data2').html(data);
}
});
});
});
</script>
<!-- MODAL THAT SHOW UP AFTER CLICKING BUTTON "ADD DETAILS"
which allow you to send data to database through the text area -->
<div class="container">
<div class="modal fade" id="myModal2" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Job Details</h4>
</div>
<div class="modal-body info_data2">
<form action="" method="post" name="savechanges">
<textarea name="textarea"> </textarea>
<button type="submit" class="btn btn-primary" name="savechanges"> Save changes</button>
<input type="hidden" name="hidden" value="<?php echo $row['id'];?>">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<!-- SCRIPT THAT SHOULD be able to send what is written in the text area to the database,-->
<?php
include("connection.php");
if ($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');
}
if (isset($_POST['savechanges'])) {
$results = $link->query("UPDATE job SET details='".$_POST['textarea']."' WHERE id=".$_POST['hidden']);
}
?>
</body>
</html>
--------------------UPDATE 5 ------------------
SECTION 1
PHP code that fetch data from the table JOB
and show for each row 3 button:
update button for updating the status and the priority
customer info button (fetch data from table "customer")
add details button (send information with through a modal pop up with a wusiwug to the column "details of the table JOB")
view details button: fetch data from the column "details of the table JOB"
SECTION 2:
SCRIPT FOR BUTTON "CUSTOMER INFO"
SECTION 3:
MODAL THAT SHOW UP AFTER CLICKING ON "CUSTOMER INFO"
SECTION 3:
SCRIPT FOR BUTTON "ADD DETAILS"
SECTION 4:
MODAL THAT SHOW UP AFTER CLICKING BUTTON "ADD DETAILS"
which allow you to send data to database through the text area
SECTION 5:
SCRIPT THAT SHOULD be able to send what is written in the text area to the database
OVERVIEW
OK, if everything is working and you just need change it to work for any record, you just need to change 44 in your php code with $_POST['hidden']
So your html and php would be something like this:
HTML
<div class="modal-body">
<form action="" method="post" name="savechanges">
<textarea name="textarea"></textarea>
<button type="submit" class="btn btn-primary" name="savechanges"> Save changes</button>
<input type="hidden" name="hidden" value="<?php echo $row['id'];?>">
</form>
</div>
PHP
<?php
include("connection.php");
if ($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');
}
if (isset($_POST['savechanges'])) {
$results = $link->query("UPDATE job SET details='".$_POST['textarea']."' WHERE id=".$_POST['hidden']);
}
?>
But I do encourage you to practice mysqli parameterized query and not using variables directly inside your queries...
UPDATE
Since your code is really hard to understand, I will just update my answer to add some assumptions, just in case they are right!
I do not know how you are showing <div> with the title of <h4 class="modal-title">Add Job Details</h4>. So let's assume that $('.info_data2').html(data); is doing what you want to do!
So in your JavaScript you have:
<script>
$(document).ready(function(){
$('.get_info2').click(function(){
var job_id = $(this).parent().siblings('input[name=hidden]').val();
$.ajax({
url: 'responses2.php',
data: 'job_id=' + job_id,
type: 'POST',
success: function(data){
// console.log(data);
$('.info_data2').html(data);
}
});
});
});
</script>
Here you are just passing job_id as the parameter, so in the responses2.php you have two issues:
1- you have to change $_POST['hidden'] to $_POST['job_id']
2- you do not have any parameter for the textarea!
Then you have to change your JavaScript to something like this:
<script>
$(document).ready(function(){
$('.get_info2').click(function(){
var job_id = $(this).parent().siblings('input[name=hidden]').val();
var textarea = $(this).parent().siblings('[name=textarea]').val();
$.ajax({
url: 'responses2.php',
data: { "job_id": job_id, "textarea" : textarea} ,
type: 'POST',
success: function(data){
// console.log(data);
$('.info_data2').html(data);
}
});
});
});
</script>
Remember, since your HTML code is really confusing, you have to work on how to get correct value of job_id and textarea. with this code I'm sure these are not returning correct values. it's just a sample of how you do what you want to do and just to put you on a correct Track!!!
as you can see, I have have added this line: var textarea = $(this).parent().siblings('name=textarea').val(); and also changed the data line to this: data: { "job_id": job_id, "textarea" : textarea} , to be able to send the textarea value to the responses2.php file...
Then in responses2.php you have to change it like this:
<?php
include("connection.php");
if ($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');
}
if (isset($_POST['savechanges'])) {
$results = $link->query("UPDATE job SET details='".$_POST['textarea']."' WHERE id=".$_POST['job_id']);
}
?>

Categories