I know this has been asked a million times, but I just can't seem to get it right. I am trying to insert multiple rows at the same time with data sent using jQuery.
I am using AJAX/jQuery to send values like this:
jQuery / AJAX
var extrasids = $('.classextrasid').map(function() {return $(this).val()}).toArray();
var extrasrates = $('.classextrasid').map(function() {return $(this).data('rates')}).toArray();
var extrasquantities = $('.classextrasid').map(function() {return $(this).data('quantity')}).toArray();
$.ajax({
type: "POST",
url: "modules/addsinglebooking.php",
dataType: 'json',
data: {extrasids:extrasids,extrasrates:extrasrates,extrasquantities:extrasquantities},
cache: false,
})
My PHP looks like this:
PHP
<?php
session_start();
$inputvalues = $_POST;
$errors = false;
$returnResult;
$result = false;
include_once '../../includes/database.php';
$extraids = $inputvalues['extrasids'];
$extrarates = $inputvalues['extrasrates'];
$extraquantities = $inputvalues['extrasquantities'];
if( !$errors ) {
foreach($extraids as $extraid){
$stmt = $mysqli->prepare("INSERT INTO `extras`(`extraid`,`extrarate`,`extraquantity`) values (?,?,?)");
$stmt->bind_param('sss', $extraid,$extrarates,$extraquantities);
if(!$stmt->execute()) echo $stmt->error;
}
$result = $stmt->get_result();
$returnResult = "Success";
}
mysqli_close($mysqli);
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
My problem:
If my values looked like this, my above code would work:
extraid extrarates extraquantity
---------------------------------------
1 rate1 quantity1
2 rate1 quantity1
3 rate1 quantity1
but all values are different like this:
extraid extrarates extraquantity
---------------------------------------
1 rate1 quantity1
2 rate2 quantity2
3 rate3 quantity3
So I only to loop through one array and add multiple records if the rest of the values are the same and only one value is different.
How can I loop through everything to add 3 multiple rows which are unique?
In your foreach you can add this:
$i = 0;
foreach($extraids as $extraid){
$stmt = $mysqli->prepare("INSERT INTO `extras`(`extraid`,`extrarate`,`extraquantity`) values (?,?,?)");
$stmt->bind_param('sss', $extraid,$extrarates[$i++],$extraquantities[$i++]);
if(!$stmt->execute()) echo $stmt->error;
}
So first setting $i to 0 and then in the loop increment it with each time it repeats
Related
I am running a POST + json code to collect data from database, all results come with only one value (this is correct), however there is only one column which should show more than one value but shows only the first one. What I need to change in my code to get this list instead of the first row result?
I've run one MYSQL query linking three databases those share the same id PCRNo, the first two databases tPCR and tcomplement should only have one result and the third one should receive more results due to we can have more lines with the same id.
This is my JavaScript
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
$('#description').val(data.Name);
$('#Comments').val(data.Comments);
$('#originator').val(data.Creator);
$('#change_type').val(data.Category);
$('#product_type').val(data.Product);
$('#req_dept').val(data.Department);
$('#flow').val(data.Flow_Start_Date);
$('#own').val(data.Owning_Site);
$('#impacted').val(data.Impacted_Site);
$('#approval').val(data.Meeting_Status);
$('#review').val(data.Review_Date);
$('#cat').val(data.Cat);
$('#cost').val(data.Cost);
$('#labor').val(data.Labour);
$('#volume').val(data.Volume);
$('#request').val(data.Request);
$('#justification').val(data.Justification);
$('#PCNlist').val(data.PCNNo);
$('#monitor').val(data.Monitor);
$('#env').val(data.Environment);
$('#trial').val(data.Trial);
$('#resp').val(data.Responsible);
$('#deadline').val(data.Deadline);
$('#dataModal').modal('show');
}
});
});
$(document).on('click', '#update', function(){
var pcr_number = document.getElementById("PCR").value;
var Comments= document.getElementById("Comments").value;
var approval= document.getElementById("approval").value;
var review= document.getElementById("review").value;
var cat= document.getElementById("cat").value;
var monitor= document.getElementById("monitor").value;
var env= document.getElementById("env").value;
var trial= document.getElementById("trial").value;
var resp= document.getElementById("resp").value;
var deadline= document.getElementById("deadline").value;
var PCC = document.getElementById("PCC").value;
$.ajax({
url:"edit.php",
method:"POST",
data:{pcr_number:pcr_number, Comments:Comments, PCC:PCC, approval:approval, review:review, cat:cat, monitor:monitor, env:env, trial:trial, resp:resp, deadline:deadline},
dataType:"text",
success:function(data)
{
alert('PCR Information Updated');
}
});
});
});
</script>
this is my fetch.php
<?php
$SelectedPCRNo = $_POST['pcr_number'];
if(isset($_POST['pcr_number']))
{
$output = '';
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "change_management";
$dbConnected = #mysqli_connect($hostname, $username, $password);
$dbSelected = #mysqli_select_db($databaseName,$dbConnected);
$dbSuccess = true;
if ($dbConnected) {
if ($dbSelected) {
echo "DB connection FAILED<br /><br />";
$dbSuccess = false;
}
} else {
echo "MySQL connection FAILED<br /><br />";
$dbSuccess = false;
}
$sql = mysqli_query($dbConnected, "SELECT * FROM change_management.tPCR INNER JOIN change_management.tcomplement ON change_management.tPCR.PCRNo = change_management.tcomplement.PCRNo INNER JOIN change_management.tPCN ON change_management.tPCR.PCRNo = change_management.tPCN.PCRNo WHERE tPCR.PCRNo = '".$_POST['pcr_number']."'");
$row = mysqli_fetch_array($sql);
echo json_encode($row);
}
?>
I have no problems with the results and the table is filled OK, only the #PCNlist should be filled with the values of all rows it is related and now just is just coming one value, the first row only. Is there any way to bring the whole PCNlist only changing some code at the fetch.php?
If I understood you correctly, the table tPCN can contain multiple rows associated with each PCR number. And you want to fetch all these rows and return them in your JSON.
If you want to achieve that, but also make sure the other two tables only return one row, then I think simply you should remove the JOIN to tPCN in your first query, and then create a second query to fetch the tPCN rows specifically.
$output = [];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCR INNER JOIN change_management.tcomplement ON change_management.tPCR.PCRNo = change_management.tcomplement.PCRNo WHERE tPCR.PCRNo = ?");
$stmt->bind_param('s', $_POST['pcr_number']);
$stmt->execute();
$result = $stmt->get_result();
//select a single row from the result and assign it as the output variable
if ($row = $result->fetch_assoc()) {
$output = $row;
}
$stmt2 = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt2->bind_param('s', $_POST['pcr_number']);
$stmt2->execute();
$result2 = $stmt2->get_result();
$output["tPCN"] = array(); //create a new property to put the tPCN rows in
//loop through all the tPCN rows and append them to the output
while ($row2 = $result2->fetch_assoc()) {
$output["tPCN"][] = $row2;
}
echo json_encode($output);
This will produce some JSON with this kind of structure:
{
"PCRNo": "ABC",
"CreationDate": "2019-08-07",
"Name": "A N Other",
//...and all your other properties, until the new one:
"tPCN": [
{
"SomeProperty": "SomeValue",
"SomeOtherProperty": "SomeOtherValue",
},
{
"SomeProperty": "SomeSecondValue",
"SomeOtherProperty": "SomeOtherSecondValue",
}
]
}
You will then need to amend your JavaScript code to be able to deal with the new structure. Since I don't know exactly which fields come from the tPCN table, I can't give you an example for that, but hopefully it's clear that you will need to loop through the array and output the same HTML for each entry you find.
N.B. As you can see I re-wrote the query code to use prepared statements and parameterised queries, so you can see how to write your code in a secure way in future.
P.S. You have a lot of code there in the "success" function just to set the values of individual fields. You might want to consider using a simple JS templating engine to make this less verbose and cumbersome, and generate the HTML you need with the values automatically added into it in the right place. But that's a separate issue, just for the maintainability of your code
I've added this code into my ajax function to bring only what I needed and it works + what #ADyson has posted.
var PCN = data.tPCN;
var i;
var PCNList = '';
for (i = 0; i < PCN.length; i++){
var PCNList = PCNList + PCN[i]['PCNNo'] + ' - ' + PCN[i]['Stage'];
}
$('#PCNlist').val(PCNList);
I'm trying to set up a button which when clicked adds a fixed number to the database value. The database is called var_stat and consists of id and value. The table has one row so far where id = var and value = 35. If clicked, the button should add 5 to the value making it 40.
I'm not sure what to do here, as all answers I found used a completely different approach and strings instead of integers. So far I have done this:
if (isset($_POST['n'])){
$n = $_POST['n'] ;
$stmt = $con->prepare('UPDATE var_stat SET value = value + $n WHERE id = ? ');
$stmt->bind_param('s', $id);
$id = "var";
$stmt->execute();
$stmt->close();
}
<script src="js/jQuery-3.4.1.js"></script>
<script>
function add(n){
$.ajax({
type: "POST",
url: "update.php",
data: {
'n' : n
},
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
<form>
<input type="button" value="+5" class="btn btn-circle btn-grey col-sm-10" onclick="add(5);">
</form>
If I change $n in the update.php to an integer and run the update.php by itself it works, however I can't seem to get this to run through my html page, so I guess there's something wrong with my javascript code?
Bind the n as well, move the id before the binding statement
if (isset($_POST['n'])){
$n = $_POST['n'] ;
$id = "var";
$stmt = $con->prepare('UPDATE var_stat SET value = value + ? WHERE id = ? ');
$stmt->bind_param('is',$n, $id);
$stmt->execute();
$stmt->close();
}
I have an array called "selected_checkboxes". In my database I have multiple columns and some of them contain the value 1, otherwise the value will be NULL. The names of those columns are exactly the same as the values of the array.
I would now like to check dynamically if the values of my array ($_POST['selected_checkboxes']) match with the values of my columns in the database. If ALL values from the array have the value 1 in the database, it should echo something like Match!
This is what I have tried so far but I think it's completely wrong:
if(!$result = $db->query("SELECT * FROM products")){
die('Error');
}
while($row = $result->fetch_object()){
foreach($_POST['selected_checkboxes'] as $value) {
if ($value == 1) {
$say .= $value . ' is = 1';
}
}
}
echo $say;
I appreciate any help!!
Edit:
This is how the array 'selected_checkboxes' is getting generated:
$('.show_result').click(function() {
// Get all selected checkboxes
var selected = [];
$.each($("input[type=checkbox]:checked"), function(){
selected.push($(this).attr('id'));
});
// Get the selected option field
selected.push($('#PG_Select_Bereich1').val());
// Deliver data to PHP
$.ajax({
url : "typo3conf/ext/produkteguide_sg/pi1/products.php",
type: "POST",
data : { selected_checkboxes:selected },
success: function(data, textStatus, jqXHR)
{
$("#PG_Resultate").html(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
//alert(errorThrown);
}
});
And this is how my database looks like:
I've done something similar but in a different way, I hope this is what you're looking for:
// Query execution
$result = mysqli_query($CONN,"SELECT * FROM whatever");
while($row_from_db = mysqli_fetch_array($result)){
$db_value = is_null($row_from_db['myValue']) ? 0 : 1;
$check_value = !isset($_POST['selected_checkboxes']['myValue']) ? 0 : 1
echo $db_value == $check_value ? "Match!" : "Not matching :(";
}
I am writing pseudo code for your requirement.
1) loop through array.
2) while loop through array if value of element is found 1 the go to next step otherwise continue loop.
3) If array element value is 1 then get a key of element and prepare sql query which checks that column name same as key name have value as 1 for each record then mark it as Match.
Hope this helps to you. If you not get with this then let me know i will write the code for you.
Edit:
Each of your checkbox name must be same as column name in database.
$array_checkbox = $_POST['selected_checkboxes'];
$query =" SELECT count(*) FROM <tabel_name> WHERE 1=1";
// get count from query and store it in $total_rows variable
$total_rows = 10; // for example purpose we take count value as 10
foreach($array_checkbox as $key => $checkbox){
$query = $query =" SELECT count(*) FROM <tabel_name> WHERE $key=1"; // here we take key of array as column name in sql query and getting that how many rows of the column have value 1
// get count from query and store it in $result variable
$result = 10;
if($result == $total_rows){
echo "Match";
}
}
Hope this is according to your requirement.
I am trying to insert jquery's sortable list values into MySql. I have issues with looping in MySql while inserting.
I have sorted items like this
-------------
Sorted List
-------------
did-1
fid-1
fid-2
fid-3
After this I have used 'serialize' to get these sorted list
$('.sortable').sortable({
connectWith: '.sortable',
tolerance: 'pointer',
update: function (event, ui) {
$('#add_list').click(function(){
var data = $('#drop_list1').sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: 'addnewlist.php',
success: function(data){
}
});
});
}
What i want is - Multiple insertion for every 'did', a 'fid' should be inserted. In my MqSql - '(did-1 , fid-1)(did-1 , fid-2)(did-1 , fid-3)'
I have tried this in my PHP.
foreach($_POST['doc'] as $doc)
{
for($i=0;$i<count($_POST['doc']);$i++)
{
$form=$_POST[$i]['form'];
echo $sql="INSERT INTO addnewdoc(doc_id,form_id) VALUES ($doc,$form)";
$res=parent::_executeQuery($sql);
}
}
If I'm understanding this correctly you want to loop through the docs, and then loop through the forms for each doc. Will this work instead?
foreach($_POST['doc'] as $doc)
{
foreach($_POST['form'] as $form)
{
echo $sql="INSERT INTO addnewdoc(doc_id,form_id) VALUES ($doc,$form)";
$res=parent::_executeQuery($sql);
}
}
That ends up running an insert query for each combination. You would be better off building all of the values into a single query and then executing it one time. For example:
$sql = "INSERT INTO addnewdoc(doc_id,form_id) VALUES ";
$values = Array();
foreach($_POST['doc'] as $doc)
{
foreach($_POST['form'] as $form)
$values[] = "($doc,$form)";
}
$sql .= join(',', $values);
$res=parent::_executeQuery($sql);
That gathers all of the values into an array and then joins each of them into a string separated by commas. You can then run a single insert query to insert all of the values.
I want to insert a sessionid and a set of students into the db.
The sessionid can be found in line of code below:
<td><input type='hidden' id='currentId' name='Idcurrent' readonly='readonly' value='4' /> </td>
A set of students are displayed in a select box as so:
<select id="studentadd" name="addtextarea">
<option value='1'>u08743 - Joe Cann</option>
<option value='4'>u03043 - Jill Sanderson</option>
<option value='7'>u08343 - Craig Moon</option>
</select>
Now I am using ajax to get both the sessionId value and the student's value and post them into a seperate php page where the insert happens by using code below:
function submitform() {
$.ajax({
type: "POST",
url: "updatestudentsession.php",
data: {
Idcurrent: $('#currentid').val(),
addtextarea:$('#studentadd').val()
},
dataType:'json', //get response as json
success: function(result){
if(result.errorflag){
$("#targetdiv").html('success');
}else{
//you got success message
$("#targetdiv").html('error');
$('#targetdiv').show();
}
}
});
}
Below is the seperate php file updatestudentsession.php where it is suppose to do the insert:
$studentid = array();
$studentid[] = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : '';
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : '';
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
}
$insert->close();
Now the problem I am having is that is not inserting the correct data in at all. It is insert the value 0 in both the SessionId and StudentId fields. Below is what the table should look like after the insert:
SessionId StudentId
4 1
4 4
4 7
Instead it looks like below:
SessionId StudentId
0 0
My question is what is causing it to not be able to retrieve and insert the correct data into the db?
Suppose part of problem is here:
Idcurrent: $('#currentid').val(),
In your HTML code ID is currentId when you are trying to get an element with id currentid. id selector is case sensitive. So, you simply pass nothing to your PHP as jquery can't find an element.
Not sure what is wrong with $studentid, but I see no reason to use an array there as you always pass only one value, so try to change your php code like below:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : '';
//var_dump($studentid);
//var_dump($sessionid);
//var_dump($_POST); - this is additionally to see whole $_POST variable.
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
}
$insert->close();
Also, see at commented out var_dump lines at the beginning. They will print values of your variables so you will be able to see what is actually set there. (as it is ajax, you will need to open developer tools and see what is returned in result on network tab)
UPD:
According to the latest comment, appears that$_POST['addtextarea'] is an array. Because of that code is modified to handle that. Please note how that value is taken:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
Old code, which is:
$studentid = array();
$studentid[] = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : '';
results in two level array. So $studentid is an array which contains one element which is an array also. That is why old for each loop is not working. $id were an array. And it was converted to 0
I think there is a probel in data :
data: {
Idcurrent: $('#currentid').val(),
addtextarea:$('#studentadd').val()
},
Try :
data: {
"Idcurrent": $('#currentid').val(),
"addtextarea":$('#studentadd').val()
},
Please not the double quotes "Idcurrent"