PHP- Как добавить значения ячеек таблицы HTML в базу данных MYSQL - PullRequest
0 голосов
/ 28 октября 2019

Во-первых, у меня есть пустая таблица (во-первых, она содержит только заголовки таблиц) и 4 поля ввода. Если кто-то заполнит эти 4 поля ввода и нажмите Add medicine Кнопка;значения этих 4 полей ввода идут в качестве первой строки таблицы. если это будет сделано снова, вторая строка таблицы будет заполнена. Эта таблица содержит 5-й столбец, в котором есть кнопка для удаления соответствующей строки. Я хочу сказать, что эти две кнопки работают отлично. Что я действительно хочу, так это если кто-то заканчивает добавление строки;все значения строк должны поступать в базу данных в виде строк. пожалуйста, помогите мне сделать это.

add_prescrition.php

<form method="POST" >
<div class="row">
    <div class="col-md-4">
        <label for="fullName">Appointment Number</label>
        <div class="form-group">
            <div class="form-line">
                <input type="text" name="appNumber" id="appNumber" class="form-control" placeholder="Appointment Number" required="">
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <label for="nic">Patient's Name</label>
        <div class="form-group">
            <div class="form-line">
                <input type="text" name="pName" id="pName" class="form-control" placeholder="Patinet's Name">
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <label for="nic">Patient's Age</label>
        <div class="form-group">
            <div class="form-line">
                <input type="text" name="pAge" id="pAge" class="form-control" placeholder="Patient's Age">
            </div>
        </div>
    </div>
</div>

<div class="form-group">
    <!-- Multiple CKEditor -->
    <label for="nic">Present Complaint</label>
        <textarea name="pc" class="ckeditor"></textarea>
        <script type="text/javascript">
            CKEDITOR.replace( 'editor1' );
            CKEDITOR.add            
        </script>
        <br><br>
    <label for="nic">Examination</label>
    <textarea name="examination" class="ckeditor"></textarea>
        <script type="text/javascript">
            CKEDITOR.replace( 'editor2' );
            CKEDITOR.add            
        </script>
</div>

<label for="Treatment"><h4>Treatment</h4></label>

<div class="row">
    <div class="col-md-3">
        <label for="doctorName">Drug Name</label>
            <select id="drugId" class="form-control show-tick" data-live-search="true" name="drugId" id="doctorId">
                <option value="0"> Select Drug</option>
                 <?php $ret=mysqli_query($con,"select * from doctors");
                while($row=mysqli_fetch_array($ret))
                {
                ?>
                <option value="<?php echo htmlentities($row['id']);?>">
                    <?php echo htmlentities($row['doctorName']);?>
                </option>
            <?php } ?>
            </select>
    </div>
    <div class="col-md-3">
        <label for="nic">Dose</label>
        <div class="form-group">
            <div class="form-line">
                 <input type="text" name="dose" id="dose" class="form-control" placeholder="Eg: 1+0+1  2+0+2">
            </div>
        </div>
    </div> 
     <div class="col-md-3">
        <label for="nic">Days</label>
        <div class="form-group">
            <div class="form-line">
                 <input type="text" name="days" id="days" class="form-control" placeholder="Eg: 1, 2, 5">
            </div>
        </div>
    </div>  
    <div class="col-md-3">
        <label for="nic">External Medicine</label>
        <div class="form-group">
            <div class="form-line">
                <textarea rows="1" class="form-control no-resize auto-growth" placeholder="External Medicine" id="eMedicine"></textarea>
        </div>
        </div>
    </div>        
</div>
<input type="button" class="btn btn-success m-t-10 waves-effect" onclick="addRow();" value="Add Medicine">
<div class="body">
    <div class="table-responsive">
        <table class="table table-bordered table-striped table-hover dataTable js-exportable" name="drugTable" id="drugTable">
            <thead>
                <tr>
                    <th>Drug Name</th>
                    <th>Dose</th>
                    <th>Days</th>
                    <th>External Medicine</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                </tr>
            </tbody>
        </table>
    </div>
</div>
<label for = 'docfee'>Doctor Fee</label>
<div class="form-group">
    <div class="form-line">
        <input type="text" name="docFee" id="docFee" class="form-control">
    </div>
</div>

<br><br><br><br>
<button class="btn btn-primary m-t-10 waves-effect" type="submit" name="submit">ADD PRESCRIPTION</button></form>

<script> 

    function deleteRow()
    {
        $('table').on('click', 'input[type="button"]', function(e){
           $(this).closest('tr').remove()
            })
    }

        function addRow()
        {
            // get input values
            var drugName = document.getElementById('drugId').value;
            var dose = document.getElementById('dose').value;
            var days = document.getElementById('days').value;
            var eMedicine = document.getElementById('eMedicine').value;
            var action = "<input type='button' class='btn btn-danger m-t-4 waves-effect' id='del' name='del' onclick='deleteRow()' value='DELETE'>";

              // get the html table
              // 0 = the first table
              var table = document.getElementsByTagName('table')[0];

              // add new empty row to the table
              // 0 = in the top 
              // table.rows.length = the end
              // table.rows.length/2+1 = the center
              var newRow = table.insertRow(table.rows.length);

              // add cells to the row
              var cel1 = newRow.insertCell(0);
              var cel2 = newRow.insertCell(1);
              var cel3 = newRow.insertCell(2);
              var cel4 = newRow.insertCell(3);
              var cel5 = newRow.insertCell(4);

              // add values to the cells
              cel1.innerHTML = drugName;
              cel2.innerHTML = dose;
              cel3.innerHTML = days;
              cel4.innerHTML = eMedicine;
              cel5.innerHTML = action;

              document.getElementById("drugId").value = "0";
              document.getElementById("dose").value = "";
              document.getElementById("days").value = "";
              document.getElementById("eMedicine").value = "";
        }

</script>

1 Ответ

1 голос
/ 28 октября 2019

Может быть, вы можете использовать мой пример, я сосредоточен на таблице, а другой вы можете добавить какой-либо ввод или другой, его сделать с чистым JavaScript.

Надеюсь, может помочь вам.

На первом изображении, это инвентарь для вашей аптеки, под изображением store front dashboard

вы можете добавить и удалить строку, вы не можете обновить тему, потому что это может тратить больше временипросто удалите их, если ошиблись.

После этого вы можете сохранить лекарство в базе данных, я предлагаю вам использовать PDO.

Почему? потому что это больше сохранить (я думаю ^ _ ^,), а также поддерживать несколько запросов тоже. см. на этой ссылке

После того, как вы уверены в транзакции, вы можете сохранить ее, и она будет перенаправлена ​​на medicSave.php => мой пример. Смотрите изображение ниже для второй части. enter image description here

Хорошо, на картинке выше, я просто отображаю результат в формате JSON. Вы можете сохранить данные JSON в базе данных сразу после этого, конечно, с помощью QUERY ^ _ ^.

О, если вам нужен код, см. ниже index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="../../foundlose/vendor/meotip/style.css">
</head>
<body>
<div class="container">
    <h1>List Of Medicine</h1>
    <form method="post" action="medicSave.php">
        <div class="indef">
            <table>
                <thead>
                    <tr>
                        <th>Drug Name</th>
                        <th>Dose</th>
                        <th>Days</th>
                        <th>External Medicine</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="dataset"></tbody>
            </table>
        </div>
        <div class="indef">
            <input type="hidden" name="totalRow" id="totalRow" value="0">
            <button type="submit" class="btn btn-process">Save Medicine</button>
        </div>
    </form>
    <hr>
    <div class="indef">
        <label for="drugName"><span>Drug Name :</span>
            <input type="text" id="drugName" placeholder="Insert Drug Name">
        </label>
    </div>
    <div class="indef">
        <label for="dose"><span>Dose :</span>
            <input type="text" id="dose" placeholder="Insert Dose">
        </label>
    </div>
    <div class="indef">
        <label for="days"><span>Days :</span>
            <input type="text" id="days" placeholder="Insert Days">
        </label>
    </div>
    <div class="indef">
        <label for="externalMedicine"><span>External Medicine :</span>
            <input type="text" id="externalMedicine" placeholder="Insert External Medicine">
        </label>
    </div>
    <div class="indef">
        <button id="add" class="btn btn-info">Add medicine list</button>
    </div>
</div>
<script type="text/javascript">

    var dataset = document.getElementById('dataset'),
    drugName = document.getElementById('drugName'),
    dose = document.getElementById('dose'),
    days = document.getElementById('days'),
    externalMedicine = document.getElementById('externalMedicine'),
    add = document.getElementById('add'),
    totalRow = document.getElementById('totalRow');

    add.onclick = function(){

        var getRow = dataset.getElementsByTagName('tr').length,
        trDataset = document.createElement('tr'),
        tdDrugName = document.createElement('td'),
        tdDose = document.createElement('td'),
        tdDays = document.createElement('td'),
        tdExternalMedicine = document.createElement('td'),
        inDrugName = document.createElement('input'),
        inDose = document.createElement('input'),
        inDays = document.createElement('input'),
        inExternalMedicine = document.createElement('input'),
        tdAction = document.createElement('td');

        /* Initiate Column Drugname Section */

        inDrugName.setAttribute('type','hidden');

        inDrugName.setAttribute('id','drugname_' + getRow);

        inDrugName.value = drugName.value;

        inDrugName.name = 'drugname_' + getRow;

        tdDrugName.textContent = drugName.value;

        tdDrugName.appendChild(inDrugName);

        /* End Column Drugname Section */

        /* Initiate Column Dose Section*/

        inDose.setAttribute('type','hidden');

        inDose.setAttribute('id','dose_' + getRow);

        inDose.value = dose.value;

        inDose.name = 'dose_' + getRow;

        tdDose.textContent = dose.value;

        tdDose.appendChild(inDose);

        /* End Column Dose Section */

        /* Initiate Column Days Section*/

        inDays.setAttribute('type','hidden');

        inDays.setAttribute('id','days_' + getRow);

        inDays.value = days.value;

        inDays.name = 'days_' + getRow;

        tdDays.textContent = days.value;

        tdDays.appendChild(inDays);

        /* End Column Days Section */

        /* Initiate Column External Medicine Section*/

        inExternalMedicine.setAttribute('type','hidden');

        inExternalMedicine.setAttribute('id','external_medicine_' + getRow);

        inExternalMedicine.value = externalMedicine.value;

        inExternalMedicine.name = 'external_medicine_' + getRow;

        tdExternalMedicine.textContent = externalMedicine.value;

        tdExternalMedicine.appendChild(inExternalMedicine);

        /* End Column External Medicine Section */

        /* Action */

        tdAction.textContent = 'Click At Row';

        /* End Action*/

        /* Initiate Each Row */

        trDataset.appendChild(tdDrugName);

        trDataset.appendChild(tdDose);

        trDataset.appendChild(tdDays);

        trDataset.appendChild(tdExternalMedicine);

        trDataset.appendChild(tdAction);

        /* Trigger To Select */

        trDataset.onclick = (function(){

            return function(){

                drugName.value = this.childNodes[0].getElementsByTagName('input')[0].value;

                dose.value = this.childNodes[1].getElementsByTagName('input')[0].value;

                days.value = this.childNodes[2].getElementsByTagName('input')[0].value;

                externalMedicine.value = this.childNodes[3].getElementsByTagName('input')[0].value;

                this.parentNode.removeChild(this);

                totalRow.value = dataset.getElementsByTagName('tr').length;

                drugName.focus();

            }

        }());

        /* Add Row To Dataset / Table */

        dataset.appendChild(trDataset);

        getRow++;

        /*Set Total Row, This Use for looping in medicSave.php*/

        totalRow.value = getRow;

        /* Reset Value Input*/

        drugName.value = '';

        dose.value = '';

        days.value = '';

        externalMedicine.value = '';

        drugName.focus();

    }

</script>
</body>
</html>

medicSave.php

<?php
//for this your can store this data to your table ^_^
header('Content-Type: application/json');
echo json_encode($_POST,JSON_PRETTY_PRINT);

?>

или запустить по фрагменту

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<link href="https://fonts.googleapis.com/css?family=Inconsolata&display=swap" rel="stylesheet">
<style type="text/css">
*{
	margin: 0;padding: 0;
	-webkit-box-sizing: border-box;
	-moz-box-sizing: border-box;
	-o-box-sizing: border-box;
	box-sizing: border-box;
	font-size: 13px;
	font-weight: normal;
	background-color: transparent;
	color: #000000;
	border: none;
	outline: none;
	font-family: "Inconsolata";
}
html, body{
	position: relative;
	width: 100%;
	height: 100%;
}
body{
	overflow-x: hidden;
	background-color: #FAFAFA;
}
h1{
	font-size: 32px;
	line-height: 40px;
}
h2{
	font-size: 30px;
	line-height: 38px;
}
h3{
	font-size: 28px;
	line-height: 36px;
}
h4{
	font-size: 26px;
	line-height: 34px;
}
h5{
	font-size: 24px;
	line-height: 32px;
}
h6{
	font-size: 22px;
	line-height: 30px;
}
p, span{
	display: inline;
	letter-spacing: 1px;
	word-spacing: 2px;
	text-align: justify;
	font-size: 16px;
	line-height: 24px;
}
strong{
	font-size: 16px;
	line-height: 24px;
	font-weight: bold;
}
hr{
	border-left: none;
	border-right: none;
	border-top: none;
	border-bottom: 1px solid #888888;
	margin: 10px 0;
}
br{
	clear: both;
}
button{
	padding: 5px 10px;
	background-color: #FAFAFA;
	border: 1px solid #888888;
	cursor: pointer;
	display: inline;
	font-size: 16px;
}
button.btn{
	color: #FAFAFA;
	border-color: transparent;
}
button.btn-none{
	background-color: #888888;
}
button.btn-danger{
	background-color: #F3192A;
}
button.btn-warning{
	background-color: #FB7C19;
}
button.btn-info{
	background-color: #1953F3;
}
button.btn-process{
	background-color: #2CA62B;
}
button.btn-help{
	background-color: #671E72;
}
a{
	font-size: 16px;
	text-decoration: none;
	color: #1953F3;
	cursor: pointer;
}
a.btn{
	padding: 3px 10px;
	border:1px solid transparent;
	color: #FAFAFA;
	display: inline-block;
	border-radius: 10px;
}
a.btn-none{
	background-color: #888888;
}
a.btn-danger{
	background-color: #F3192A;
}
a.btn-warning{
	background-color: #FB7C19;
}
a.btn-info{
	background-color: #1953F3;
}
a.btn-process{
	background-color: #2CA62B;
}
a.btn-help{
	background-color: #671E72;
}
pre, code{
	padding: 10px;
	overflow: auto;
}
pre.code, code.code{
	border:1px solid #888888;
	background-color: #000000;
	color: #28C340;
	font-size: 16px;
	line-height: 20px;
	max-height: 375px;
	height: auto;
	font-family: "Source Code Pro";
	tab-size:2;
}
table{
	border:1px solid #888888;
	width: 100%;
	border-collapse: collapse;
}
tr, td, th{
	border:1px solid #888888;
	padding: 5px 10px;
	font-size: 16px;
	cursor: pointer;
}
tr:hover{
	background-color: #000000;
}
tr:hover td, tr:hover th{
	color: #FAFAFA;
}
tr:nth-child(even){
	background-color: #DDDDDD;
}
tr:nth-child(even):hover{
	background-color: #000000;
}
th{
	text-align: center;
	font-weight: bold;
}
/**/
.container{
	max-width: 800px;
	width: 100%;
	padding: 0 10px;
	display: block;
	margin: auto auto;
}
.indef{
	padding: 5px 0;
}
.indef label{
	display: block;
	cursor: pointer;
}
.indef input{
	width: 100%;
	border: 1px solid #888888;
	font-size: 16px;
	padding: 5px 10px;
}
.indef select, .indef option{
	width: 100%;
	background-color: #1953F3;
	color: #FAFAFA;
	padding: 5px;
	font-size: 16px;
}
.indef textarea{
	width: 100%;
	border: 1px solid #888888;
	font-size: 16px;
	padding: 5px 10px;
	height: 400px;
	resize: none;
}	
</style>	
</head>
<body>
<div class="container">
	<h1>List Of Medicine</h1>
	<form method="post" action="medicSave.php">
		<div class="indef">
			<table>
				<thead>
					<tr>
						<th>Drug Name</th>
						<th>Dose</th>
						<th>Days</th>
						<th>External Medicine</th>
						<th>Action</th>
					</tr>
				</thead>
				<tbody id="dataset"></tbody>
			</table>
		</div>
		<div class="indef">
			<input type="hidden" name="totalRow" id="totalRow" value="0">
			<button type="submit" class="btn btn-process">Save Medicine</button>
		</div>
	</form>
	<hr>
	<div class="indef">
		<label for="drugName"><span>Drug Name :</span>
			<input type="text" id="drugName" placeholder="Insert Drug Name">
		</label>
	</div>
	<div class="indef">
		<label for="dose"><span>Dose :</span>
			<input type="text" id="dose" placeholder="Insert Dose">
		</label>
	</div>
	<div class="indef">
		<label for="days"><span>Days :</span>
			<input type="text" id="days" placeholder="Insert Days">
		</label>
	</div>
	<div class="indef">
		<label for="externalMedicine"><span>External Medicine :</span>
			<input type="text" id="externalMedicine" placeholder="Insert External Medicine">
		</label>
	</div>
	<div class="indef">
		<button id="add" class="btn btn-info">Add medicine list</button>
	</div>
</div>
<script type="text/javascript">

	var dataset = document.getElementById('dataset'),
	drugName = document.getElementById('drugName'),
	dose = document.getElementById('dose'),
	days = document.getElementById('days'),
	externalMedicine = document.getElementById('externalMedicine'),
	add = document.getElementById('add'),
	totalRow = document.getElementById('totalRow');

	add.onclick = function(){

		var getRow = dataset.getElementsByTagName('tr').length,
		trDataset = document.createElement('tr'),
		tdDrugName = document.createElement('td'),
		tdDose = document.createElement('td'),
		tdDays = document.createElement('td'),
		tdExternalMedicine = document.createElement('td'),
		inDrugName = document.createElement('input'),
		inDose = document.createElement('input'),
		inDays = document.createElement('input'),
		inExternalMedicine = document.createElement('input'),
		tdAction = document.createElement('td');

		/* Initiate Column Drugname Section */

		inDrugName.setAttribute('type','hidden');

		inDrugName.setAttribute('id','drugname_' + getRow);

		inDrugName.value = drugName.value;

		inDrugName.name = 'drugname_' + getRow;

		tdDrugName.textContent = drugName.value;

		tdDrugName.appendChild(inDrugName);

		/* End Column Drugname Section */

		/* Initiate Column Dose Section*/

		inDose.setAttribute('type','hidden');

		inDose.setAttribute('id','dose_' + getRow);

		inDose.value = dose.value;

		inDose.name = 'dose_' + getRow;

		tdDose.textContent = dose.value;

		tdDose.appendChild(inDose);

		/* End Column Dose Section */

		/* Initiate Column Days Section*/

		inDays.setAttribute('type','hidden');

		inDays.setAttribute('id','days_' + getRow);

		inDays.value = days.value;

		inDays.name = 'days_' + getRow;

		tdDays.textContent = days.value;

		tdDays.appendChild(inDays);

		/* End Column Days Section */

		/* Initiate Column External Medicine Section*/

		inExternalMedicine.setAttribute('type','hidden');

		inExternalMedicine.setAttribute('id','external_medicine_' + getRow);

		inExternalMedicine.value = externalMedicine.value;

		inExternalMedicine.name = 'external_medicine_' + getRow;

		tdExternalMedicine.textContent = externalMedicine.value;

		tdExternalMedicine.appendChild(inExternalMedicine);

		/* End Column External Medicine Section */

		/* Action */

		tdAction.textContent = 'Click At Row';

		/* End Action*/

		/* Initiate Each Row */

		trDataset.appendChild(tdDrugName);

		trDataset.appendChild(tdDose);

		trDataset.appendChild(tdDays);

		trDataset.appendChild(tdExternalMedicine);

		trDataset.appendChild(tdAction);

		/* Trigger To Select */

		trDataset.onclick = (function(){

			return function(){

				drugName.value = this.childNodes[0].getElementsByTagName('input')[0].value;

				dose.value = this.childNodes[1].getElementsByTagName('input')[0].value;

				days.value = this.childNodes[2].getElementsByTagName('input')[0].value;

				externalMedicine.value = this.childNodes[3].getElementsByTagName('input')[0].value;

				this.parentNode.removeChild(this);

				totalRow.value = dataset.getElementsByTagName('tr').length;

				drugName.focus();

			}

		}());

		/* Add Row To Dataset / Table */

		dataset.appendChild(trDataset);

		getRow++;

		/*Set Total Row, This Use for looping in medicSave.php*/

		totalRow.value = getRow;

		/* Reset Value Input*/

		drugName.value = '';

		dose.value = '';

		days.value = '';

		externalMedicine.value = '';

		drugName.focus();

	}
	
</script>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...