I'm trying to submit a form in a fancybox where users can add a company to a select box that exists on the modals parent page. Im doing this by submitting the modal information to a script that adds the company to my database. Then I run a query to to get all the updated companies as a group of tags. Then I am trying to pass that group of tags to the parent page as a jquery update. Im not sure if this is the best approach or where I'm going wrong.
I am attempting to use this post as a guide:
Find element on site from a fancybox iframe
But I have two problems with my code.
One: The fancybox is not closing
Two: The select box on the parent page is not updating
I am not sure where I am going wrong with my success call. The code from the Modal page is:
$("#send-message").click(function(){
$(this).closest('form').submit(function(){
return false;
});
var frm = $(this).closest('form');
if($(frm).valid()){
$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post(
"../forms/company_add.php",
data,
function(data) {
if (data.success) {
// data.redirect contains the string URL to redirect to
$('#companyselect', $(parent.document)).html(data.success);
parent.$.fancybox.close();
}
else {
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").append(data.error);
}
},
"json"
);
}
});
The Code from company_add.php returns all the options tags like such:
if ($_POST) {
// Collect POST data from form
$name = filter($_POST['name']);
$conmail = filter($_POST['conmail']);
$addy = filter($_POST['addy']);
$confax = filter($_POST['confax']);
$city = filter($_POST['city']);
$state = filter($_POST['state']);
$con = filter($_POST['con']);
$conphone = filter($_POST['phone']);
$zip = filter($_POST['zip']);
}
$search1 = mysql_query("SELECT man_name FROM manufacturers WHERE man_name = '$name'");
$outcome1 = mysql_fetch_row($search1);
$num_rows1 = mysql_num_rows($search1);
$imageid1 = $outcome1[0];
$imageid1 = filter($imageid1);
if ($num_rows1 > 0) {
echo json_encode(array(
"error" => '<div class="msg-error">A company by that name already exists.</div>'
));
} else {
$stmnt = mysql_query("INSERT INTO manufacturers (manufacturer_id, man_name, man_address, man_city, man_state,man_zip, man_contact, man_phone, man_fax, man_mail) VALUES ('NULL', '" . $name . "', '" . $addy . "' ,'" . $city . "', '" . $state . "' , '" . $zip . "' , '" . $con . "' , '" . $conphone . "' , '" . $confax . "', '" . $conmail . "' )");
//echo "Duplicate WAS found:" . $answer1;
mysql_query($answer1);
//}
$resp['status'] = 'success';
if (empty($error)) {
$nada = "SELECT man_name FROM manufacturers ORDER BY man_name ASC";
$resulter = mysql_query($nada);
$comp1 = '0';
//Spit out array of companys as select boxes
$select = '<option value="">--Select one--</option>';
while ($result59 = mysql_fetch_array($resulter))
$select .= '<option value="' . $result59['man_name'] . '">' . $result59['man_name'] . '</option>';
echo json_encode(array(
"success" =>$select
));
} else {
echo json_encode(array(
"error" => '<div class="msg-error">Error: Unable to add your company at this time</div>'
));
}
}
I am new to programming and very new to Jquery so I'm hoping someone can see where I'm going wrong. I am using fancybox 2 and php.
Have you checked error console for any JavaScript errors?
You can try this anyway:
parent.$('#companyselect').html(data.success);
Related
I am quite new in php and trying to write my first scripts. I put values in a database. If a record has to be changed, the user can choose the id of the record that has to be changed. Some datas will remain, only read and some f.e. remarks can be changed. I have no problem with getting the datas from the database, but with storing the changed values.
User can choose the record to be changed:
public function bejelentesKivalasztas(){
$this->kapcsolodas();
$sqlHibabejelentesekTablabol = "SELECT bejelentesID FROM hibarogzites";
$this->hibabejelentesekTablabol = mysqli_query($this->kapcs, $sqlHibabejelentesekTablabol);
$sorokSzama = mysqli_num_rows($this->hibabejelentesekTablabol);
global $adat;
global $i;
$adat = [];
print("<select class='textarea' name='bejelentes_ID' id='bejelentes_ID' style='width: 220px'>");
for ($i=0; $i<$sorokSzama; $i++){
$adat[$i] = mysqli_fetch_array($this->hibabejelentesekTablabol);
print("<option value='" . $adat[$i]['bejelentesID'] . "'> " . $adat[$i]['bejelentesID'] . " </option>");
}
}
Necessary datas will be recalled and printed with the possibility to change some of them:
<?php
if(isset($_POST['bejelentesKivalasztas'])){
$bejelentesID = $_POST['bejelentes_ID'];
$boltCimBeolvasas = new adatlekerdezes($bejelentesID);
$boltCimBeolvasas ->boltCimBeolvasas($bejelentesID);
}
?>
public function boltCimBeolvasas(){
if(isset($_POST['bejelentesKivalasztas'])){
$bejelentesID = $_POST['bejelentes_ID'];
$this->kapcsolodas();
global $boltSzam, $boltVaros, $boltIrsz, $boltUtca, $bejelentesID;
$this->bejelentesID = $bejelentesID;
$this->egyBoltkivalasztas();
$sqlReadBoltAddressFromTable= "SELECT * FROM boltok WHERE boltID = '" . $this->boltID ."'";
$boltCimBeolvasas = mysqli_query($this->kapcs,$sqlReadBoltAddressFromTable);
$this->adat2 = mysqli_fetch_array($boltCimBeolvasas);
$this->boltSzam = $this->adat2[1];
$boltSzam = $this->boltSzam;
$boltIrsz = $this->adat2[2];
$boltVaros = $this->adat2[3];
$boltUtca = $this->adat2[4];
$this->bejelentesLehivas($this->bejelentesID);
$this->megjegyzesBeolvasas($this->bejelentesID);
}
}
public function megjegyzesBeolvasas(){
$this->kapcsolodas();
global $bejelMegjegyz;
$hibabejelentesekTablabol = [];
$this->sqlHibabejelentesekTablabol = "SELECT megjegyzesSzoveg FROM hibarogzites where bejelentesID = '" . $this->bejelentesID . "'";
$hibabejelentesekTablabol = mysqli_fetch_array(mysqli_query($this->kapcs, $this->sqlHibabejelentesekTablabol));
global $adat3;
$adat3 = [];
$this->adat3 = $hibabejelentesekTablabol;
$bejelMegjegyz = $this->adat3[0];
return $bejelMegjegyz;
}
But when restoring should follow, the ID (bejelentesID) gets lost and as this, data will not change.
public function bejelentesMod($intezkedes, $megjegyzes, $szerelo, $bejelentesID){
$this->kapcsolodas();
$sqlSzereloAdat = "SELECT *
FROM szerelo
WHERE szerelo_nev = '" . $szerelo . "'";
$szereloAdat = mysqli_fetch_array(mysqli_query($this->kapcs, $sqlSzereloAdat));
print("Szerelőadat: " . $szereloAdat['szereloID'] . " eddig / ");
$this->szereloID = $szereloAdat['szereloID'];
$this->intezkedesID = $intezkedes;
$this->bejelentesID = $bejelentesID;
print("intID: " . $this->intezkedesID);
print(" / bejelID: " . $this->bejelentesID);
$sqlHibabejelentesFrissites = "UPDATE hibarogzites SET megjegyzesSzoveg = '" . $megjegyzes . "', intezkedesID = '" . $this->intezkedesID . "', szereloID = '" . $this->szereloID . "', felhasznaloID = '" . $this->felhasznaloID . "' WHERE bejelentesID = '" . $this->bejelentesID . "'";
$hibabejelentesFrissites = mysqli_query($this->kapcs, $sqlHibabejelentesFrissites);
print(', $sqlhibabejelentesFrissítés értéke: ' . $sqlHibabejelentesFrissites);
if(!mysqli_connect_errno()){
$this->message = "A bejegyzés módosítva";
}
else{
$this->message = "A bejegyzés módosítása nem sikerült";
}
// header('Location: hibabejelentesek.php');
}
From that point that the id gets lost, the update cannot happen. I tried the mysql command at it worked in the sql programm directly. I inserted the
print("intID: " . $this->intezkedesID);
print(" / bejelID: " . $this->bejelentesID);
in function bejelentesMod to see what was the problem.
Maybe session can be the solution - but the id must be changed when another record must be changed. Can I use this session variable despite of that?
I suppose there are several problems with this code, but as I wrote - this is my first one. Even though I hope someone can me help how to get it work.
Thanks in advance for any help.
here i'am trying to insert multiple rows at same time in my case more than 200-250 rows at same time but i got below error
Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini
but when i increased the max_input_vars = 3000 this solved problem was now iam able to insert but it is taking too much time.
i want to insert faster but need help
this is my php code
<?php
include "connection.php";
if (isset($_POST['close_val'])) {
$item_cid = $_POST["item_cid"];
$item_id = $_POST["item_id"];
$op_date = $_POST["op_date"];
$op_value = $_POST["op_value"];
$close_date = $_POST["close_date"];
$close_val = $_POST["close_val"];
// Converting the array to comma separated string
for ($count = 0; $count < count($item_id); $count++) {
$item_cid_clean = mysqli_real_escape_string($conn, $item_cid[$count]);
$item_id_clean = mysqli_real_escape_string($conn, $item_id[$count]);
$op_date_clean = mysqli_real_escape_string($conn, $op_date[$count]);
$op_value_clean = mysqli_real_escape_string($conn, $op_value[$count]);
$close_date_clean = mysqli_real_escape_string($conn, $close_date[$count]);
$close_val_clean = mysqli_real_escape_string($conn, $close_val[$count]);
$sql = "SELECT COUNT(*) AS cntuser from bar_opening_details WHERE `item_id` = '" . $item_id_clean . "' AND close_date='" . $close_date_clean . "' AND item_cid='" . $item_cid_clean . "' ";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$count1 = $row['cntuser'];
if ($count1 > 0) {
// update
$updatequery = "UPDATE bar_opening_details SET
`item_cid` = '" . $item_cid_clean . "',
`item_id` = '" . $item_id_clean . "',
`op_date` = '" . $op_date_clean . "',
`op_value` = '" . $op_value_clean . "',
`close_date` = '" . $close_date_clean . "',
`close_val` = '" . $close_val_clean . "'
WHERE close_date='" . $close_date_clean . "' and `item_id` = '" . $item_id_clean . "' ";
mysqli_query($conn, $updatequery);
} else {
$insertquery = "INSERT INTO bar_opening_details
(item_cid,
item_id,
op_date,
op_value,
close_date,
close_val) values ('" . $item_cid_clean . "', '" . $item_id_clean . "', '" . $op_date_clean . "', '" . $op_value_clean . "', '" . $close_date_clean . "', '" . $close_val_clean . "')";
mysqli_query($conn, $insertquery);
}
}
// insert
$return_arr = array('item_cid' => $item_cid, 'item_id' => $item_id, 'op_date' => $op_date, "close_val" => $count);
echo json_encode($return_arr);
mysqli_close($conn);
}
here is my ajax code. using this iam able to sent request to insert but it is takin to much time
<script>
$(document).ready(function() {
// submit button click
$("#submit").click(function() {
$('#loading').show();
var item_cid = [];
var item_id = [];
var op_date = [];
var op_value = [];
var close_date = [];
var close_val = [];
var Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
// Initializing array with Checkbox checked values
$("input[name='item_cid[]']").each(function() {
item_cid.push(this.value);
});
$("input[name='item_id[]']").each(function() {
item_id.push(this.value);
});
$("input[name='op_date[]']").each(function() {
op_date.push(this.value);
});
$("input[name='op_value[]']").each(function() {
op_value.push(this.value);
});
$("input[name='close_date[]']").each(function() {
close_date.push(this.value);
});
$("input[name='close_val[]']").each(function() {
close_val.push(this.value);
});
$.ajax({
url: 'lib/cbentry.php',
type: 'post',
data: {
item_cid: item_cid,
item_id: item_id,
op_date: op_date,
op_value: op_value,
close_date: close_date,
close_val: close_val
dataType: 'JSON',
success: function(response) {
$('.details').show();
// selecting values from response Object
var name = response.close_val;
$('#loading').hide();
// var email = response.email;
// var lang = response.lang;
// var foundjquery = response.foundjquery;
Toast.fire({
icon: 'success',
title: 'Data Entered Successfully'
})
// setting values
$('#name').text(name);
// $('#email').text(email);
// $('#lang').text(lang);
// $('#foundjquery').text(foundjquery);
}
});
});
});
</script>
JSON
A simple 2-line fix to allow for unlimited items: Suggest you encode the array into JSON for POSTing, then use json_decode() to turn it back into an array when it arrives in PHP.
But, I have to ask... Are there really hundreds of new (or changed) rows? If only a few rows, consider shipping one row at a time via AJAX to PHP -- perhaps based on whether a value has changed after the mouse leaves "focus". A lot of little AJAX calls would have a lot of overhead (launching many PHP threads), but the task would be finished by the time you leave the web page. It would "feel" as if every thing was "instantaneous". (OK, if you have a thousand users doing this same thing at the same time, this technique could overload the server.)
Arrays
Here's another approach: Use "arrays". If the input names end in []:
<input type=text name=x[] ">
the will come in as an array in $x. If you have multiple of these, then the subscripts (0, 1, ...) will let you match them up.
$list = GetArray('list');
function GetArray($fn) {
// Input an array of things from
// echo "<input type=checkbox name=\"fn[]\" value=\"$out_fn\" $checked>\n";
// url has &fn[]=aaa&fn[]=ccc
$req = #$_REQUEST[$fn]; // Note: this must NOT end in []
$fns = empty($req) ? [] :
(is_array($req) ? $req :
explode(',', $req));
return $fns; // always an array
}
($_REQUEST includes $_POST; change it if you would prefer)
INSERT
As for the speed of a MySQL insert... A single INSERT with 100 rows will run 10 times as fast 100 1-line INSERTs. So, if there are really hundreds of new rows, I recommend "batching" the inserts.
If most of the rows are already in the table, then INSERT IGNORE is a 'simple' way to deal with that. But... If there is an AUTO_INCREMENT id on the table, the dups will "burn" ids.
IODKU is the optimal way to deal with rows that are either new or modified. It, too, can be batched. But, it also burns ids if the query is not including the original id where available.
(I can elaborate, you you elaborate.)
I have an $.ajax function that posts to a php page and gets some results.
function GetLicenseCount(SoftwareNameFK, SoftwareTypeFK,LicenseMethodFK,MinistryFK )
{
$.ajax({
type: "GET",
url: "modules/SoftwareLicenseAllocations/GetLicenseCount.php",
data: {SoftwareName : SoftwareNameFK, SoftwareType: SoftwareTypeFK, LicenseMethod: LicenseMethodFK, Ministry: MinistryFK},
dataType: "json",
success: function(result) {
var LicenseCount = document.getElementById("txtLicenseCount");
var idHidden = document.getElementById("txtId");
//get id value from string, by using split and getting the first part before the delimeter
var id = result.split(",")[0];
//get second part of result using string
LicenseCount.value = result.split(",")[1];
idHidden.value = id;
},
error: function(reason) {
console.log(reason);
alert("Failed to get License Count");
}
});
}
GetLicenseCount.php
<?php
//Local include path format
set_include_path('C:\PROJECTS\BRIAN\AMS\Web Application;C:\PROJECTS\BRIAN\AMS\Web Application\inc\pear;C:\PROJECTS\BRIAN\AMS\Web Application\js;');
//Search Screen
require_once('vars.php');
require_once('funcs.php');
//read the parameter passed through URL
$SoftwareName = $_GET['SoftwareName'];
$SoftwareType = $_GET['SoftwareType'];
$LicenseMethod = $_GET['LicenseMethod'];
$Ministry = $_GET['Ministry'];
//formulate query - get all active departments
$queryString = "SELECT DISTINCT id, LicenseCount"
. " FROM SoftwareLicenseAllocations WHERE"
. " SoftwareTypeFK =" . $SoftwareType
. " AND SoftwareNameFK = " . $SoftwareName
. " AND LicenseMethodFK=" . $LicenseMethod
. " AND MinistryFK=" . $Ministry;
// $queryString = "SELECT DISTINCT LicenseCount"
// . " FROM SoftwareLicenseAllocations WHERE"
// . " SoftwareTypeFK =" . 2
// . " AND SoftwareNameFK = " . 2
// . " AND LicenseMethodFK=" . 2
// . " AND MinistryFK=" . 1 ;
$sla = GetOpenItDataSet($queryString);
//loop on result set to refresh the department options list
while ($row = mysql_fetch_array($sla))
{
$LicenseCount = $row["LicenseCount"];
$id = $row['id'];
}//endWhile
$_SESSION['id'] = 22;
//echo $departmentArray;
echo json_encode($id . "," . $LicenseCount);
//$_POST["lcID"] = $id;
I am trying to get one of the values passed on in the original page.
i tried using $_Session on GetLicenseCount.php but the variable remains null.
Is is possible to pass a variable from jQuery to PHP? If so, how?
EDIT:
The problem is that GetLicenseCount is supposed to pass id, which it is doing, but I cannot use it in the original page via PHP, only via jQuery. When I come to use the $_SESSION['id'] through the original/previous php page it remains null.. The jQuery block is contained in another php page.
This is the first time i am working on php and JavaScripts ... need your help in fixing something.
my site have a searchbox at the header, when a search term is submitted it goes to the search.php which holds a filter menu and search result. The filter menu is based on few selectlist. As soon as any optionis clicked in the filter menu it updates the search result.
For this i am using a javascript that calls data from another php file "SearchResult.php" to update a div with ID #Result.
PROBLEM:
it works perfectly fine at localhost however when online it causes a delay in updating the Search Result.
HELP:
Is there any way to show loading of some kind to let the viewer understand or is there anyway to make it fast.
here are my codes:
Java Script Function
function get()
{
$('#Search_Results').hide();
$.post('SearchResults.php', { Search: form.Search.value, cat: form.category.value, brand: form.brand.value },
function(output)
{
$('#Search_Results').html(output).show();
}
)
}
SEARCH FILTER FORM
enter code hereif(!empty($_REQUEST['Search'])){
$SearchTerm = $_REQUEST['Search'];
} else {
$SearchTerm = '';
}
// Search term submited
echo '<input name="Search" type="hidden" value="'.$SearchTerm.'" />';
$sql = mysql_query ("SELECT * FROM categories");
echo '<h4>Filter Categories</h4><select name="cat" onChange="get();" size="15">';
echo '<option value="" class="Select_Options">All Categories</option>';
while ($row = mysql_fetch_array($sql))
{
echo '<option class="Select_Options" value="' . $row["CategoryID"] . '">' . $row["CategoryName"] . '</option>';
}
echo '</select>';
//Few more such filters
SEARCH RESULT PAGE
if(!empty($_REQUEST['Search'])){
$SearchTerm = $_REQUEST['Search'];
}
else {
echo 'Please enter search keyword(s)';
exit();
}
if(!empty($_REQUEST['cat'])){
$cat = $_REQUEST['cat'];
$SearchQuery .= " AND categories.CategoryID = '$cat'";
}
if(!empty($_REQUEST['brand'])){
$brand = $_REQUEST['brand'];
$SearchQuery .= " AND brands.BrandID = '$brand'";
}
$sql = "SELECT DISTINCT products.ProductID, ProductKeywords, products.SectionID, products.ProductThumb, products.ProductPrice, products.CategoryID, products.SubCategoryID, products.BrandID, brands.BrandLogo, ProductTitle AS title FROM products
INNER JOIN brands ON products.BrandID = brands.BrandID
INNER JOIN sections ON products.SectionID = sections.SectionID
INNER JOIN categories ON products.CategoryID = categories.CategoryID
INNER JOIN subcategory ON products.SubCategoryID = subcategory.SubCatID $ColorJoin
WHERE MATCH (ProductKeywords) AGAINST ('$SearchTerm*' in boolean mode)$SearchQuery";
$query = mysql_query($sql);
echo '<div id="Product_Search_Container"><ul>';
while ($row = mysql_fetch_array($query))
{
$ProductID = $row["ProductID"];
$sql2 = mysql_query ("SELECT COUNT(ProColorID) AS ProductCount FROM productcolors WHERE ProductID = '$ProductID'");
while ($row5 = mysql_fetch_array($sql2))
{
$BrandID = $row["BrandID"];
$sql3 = mysql_query ("SELECT * FROM brands WHERE BrandID = '$BrandID'");
while ($row6 = mysql_fetch_array($sql3))
{
$ProductThumb = $row["ProductThumb"];
if ($ProductThumb == NULL) { $ProductThumb = "No_Image.jpg"; }
echo '<li><img src="images/Products/Thumbs/' . $ProductThumb . '" width="210px" height="275px" />
<div class="zoomer"><span class="zoom';
if ($ProductThumb != "No_Image.jpg") {
echo ' cursonstyle" style="position: relative; overflow: hidden;"><img src="images/Products/Thumbs/zoom/' . $ProductThumb . '" alt="' . $row["title"] . '" />
'; } else { echo '">'; }
echo '</span><span class="Pro_Title">' . $row["title"] . '</span>
<span class="BrandLogo"><img src="images/Brands/' . $row6["BrandLogo"] . '" /></span>
<span class="ProColors">' . $row5["ProductCount"] . ' Colors</span>
<span class="ProPrice">$' . $row["ProductPrice"] . '</span>
</a></li>';
}
}
}
echo '</ul></div>';
You could show a loading message as simple as showing it when you start the post request and hiding it in the callback.
function get()
{
$('#Search_Results').hide();
$('#loading').show().html('Please wait while loading..'); // <-- show message on function call
$.post('SearchResults.php', { Search: form.Search.value, cat: form.category.value, brand: form.brand.value },
function(output)
{
$('#loading').hide(); // <-- hide in callback function
$('#Search_Results').html(output).show();
}
)
}
You should also handle errors in your ajax request and look into prepared statements or at least use mysql_real_escape_string() for all user inputs.
First off, i have checked to make sure that the const.php is in the directory where the page is.
I am creating a page that would allow admin to add multiple entries to a MySQL table through the website. It uses a JavaScript to expand the array of textbox input fields so that an admin does not have to enter any more entries than he/she has to. But if the entry the admin is trying to add is already there, then it won't be added. After the code is run the user is told which entries were added to the table and which entries were not added because there was already such an entry.
Here is the form which passes input arrays to the PHP code.
form id=userform action="addplayers.php" method="post" >
<legend>Player Info</legend>
<ol>
<div id="dynamicInput">
<li>
<label for=player>Player</label>
<input id=player type="text" name="player[]">
</li>
<li>
<label for=team>Team</label>
<input id=team type="text" name="team[]">
</li>
<li>
<label for=path>Player page path</label>
<input id=path type="text" name="path[]">
</li>
<li>
<label for=image>Player image path</label>
<input id=image type="text" name="image[]">
</li>
<br/>
</div>
</ol>
<input type="button" value="ADD ANOTHER PLAYER" onClick="addInput();">
<button type=submit name=submit> Submit </button>
</form>
Here the javascript code dynamically creates textbox input fields which expands the input array.
<script language="Javascript" type="text/javascript">
function addInput(){
var newdiv = document.createElement('div');
newdiv.innerHTML = "<li><label for=player>Player</label><input id=player type='text' name='player[]'></li>";
document.getElementById('dynamicInput').appendChild(newdiv);
var newdiv = document.createElement('div');
newdiv.innerHTML = "<li><label for=team>Team</label><input id=team type='text' name='team[]'></li>";
document.getElementById('dynamicInput').appendChild(newdiv);
var newdiv = document.createElement('div');
newdiv.innerHTML = "<li><label for=path>Player page path</label><input id=path type='text' name='path[]'></li>";
document.getElementById('dynamicInput').appendChild(newdiv);
var newdiv = document.createElement('div');
newdiv.innerHTML = "<li><label for=image>Player image path</label><input id=image type='text' name='image[]'></li><br/>";
document.getElementById('dynamicInput').appendChild(newdiv);
}
</script>
Here is the php code that form posts to.
include "const.php";
$entry_results = "";
if( isset($_POST['submit']) )
{
$conn = mysql_connect(MYSQL_HOST, MYSQL_LOGIN, MYSQL_PASSWORD) or die("Could not connect: " . mysql_error());
mysql_select_db(MYSQL_DB);
$player = $_POST['player'];
$team = $_POST['team'];
$path = $_POST['path'];
$image = $_POST['image'];
$invalid = array();
$valid = array();
$j = 0;
$k = 0;
for($i=0; $i<count($player);$i++)
{
//Check to see if player is in the database
$query = "Select name FROM tblPlayers where name = '" . $player[i] ."'";
$result = mysql_query($query);
if(!empty($result))//if query gives a result add player to list of invalid entries
{
$invalid[$j++] = $player[$i];
}
else//otherwise add to database
{
$valid[$k++] = $player[$i];
if(empty($image[$i]))
{$image[$i] = '#';}
if(empty($path[$i]))
{$path[$i] = '#';}
$query = "SELECT entity_id FROM tblTeams WHERE team = '" . $team[$i] . "'";
$result = mysql_query($query);
$query = "INSERT INTO tblPlayers ( team_id, name, image, path) VALUES (
'" . $result . "',
'" . $player[$i] . "',
'" . $image[$i] . "',
'" . $path[$i] . "'
)";
$result = mysql_query($query);
}
}
if(!empty($invalid[0]))
{
for($i=0;$i<count($invalid);$i++){
$entry_results .= $invalid[$i];
if(($i+1)!=count($invalid))
$entry_results .= ', ';
}
$entry_results .= "were found in the database and were not enterered to prevent duplicant record. ";
}
if(!empty($valid[0]))
{
for($i=0;$i<count($valid);$i++){
$entry_results .= $invalid[$i];
if(($i+1)!=count($valid))
$entry_results .= ', ';
}
$entry_results .= "were entered into the players table.";
}
mysql_close($conn);
}
?>
This separate line of PHP code tells admin the result of the entry.
<?php
if( !empty($entry_results) )
{
echo "<h3>$register_message</h3><br />\n";
}
?>
You are not handling result sets properly. Take a look at this bit of code:
$query = "SELECT entity_id FROM tblTeams WHERE team = '" . $team[$i] . "'";
$result = mysql_query($query);
$query = "INSERT INTO tblPlayers ( team_id, name, image, path) VALUES (
'" . $result . "',
'" . $player[$i] . "',
'" . $image[$i] . "',
'" . $path[$i] . "'
)";
After the first query, $result will be a result resource, not the value of the "entity_id" column. That code should be rewritten as:
$query = "SELECT entity_id FROM tblTeams WHERE team = '" . $team[$i] . "'";
$result = mysql_query($query);
if ($row = mysql_fetch_assoc($result)) {
$query = "INSERT INTO tblPlayers ( team_id, name, image, path) VALUES (
'" . $row['entity_id'] . "',
'" . mysql_real_escape_string($player[$i]) . "',
'" . mysql_real_escape_string($image[$i]) . "',
'" . mysql_real_escape_string($path[$i]) . "'
)";
} else {
die "Couldn't find entity_id for this team.";
}
Also, you should properly escape ALL user input that you use in database queries. I did this above using the "mysql_real_escape_string" function.
change all your form elements names from e.g: 'player[]' to 'player', and do so as well in your javascript.Submitting the form will automatically put all elements with the same name in an array.