how to save multiple ckeditor in php? - javascript

I have create a multiple ckeditor in php, it can display the panel of ckeditor correctly, but when I click update after adding something in it, it didn't save to the database.
<?php
if(isset($_POST["action"])&&($_POST["action"]=="update")){
$id = $_POST['id'];
$content = $_POST['content'];
$query_update = "UPDATE `correspond` SET content='$content' WHERE id='$id'";
mysql_query($query_update);
header("Location: correspond.php");
}
?>
<table>
<?php while($row_correspond_result=mysql_fetch_assoc($correspond_result)){ ?>
<tr class="table table-bordered table-striped"><form action="" method="POST" name="correspond_form" id="correspond_formJoin">
<tbody id="myTable">
<td colspan="3" align="center"><div contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?> </div>
<script>
var elements = document.getElementsByClassName( 'myContent' );
for ( var i = 0; i < elements.length; ++i ) {
CKEDITOR.inline( elements[ i ], { /* config for this instance */ } );
}});
</script>
</td>
</tr><tr>
<td colspan="2"></td>
<td align="center">
<input name="action" type="hidden" id="action" value="update">
<input type="submit" name="Submit" value="Update"></td>
</form></tr><?php }?> </tbody></table>

To save multiple ckeditor, you have need to pass the name attribute in array format. when you click on submit save the content value using the serialize function.
PHP code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["action"])&&($_POST["action"]=="update")){
$content = $id = '';
$form_data = $_POST['form_data'];
for($i=0 ; $i<count($form_data['id']); $i++){
$content = serialize($form_data['content'][$i]);
$id = $form_data['id'][$i];
$query_update = "UPDATE correspond SET content='$content' WHERE id= $id";
mysqli_query($conn, $query_update);
}
//header("Location: correspond.php");
}
?>
At the time of display unserialize content value and put in textarea field.
HTML Code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.11.4/standard/ckeditor.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var elements = document.getElementsByClassName( 'myContent' );
for ( var i = 0; i < elements.length; ++i ) {
CKEDITOR.replace( elements[ i ]);
//CKEDITOR.inline( elements[ i ], { /* config for this instance */ } );
}
});
</script>
<table>
<tr class="table table-bordered table-striped">
<form action="" method="POST" name="correspond_form" id="correspond_formJoin">
<tbody id="myTable">
<td colspan="3" align="center">
<?php
$sql = "SELECT id, content FROM correspond";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//get the content form database and use unserialize method
$content = unserialize($row["content"]);
?>
<!-- Change div to textarea and use the name attr as array format -->
<textarea contenteditable="true" class="myContent" name="form_data[content][]" id="content"><?php echo $content;?> </textarea>
<!-- add the corresponding id to update the content. -->
<input type="hidden" name = "form_data[id][]" value ="<?php echo $row["id"];?> ">
<?php
}
}
?>
</td>
</tr><tr>
<td colspan="2"></td>
<td align="center">
<input name="action" type="hidden" id="action" value="update">
<input type="submit" name="Submit" value="Update"></td>
</form></tr></tbody></table>

This div Converted to TextArea
From
<div contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?> </div>
To
<textarea contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?> </textarea>

Related

How do I create a delete button where I can delete the list at the side of my database?

enter image description here
How do I create a delete button where I can delete the list at the side of my database?
I'm trying to get the 'x' or delete button as shown in the picture
This is my current code:
<html>
<head>
<link rel="stylesheet" href="css/booklist.css">
<title>Search data by its ID</title>
<script type="text/javascript">
function out() {
alert("Checkout Items Successful!");
}
</script>
</head>
<div class="background">
<h1>Library Checkout System</h1>
<h2>Loan/Request Your Books Here</h2>
<form action="" method="POST">
<input type="text" name="id" placeholder="Please enter Book ID" />
<input type="submit" name="search" value="Search By ID" />
</form>
<table border="2" id="newton">
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Returned Date</th>
</tr><br><br>
<?php
$connection = mysqli_connect("localhost","root", "");
$db = mysqli_select_db($connection,"myfirstdb");
session_start();
if (!isset($_SESSION['id'])) {
$_SESSION['id'] = array();
}
if(isset($_POST['search']))
{
$id = $_POST['id'];
array_push($_SESSION['id'],$id); //Here we have declared a session array. We can add elements to it by array_push function.//
$_SESSION['id'] = array_unique($_SESSION['id']); //array_unique: Removes duplicate values from an array
$id = implode(',',$_SESSION['id']); //implode : returns a strings from the elements of an array.//
// instead of changing the database of each row, the implode() function adds the rows according to the selected id entered.//
// this function is the key for solving my original problem.//
$query = "SELECT * FROM `table3` where id in ($id)";
$query_run = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($query_run))
{
?>
<tr>
<td>
<?php echo $row ['product_name']; ?> </td>
<td>
<?php echo $row ['quantity']; ?> </td>
<td>
<?php echo $row ['returned_date']; ?> </td>
</tr>
<?php
}
}
?>
</table>
<br>
<input type="submit" name="send" value="Confirm Booklist" onclick="out()" />
</form>
</div>
</body>
</html>
How do I create a delete button where I can delete the list at the side of my database?
I'm trying to get the 'x' or delete button as shown in the picture

passing value to hidden input value before submit

I am trying to run a form that stores an Id in a hidden input tag so that I can retrieve it in the next page using php. For some reason I can't retrieve the value using the php file. Echoing orderId.value and order number are working fine.
main_page.php
<script>
function EditValues(orderNumber) {
var orderId = document.getElementById("orderId");
orderId.value = orderNumber;
document.forms["form1"].submit();
}
</script>
<body>
<form action="edit-form.php" id="form1">
<div class="container">
<!--use the hidden input variable to save the order number clicked -->
<input id="orderId" type="hidden" name="orderId"/>
<?php
require("config.php");
$con = new mysqli(DB_Host, DB_User, DB_Password, DB_Name);
if ($con->connect_error) {
die("Connection failed");
}
echo '<table id="tblOrders" name ="OrderTable" style="width: 100%">
<tr>
<th>Sno</th>
<th>Order Number</th>
</tr>';
$displayTableDataQuery = "SELECT id, orderNumber, customerName, deliveryDate FROM orderTable";
if ($tableData = $con-> query($displayTableDataQuery)) {
while($row = $tableData-> fetch_assoc()) {
$id = $row['id'];
$orderNumber = $row["orderNumber"];
echo '<tr >
<td>'.$id.'</td>
<td id = "orderNumber">'.$orderNumber.'</td>
<td><input type = "button" id ="editButton'.$id.'" value = "Edit" onclick = "EditValues('.$orderNumber.');"/> </td>
<td><input type = "button" id = "printInvoice'.$id.'" value="Print" onclick = "PrintInvoice('.$orderNumber.');" /> </td>
</tr>';
}
} else {
echo $con->error;
}
$tableData->free();
?>
</div>
</form>
</body>
In edit-form.php
<?php
$xyzabc = $_POST['orderId'];
echo $xyzabc;
?>
There is nothing echoed for $xyzabc
I would prefer if there was some way to do this without jQuery as I'm kind of new to this and haven't really gotten a hang of how everything works together as of now.
You can store value directly to the hidden input field.
<!--use the hidden input variable to save the order number clicked -->
<input id="orderId" type="hidden" name="orderId" value="<?=$variable_name;?> />
So that when you submit the form
<?php
$xyzabc = $_POST['orderId'];
echo $xyzabc;
?>
will fetch the data.
Or you can pass the hidden value in url. For example
<a href="localhost:8000/edit-form.php?orderId="<?=$variable_name;?>
Then in you form-edit.php
<?php
$xyzabc = $_GET['orderId'];
echo $xyzabc;
?>

Show/hide info using slideToggle on button

Objective Inserting name(input-text) and info(textarea-contains multiple lines) into the database, and after submission of the form, at the same page, 2 columns are for displaying the same data in columns, name & info, but under info column. I have made buttons for each row in front of the names, which is used as slideToggle for showing/hiding which contains the data retrieved from the 'info' column
Problem - when I am clicking the button of 1st row, instead of displaying the info related to 1st entry only, it is sliding and showing all info(s) related to all entries at only click.
*others - one more input has been added to the form but as hidden used for id(auto increment)
----index.php-----
<?php include('php_code.php'); ?>
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM records WHERE id=$id");
if (count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$name = $n['name'];
$acc = $n['acc_no'];
$info = $n['info'];
}
}
?>
<html>
<head>
<title>JSK</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('form').hide();
$('p').hide();
$('#sp').hide();
$("#inf").click(function(){
$("p").slideToggle();
$('#sp').slideToggle();
});
$("#fo").click(function(){
$("form").slideToggle();
});
});
</script>
</head>
<body>
<div class="container">
<div class="left">
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
<?php $results = mysqli_query($db, "SELECT * FROM records"); ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Account No</th>
<th>Info</th>
<th colspan="2">Action</th>
</tr>
</thead>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['acc_no']; ?></td>
<td><button id="inf" onclick="myFunction()">show</button></td>
<td>
<a href="index.php?edit=<?php echo $row['id']; ?>" class="edit_btn" >Edit</a>
</td>
<td>
Delete
</td>
</tr>
<tr id="sp"> <td colspan="4"><p> <?php echo $row['info']; ?> </p></td>
</tr>
<?php } ?>
</table>
<div id="fotable" align="center">
<button id="fo">Add New/Edit</button>
</div>
<form method="post" action="php_code.php" >
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>Name</label>
<input type="text" autocomplete="off" name="name" value="<?php echo $name; ?>">
</div>
<div class="input-group">
<label>Account No</label>
<input type="text" name="acc" value="<?php echo $acc; ?>">
</div>
<div class="input-group">
<label for="info">Info</label>
<textarea class="form-control" rows="8" name="info" id="info"><?php echo $row['info']; ?></textarea>
</div>
<div class="input-group">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Add Account</button>
<?php endif ?>
</div>
</form>
</div><!-- left closed -->
<div class="right">
hello
</div> <!-- right closed -->
</div> <!-- container closed -->
</body>
</html>
---php_code.php-----
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'jskrecords');
// initialize variables
$name = "";
$acc = "";
$info = "";
$id = 0;
$update = false;
if (isset($_POST['save'])) {
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "INSERT INTO records (name, acc_no, info) VALUES ('$name', '$acc', '$info')");
$_SESSION['message'] = "Account saved";
header('location: index.php');
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "UPDATE records SET name='$name',acc_no='$acc',info='$info' WHERE id=$id");
$_SESSION['message'] = "Account updated!";
header('location: index.php');
}
if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM records WHERE id=$id");
$_SESSION['message'] = "ACC deleted!";
header('location: index.php');
}
?>
Concept:
If you are creating multiple form from same mysql table using php script, You need to give each form a unique id.
e.g.
<form method="post" action="php_code.php" id="form<?= $id ?>">
Then add data-target="#form" to button with class 'inf'. It will store id of form.
<button class="inf" data-target="#form<?= $id ?>">show</button>
When button is clicked we know which form to open from data-target.
<script>
$('.container').on('click','button.inf',function(e){
e.preventDefault();
var formid=$(this).attr('data-target'); //get value of data-target attribute
//...proceed to play toggle with this form 'formid'

Creating Dynamic Rows with Dropdown (from mysql DB) that populates textbox inside rows via Ajax Jquery

In the above image i am creating dynamic rows (which is working just fine). However, I have then included the ability to populate the "Desc:" textbox based on what is selected in the dropdown to the left of "Desc:". This works just fine for the first row but not for any other row after that.
Here is my javascript code for the add and remove rows (working well):
<script type="text/javascript">
$(function(){
function initTemplates() {
$('.template').each(function () {
var template = $(this).children(),
key = template.attr('class') || 'template' + templates.length;
templates[key] = template;
$(this).remove();
});
}
var templates = {};
initTemplates();
//when the Add Field button is clicked
$("#add").click(function () {
$('#items').append(templates['emp_detail'].clone());
});
//function on Delete button
$(document).on('click', '.delete', function () {
$(this).parent().remove();
});
});
</script>
Here is the code (php and HTML) for pulling data from mySQL DB and populating the dropdown:
<div class="template">
<div class="emp_detail">
<script type="text/javascript">
$(document).ready(function(){
$("#sel_depart").change(function(){
var deptid = $(this).val();
$.ajax({
url: 'getUsers.php',
type: 'post',
data: {depart:deptid},
dataType: 'json',
success:function(response){
var len = response.length;
$("#sel_user").empty();
for( var i = 0; i<len; i++){
var PartNumber = response[i]['PartNumber'];
$("#sel_user").empty().append("<input type=text value='"+PartNumber+"' size=20 name=PartNumber[]>");
}
}
});
});
});
</script>
<span width=100%>
<table border="0" cellpadding=0 cellspacing=0 width="100%">
<tr>
<td style='white-space:nowrap;'>
<input type="button" class="delete" value="Delete">
<label><font style="font-size:11px;"><b>Part: </b></label><input type="text" class="small" name="BX_ProductName[]" size="20">
<label><font style="font-size:11px;color:#D41118;"><b>OR </font></label>
<select name="Prod1[]" id="sel_depart">
<option>Select Pre-Loaded Part...</option>
$sql = "SELECT DISTINCT ProductName, id FROM table_name GROUP BY ProductName ORDER BY ProductName ASC";
$sql_result = mysql_query($sql,$connection);
while ($row = mysql_fetch_array($sql_result))
{
$id = $row['id'];
$ProductName = $row['ProductName'];
echo"<option value=\"$id\">$ProductName</option>";
}
mysql_close($connection);
?>
<label for="PartNumber"><font style="font-size:11px;"><b>Desc: </b></label><span id="sel_user"><input type="text" class="small" name="PartNumber[]" size="20"></span>
<label for="AmountOrdered"><font style="font-size:11px;"><b>Qty: </b></label><input type="text" required="required" class="small" name="AmountOrdered[]" size="5">
<label for="build"><font style="font-size:11px;"><b>Build#: </b></label><input type="text" required="required" class="small" name="build[]" size="10">
<label for="unit_cost"><font style="font-size:11px;"><b>Unit$: </b></label><input type="text" class="small" name="unit_cost[]" size="10">
<label for="total_cost"><font style="font-size:11px;"><b>Total$: </b></label><input type="text" class="small" name="total_cost[]" size="10">
<label><font style="font-size:11px;"><b>Date: </b></label><input type="text" class="emp_from" name="ExpectedDate[]" size="10">
</td>
</tr>
</table>
</span>
</div>
</div>
<div id="items">
</div>
Here is the getUsers.php file:
$host = "localhost"; /* Host name */
$user = "username"; /* User */
$password = "password"; /* Password */
$dbname = "db_name"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$departid = $_POST['depart'];
$sql = "SELECT id, PartNumber FROM table_name WHERE id = ".$departid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ) {
$PartNumber = $row['PartNumber'];
$userid = $row['id'];
$users_arr[] = array("PartNumber" => $PartNumber);
}
// encoding array to json format
echo json_encode($users_arr);

Trying to search table in PHP

I am trying to create a search within my table.
I have the table populated with date already loaded, but when i type into the search box for example a name and press submit, nothing is happening the page just reloads and nothing happens.
Here is the code, (i also need to do the same with a table where the table data is all foreign keys.)
<?php // Include config file
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/config.php");
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/functions.php");
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/header.php");
$sql = "SELECT * FROM patient";
if (isset($_POST['searchform'])) {
$search_term = ($_POST['searchpat']);
$sql .= " WHERE fName LIKE '{$search_term}'";
$sql .= " OR sName LIKE '{$search_term}'";
$sql .= " OR addLineOne LIKE '{$search_term}'";
}
$query = mysqli_query($db, $sql) or die(mysql_error());
?>
<body>
<div class="container">
<?php include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/logo.html"); ?>
<h2>List of Patients</h2>
<p>All Patients Registered with Freddies Medical:</p>
<form name="searchform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Search for Patient</label>
<input type="text" class="form-control" name="searchpat" required><br>
<input type="submit" class="btn btn-primary" name="search" value="Submit">
<span class="help-block"></span>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>First Name</th>
<th>Surname</th>
<th>Address</th>
<th>Phone</th>
<th>Email Address</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td>'.$row['fName'].'</td>
<td>'.$row['sName'].'</td>
<td>'.$row['addLineOne'].", ".$row['addCity'].", ".$row['addPostCode'].'</td>
<td>'.$row['phone'].'</td>
<td>'.$row['email'].'</td>
<td>View Patient</td>
<td>Delete</td>
</tr>';
$no++;
}?>
</tbody>
</table>
New Patient
Admin Area
</div>
<div class="bottompadding"></div>
<?php include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/footer.php"); ?>
</body>
</html>
$_POST['searchform'] will not be set as far as I know since it is the name of the form and not a form element. Better check for isset($_POST['search']):
if(isset($_POST['search'])) {
$search_term = $_POST['searchpat'];
$sql .= " WHERE fName LIKE '%".$search_term."%'"; // Using % wildcard will search for fields 'containing' searched string rather then 'exact matches'
$sql .= " OR sName LIKE '%".$search_term."%'";
$sql .= " OR addLineOne LIKE '%".$search_term."%'";
}

Categories

Resources