Separating variables for SQL insert using PHP and JavaScript - javascript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.

When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli

Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Related

Use AJAX to run PHP script and then return single value

Okay, this question was closed for not being clear enough, so I'm going to completely re-write it in as clear a form as I can...
Project: Room Booking System
Required Function: Check the database for existing bookings matching a criteria, return the result of 'COUNT' SQL query to a textbox which another function then looks to.
The values which need to be inserted into the COUNT criteria are as follows:
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
</br>
Problem: I have a functioning php script which counts the number of rows in the database matching a criteria, which will then return the result to a textbox (main function sorted) when set up in a test directory with nothing else on the page. However, when I embed this php into an existing page (the new booking page) it doesn't work when the 'Check Availability' button is clicked. Instead, it reloads the page (as php does) which is not useful when users have already input their data for checking (and would need to re-enter it). I've Googled and have found that I need to use AJAX to run the php function in the background and then return the result to the textbox on the current page. I have never ever used AJAX and are only new to php, js etc. as it is, so I have no idea what I'm doing
How can you help: I need help in converting my existing code into a working solution to the above problem, probably using a combination of AJAX, PHP and JS functions.
Code:
PHP COUNT CODE (works)
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '2019-12-30' AND Time = 'Period 6' AND Room = 'C3'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
Area of php/html in which the result should be returned (id="availresult")
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
Test AJAX function, as suggested by an existing reply to my post
<script>
function soflow() {
$.post('checkAvailability.php', {info: 'start'}, function(data) { //if you don't need to send any data to the php file then you can set the value to whatever you want
document.getElementById('availResult').innerHTML = data;
});
}
</script>
I have tried various ways to do this myself, including modifying the suggested AJAX code above, but I'm not sure how to get my values from my various textbox over to the PHP function. Also, I don't know how to tell whether the AJAX function is running, or whether there is an error somewhere. At present, the value shown in my 'availresult' textbox does not change.
I appreciate any help with this, and thank anyone who has tried to help so far. I'm not sure how much clearer I can make this - please don't close the question again.
UPDATE:
(index.php):
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
<br/>
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
<script>
function soflow() {
var var_date = $('#datebox').val();
var var_time = $('#timebox').val();
var var_room = $('#roombox').val();
$.post('checkAvailability.php', {info: 'start', date: var_date, time: var_time, room: var_room}, function(data) {
document.getElementById('availResult').innerHTML = data;
});
}
</script>
</body>
</html>
(test.php):
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
if (mysqli_connect_errno()) { // Check connection
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = mysqli_real_escape_string($con, $_POST['date']);
$time = mysqli_real_escape_string($con, $_POST['time']);
$room = mysqli_real_escape_string($con, $_POST['room']);
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '$date' AND Time = '$time' AND Room = '$room'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
You could also do ajax with pure JavaScript, but this is simpler.
Also note that this is just an example on how to do an ajax connection in the first place.

Dynamically send javascript value via form

I don't know if it's possible, but I need to send some information across a form ou inside url come from checkbox value.
This code below is inside a products loop and create a checkbox on every products (product comparison approach).
In my case, it's impossible to make this code below across a form.
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
To resolve this point, I started to use an ajax approach and put the result inside a $_SESSION
My script to for the checbox value
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty create the list via ajax
if (chkArray.length !== 0) {
$.ajax({
method: 'POST',
url: 'http://localhost/ext/ajax/products_compare/compare.php',
data: { product_id: chkArray }
});
}
});
});
And at the end to send information on another page by this code. Like you can see there is no form in this case.
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
No problem, everything works fine except in my compare.php file, I have not the value of my ajax. I inserted a session_start in ajax file
But not value is inserted inside compare.php.
I tried different way, include session_start() inside compare.php not work.
My only solution is to include in my products file a hidden_field and include the value of ajax across an array dynamically, if it's possible.
In this case, values of hidden_fields must be under array and sent by a form.
This script must be rewritten to include under an array the chechbox value
without to use the ajax. How to insert the good code?
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty show the <div> and create the list
if (chkArray.length !== 0) {
// Remove ajax
// some code here I suppose to create an array with the checkbox value when it is on true
}
});
});
and this code with a form
<?php
echo HTML::form('product_compare', $this->link(null, 'Compare&ProductsCompare'), 'post');
// Add all the js values inside an array dynamically
echo HTML::hidddenField('product_compare', $value_of_javascript);
?>
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
</form>
Note : this code below is not included inside the form (no change on that).
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
My question is :
How to populate $value_of_javascript in function of the checkbox is set on true to send the information correctly inside compare.php
If my question has not enought information, I will edit this post and update in consequence.
Thank you.
You cannot pass JavaScript Objects to a server process. You need to pass your AJAX data as a String. You can use the JavaScript JSON.stringify() method for this...
$.ajax({
method: 'POST',
url : 'http://localhost/ext/ajax/products_compare/compare.php',
data : JSON.stringify({product_id: chkArray})
});
Once that has arrived at your PHP process you can turn it back into PHP-friendly data with PHP JSON methods...
<?
$myArray = json_decode($dataString, true);
// ... etc ... //
?>
See:
JSON # MDN
JSON # PHP Manual
Example: Form Submission Using Ajax, PHP and Javascript

How do I attach checkboxes to a submit

I have unknown amount of checkbox inputs on a page created based on rows in an sql database.
The checkboxes look like:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
The checkboxes are intended, when checked and submitted, to delete a row from the database based on the value of $mid
The checkboxes could be either loose (not contained in any forms), or each could be contained in its own form (without a submit button). There is no way however to contain all the checkboxes in one form.
The reason is it's displayed in a loop with output like this:
<tr>
<td><input type="checkbox" class="deletefunc" value="<? echo $mid; ?>"></td>
<td><input type="checkbox" class="star" value="1"> <!-- jquery/ajax onclick function --></td>
<td><a href></td>
<td><form name....><input type="submit" value="something"></form></td>
<tr>
So what I need help understanding is, how to gather all the checkboxes based on classname, and attach them to a submit button....
And further, how would I write the loop function so it knows how many deletes to perform? What I mean is, how would I write a loop that would get the values from an unknown amount of inputs. Normally I know how many inputs there are and what the names are so its a matter of assigning a variable for each input.... I've never done this with an unknown amount of inputs.
I would do it like this:
HTML:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
<button id="delete-them">Delete Them</button>
JS:
$(function() {
$('#delete-them').on('click', function() {
var data = $('.deletefunc').attr('name', 'delete[]').serialize();
$.ajax('delete-them.php', {
method: 'POST',
data: data,
success: function() {
alert('deleted!');
}
});
});
});
PHP:
<?php
$ids = $_POST['delete'];
$params = array_fill(0, count($ids), "?");
$sql = "DELETE FROM some_table WHERE id IN (" . implode(",", $params) . ")";
//DELETE FROM some_table WHERE id IN(?,?,?,?);
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
$stmt = $pdo->prepare($sql);
$stmt->execute($ids);
?>
So we basically listen for a click on our button, when it happens, we set the name (with [] at the end so it becomes an array) for all of the items with the class we care about, so that when we serialize those items we know how to reference it in our PHP.
We then POST that data over to the server, where we read the array we just sent, see how many there are, and then create a query to delete those items.

Automatically update another page without refreshing

I have this problem on how I could automatically update my webpage without refreshing. Could someone suggest and explain to me what would be the best way to solve my problem? Thanks in advance
add.php file
In this php file, I will just ask for the name of the user.
<form id="form1" name="form1" method="post" action="save.php">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
save.php In this file, I will just save the value into the database.
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
$sql->execute();
studentlist.php In this file, i want to display the name I enter
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
Problem
When the two pages is open, I need to refresh the studentlist.php before i can see the recently added data.
thanks :D
You'll want to use ajax and jquery. Something like this should work:
add.php
add to the head of the document:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){//loads the information when the page loads
var saveThenLoad = {
url: "save.php",//the file sending data to
type: 'POST',//sends the form data in a post to save.php
dataType: 'json',
success : function(j) {
if(j.error = 0){
$("#student_info").html(j.info);//this will update the div below with the returned information
} else {
$("#student_info").html(j.msg);//this will update the div below with the returned information
}
}
}
//grabs the save.submit call and sends to the ajaxSubmit saveThenLoad variable
$("#save").submit(function() {
$(this).ajaxSubmit(saveThenLoad);
return false;
});
//grabs the submit event from the form and tells it where to go. In this case it sends to #save.submit above to call the ajaxSubmit function
$("#add").click(function() {
$("#save").submit();
});
});
</script>
<!-- put this in the body of the page. It will wait for the jquery call to fill the data-->
<div id="student_info">
</div>
I would combine save and studentlist into one file like this:
$return['error']=0;
$return['msg']='';
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error saving data';
}
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error retrieving data';
}
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
$return['$output'];
echo json_encode($return);
Does this need to be in three separate files? At the very least, could you combine add.php and studentlist.php? If so, then jQuery is probably the way to go. You might also want to use some html tags that would make it easier to dynamically add elements to the DOM.
Here's the combined files:
<form id="form1" name="form1">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
The List of students <br></br>
<ul id="student-list">
<?php
//I assume you're connecting to the db somehow here
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_NUM)) //this might be easier to output than an associative array
{
//Returns will make your page easier to debug
print "<li>" . implode(" ", $result) . "</li>\n";
}
?>
</ul>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$('#form1').submit(function(event){
event.preventDefault();
//submit the form values
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
//post them
$.post( "test.php", { firstname: firstname, lastname: lastname })
.done( function(data) {
//add those values to the end of the list you printed above
$("<li>" + firstname + ' ' + lastname + "</li>").appendTo('#student-list');
});
});
});
</script>
You might want to do some testing in in the $.post call above to make sure it was handled properly. Read more about that in the docs.
If you really need three files, then you'll might need to use ajax to do some sort of polling on studentlist.php using setTimeout to see if you have any new items.
The cheap-way is using a meta-refresh to refresh your page (or use JavaScript setInterval and ajax).
The more expensive way is having a Realtime JavaScript application. Look at Socket.IO or something like that.

cakephp javascript dynamic update

all creating a cakephp(using 2.1.2) page. we prompt the user to enter how many fields they are after(an int) and then we want the page to use a for-loop for the number entered.
here is the code for the add page
<h2>Please select how many fields you wish to add</h2></br>
<?php
print $this->Session->flash('flash', array('element' => 'alert'));
echo $this->Form->create('Field', array('action'=>'add'));
For(int i=0; i<'flash'; i++)
{
echo $this->Form->input('name',array('label'=>'Please Enter Field Name: ', 'type'=>'text'));
echo $this->Form->input('description',array('label'=>'Please Enter Field Description: ', 'type'=>'text'));
}
echo $this->Form->end('Click Here To Submit Template');
?>
here is the code for the alert
<script type="text/javascript">
prompt('How many fields?','<?php print $message; ?>');
</script>
the question is how do we create a variable with the alert.ctp then be able to use that variable for a for loop to print out a form that takes user input.
EDIT:
Javascript function:
<script type="text/javascript">
var number_of_fields=prompt("How many fields?",'<?php print $message; ?>');
var field_html="";
for (i=0; i<number_of_fields; i++)
{
field_html +='<input type="text" name="data[FIELD]['+i+'][name]">';
}
$("#FORMID").append(field_html);
</script>
View:
<?php
print $this->Session->flash('flash', array('element' => 'alert'));
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->end('Click Here To Submit Template');
?>
Get no errors now, but cant display any fields. What do we put in the view to print the fields (which will be more input- so user can create a field)?
Since we are getting the value of no: of required in javascript , i recommend to create fields also in javascript by following conventions used by cakephp to create input fields. So you can use javascript for loop and concat the fields in to a js variable and insert this html inputs to the form using javascript.
eg:
var number_of_fields=prompt("How many fields?",'<?php print $message; ?>');
var field_html="";
for (i=0; i<number_of_fields; i++)
{
field_html +='<input type="text" name="data[MODELNAME]['+i+'][name]">';
}
$("#FORMID").append(field_html);
i hope this would make sense

Categories

Resources