I've been researching this for 2 days but have yet to find an adequate solution to my issue. Essentially I am trying to "link" database rows by ID based on multiple check boxes using jQuery, but here is where it gets a little tricky:
Background:
- I have a database table (
positions
) displayed as an HTML table (#ct
) with check boxes next to each row. - Up to four (4) rows can be checked at a time and "linked" to one another (but don't worry about the limit of number of boxes that can be checked)
- Linking the rows from
positions
SHOULD create one new row incovered_positions
with columnsid
(PK),linked_id1
,linked_id2
,linked_id3
,linked_id4
What is already done:
- Each checkbox already has its value assigned to the respective row
id
inpositions
- A dropdown select box already triggers the Javascript function
ctActions()
What I think is needed:
Create an array in
ctActions()
of the checkbox values using something like:var linked_ids = []; $("#ct input[type='checkbox']:checked").each(function() { linked_ids.push(this.value); });
Encode and send the data to PHP:
var linked_ids_json = JSON.stringify(linked_ids); $.post('link-positions.php', { linked_ids_json: linked_ids_json } );
In my
link-positions.php
:// Get & explode array $array = json_decode($_POST['linked_ids_json']); // Test whether each value is set -- Not sure if needed $linked_id1 = (isset($array[0]) ? $array[0] : ""); $linked_id2 = (isset($array[1]) ? $array[1] : ""); $linked_id3 = (isset($array[2]) ? $array[2] : ""); $linked_id4 = (isset($array[3]) ? $array[3] : ""); include('../mysqli-connect.php'); $conn = dbConnect(); $sql = "INSERT INTO `covered_positions` ( linked_id1, linked_id2, linked_id3, linked_id4) VALUES (?, ?, ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param('iiii', $linked_id1, $linked_id2, $linked_id3, $linked_id4); $stmt->execute(); $conn->close();
But after all this, nothing happens. I'm sure there are some blatant errors in my code so I thought I would post it for some more experienced eyes.
UPDATES
- Fixed
$stmt->execute
to$stmt->execute()
but still does not solve issue.
$stmt->execute;
be$stmt->execute();
inlink-positions.php
? – sbeliv01 Feb 15 at 18:21->execute
stuff, you should also add in proper error handling on the DB code. you're simply assuming that each of those calls (connect, prepare, bind, execute) has succeeded. DB operations have exactly ONE way to succeed, and a near infinite number of ways to fail. ALWAYS check return values or try/catch db operations. – Marc B Feb 15 at 18:24