UPDATE reflected in DB but not SELECT query - php

First time for me here.
I am using PHP, MySQL, JavaScript and running JQUERY and AJAX functions.
I have an anchor link that runs a function.
The function emptys a DIV tag and then fills/displays (SELECT query) a table of rows in the DIV with a is null where clause. Each row has a select box where the NULL data column would go. The data in the select box comes from a different table.
When the select box changes it immediately runs the ajax to UPDATE the table row with the new data in the select box.
When you click the link to run the function again (empty, select query and display based on null column) the row that was just updated to the DB shows up again based on the is null clause. Checking the DB table at this point shows that it is in fact not null and was UPDATEd properly the first go around.
The page is never refreshed during this process and never has to be. If I do refresh it shows the proper data without the BUG.
All your thoughts are greatly appreciated.
matt
function closeItemsBtn() { // called by a click function of a standard link/button
$('#CloseItems').empty(); // remove all html from the DIV
var newAppend = '';
<?
//[... connect to db ...]
// select info from 2 different tables so it can be used in different locations if necessary
// where the row has not been reviewed and therefore is null
$query = "select * from nearmiss where reviewedId is null order by submitDate desc";
$result = $db->query($query) or die($db->error);
$query2 = "select * from hazardid where reviewedId is null order by submitDate desc";
$result2 = $db->query($query2) or die($db->error);
$num_rows = $result->num_rows;
$num_rows2 = $result2->num_rows;
// create html for the DIV tag. Creates a table in a DIV that collapses by clicking aCloseList.
// each row is in tbody so it can be striped by a all purpose striping function
// this part is the table header and opening div tags and link
$newAppend = "<p id=\"closeList\">Show/Hide {$num_rows} Near Misses requiring attention.</p><div id=\"closenearmiss\" style=\"display:none;\"><table class=\"closenearmisstable\"><tbody><tr><td>Date Submitted</td><td>Submitted By</td><td>Location</td><td>Reviewed By</td></tr><tr><td rowspan=\"2\">Type</td><td colspan=\"3\">Description / Observation</td></tr><tr><td colspan=\"3\">Action / Reinforcement</td></tr></tbody>";
// update various foreign key information from other tables
for ($i=0;$i<$num_rows;$i++) {
$row = $result->fetch_assoc();
$query3 = "select location from locations where locationId='{$row['locationId']}'";
$result3 = $db->query($query3);
$location = $result3->fetch_assoc();
$query3 = "select name from employees where employeeId='{$row['employeeId']}'";
$result3 = $db->query($query3);
$name = $result3->fetch_assoc();
// here is the table itself with the select tag in the null column name=reviewed
$newAppend .= "<tbody><tr><td>{$row['submitDate']}</td><td>{$name['name']}</td><td>{$location['location']}</td><td><form name=\"nearmissreview\" action=\"\" method=\"\"><input type=\"hidden\" name=\"docId\" value=\"{$row['nearmissId']}\"><input type=\"hidden\" name=\"type\" value=\"nearmiss\"><select name=\"reviewed\"><option>Choose name to sign off</option></select></form></td></tr><tr><td rowspan=\"2\">Near Miss</td><td colspan=\"3\">{$row['description']}</td></tr><tr><td colspan=\"3\">{$row['action']}</td></tr></tbody>";
}
$newAppend .= "</table></div>";
// this is the beginning of the second table same structure as first with collapsing but
// different data
$newAppend .= "<p id=\"closeList\">Show/Hide {$num_rows2} Hazard IDs requiring attention.</p><div id=\"closehazardid\" style=\"display:none;\"><table class=\"closehazardidtable\"><tbody><tr><td>Date Submitted</td><td>Submitted By</td><td>Location</td><td>Reviewed By</td></tr><tr><td rowspan=\"2\">Type</td><td colspan=\"3\">Description / Observation</td></tr><tr><td colspan=\"3\">Action / Reinforcement</td></tr></tbody>";
for ($i=0;$i<$num_rows2;$i++) {
$row = $result2->fetch_assoc();
$query3 = "select location from locations where locationId='{$row['locationId']}'";
$result3 = $db->query($query3);
$location = $result3->fetch_assoc();
$query3 = "select name from employees where employeeId='{$row['employeeId']}'";
$result3 = $db->query($query3);
$name = $result3->fetch_assoc();
$newAppend .= "<tbody><tr><td>{$row['submitDate']}</td><td>{$name['name']}</td><td>{$location['location']}</td><td><form name=\"hazardidreview\" action=\"\" method=\"\"><input type=\"hidden\" name=\"docId\" value=\"{$row['hazardidId']}\"><input type=\"hidden\" name=\"type\" value=\"hazardid\"><select name=\"reviewed\"><option>Choose name to sign off</option></select></form></td></tr><tr><td rowspan=\"2\">Hazard ID</td><td colspan=\"3\">{$row['description']}</td></tr><tr><td colspan=\"3\">{$row['action']}</td></tr></tbody>";
}
$newAppend .= "</table></div>";
echo "newAppend='{$newAppend}';";
$result->free();
$result2->free();
$result3->free();
$db->close();
?>
// put HTML of $newAppend php in the DIV
$('#CloseItems').append(newAppend);
// fill the select box with a variable set somewhere else in the code not displayed here
$('#CloseItems select[name=reviewed]').append(newAppendE);
stripePointsTable('.closenearmisstable tbody');
stripePointsTable('.closehazardidtable tbody');
// close list click options
$('#closeList > a').each(function() {
$(this).click(function() {
if ($(this).parent().next().css('display')=='none') {
$(this).parent().next().slideDown('slow');
} else {
$(this).parent().next().slideUp('fast');
}
});
});
// select tag change function that calls ajax and displays a message in a DIV called header
$('#closenearmiss select').change(function() {
function processDataClose(data, success) {
if (success) {
$('#header').prepend(data+"<br />");
closeItemsBtn();
} else {
$('#header').prepend(data+"<br />");
}
}
var formData = $(this).parent().serialize();
$.post('processreviewsign.php',formData,processDataClose);
});

jQuery caches your ajax calls. This is likely why you see the correct result when you refresh the page, but not in subsequent calls via ajax.
Try setting cache: false in your ajax call

Related

Don't query SQL string if value is empty

I have two drop down menu's and when you select a value the value is saved in a session and passed trough AJAX to update a div. I have this working.
The reason I save the value in a session is because I need the database query to be dynamically filled (constructed). At this moment I have the following code:
<?php
$q = $_GET['q'];
$_SESSION['theme'] = $q;
$i = $_SESSION['category'];
$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded WHERE Subcategorie = '".$i."'";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($result);
echo "
<a href='http://example.nl/search/'>" . $row['c'] . "</a>";
?>
This counts all items from $q which is the value of the first drop down menu.
And WHERE Subcategorie = '".$i."', $i is the value from the second drop down menu.
But, now the problem. If the second value is empty (I haven't selected an option from that drop down menu) the query still add's this part to the query, like:
$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded WHERE Subcategorie = ''";.
This makes the count from the first drop down menu always show 0. Is there away to only add the WHERE Subcategorie = '".$i."' when the second drop down menu has a value?
I'm still kind of new to MySQL so please be nice...
Use a query without WHERE clause. Then check if $i is not null, empty or whitespace. If so, add WHERE clause to your query.
$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded";
if($i != "")
$query = $query." WHERE Subcategorie = '".$i."'";

Selecting data from database based on selection from another table

Newby to php / sql so be kind to my ignorance.
On page index.php I have a navigation menu that retrieves options from table car_category, column car_type.
If user selects option from navigation, it takes him to another page where he should see list of entries selected from column car_review_details, coming from another table, car_review.
First function executes on index.php and retrieves the data from table car_category:
function list_type (){
global $conn, $sql, $test;
$test = "SELECT car_type FROM `car_category` WHERE car_type IS NOT NULL AND car_type <> ''";
$result = mysqli_query($conn, $test);
if (!$result){
die("failed");
}
while ($row = mysqli_fetch_assoc($result)){
echo "<a href='car_review.php?subject=";
echo urlencode ($row["car_type"]);
echo "'>";
echo $row ["car_type"];
echo "</a>";
echo "<br>";
}
}
The function above works fine.
Now, on page care_review.php I would like display the data from column car_review_details. The tables car_category and car_review have the column catID which should determine which data gets selected from table car_review, based on the selected link in page index.php
Code for function on page car_review.php looks as following:
function car_style(){
global $conn;
$details = "SELECT *
FROM `car_category`
INNER JOIN `car_review`
ON `car_category`.`catID` = `car_review`.`catID`
WHERE `car_category`.`catID` = $row ['catDesc']";
$result = mysqli_query($conn, $details);
if (!$result){
die("failed");
}
while ($row_1 = mysqli_fetch_assoc($result)){
echo ($row_1["car_review_details"]);
echo "<br>";
}
}
How do I go about echoing data from column car_review_details based on selection from function list_type ().
Many thanks for your feedback.

How to store row for later use when generated element is clicked without updating page?

How can I store the QuestionID of the specific clicked question generated by my query without adding it to the URL as I have done below?
I want to store the QuestionID value so that I can put it into my database with the IP address of my user (no login), without updating the page.
$stmt = $conn->prepare("SELECT * FROM question ORDER BY QuestionVotes DESC LIMIT 4");
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//$row["QuestionID"] to add id to url
echo "<div class=\"col-md-3\"><h2>". $row["QuestionHeader"]. "</h2><p>". $row["QuestionText"]. "</p><p> " . $row["QuestionVotes"] . "</p></div>";
$id = $row["QuestionID"];
}
}
else
{
echo "0 results";
}
Table:
Question: QuestionID (PK), QuestionHeader, QuestionText, QuestionVotes

PHP Dynamic drop down list for deleting rows

I am creating a deletion page for the removal of rows in the database. I have everything working up until the actual removal of the rows upon submit. The records display in the drop down without problem, any ideas of a solution are appreciated. (I am using deprecated SQL, I know.)
1ST PART OF PHP (FORM)
$query = 'SELECT event_name FROM event';
$result = mysql_query($query);
echo "<select name='events' value='-'>\n";
echo "<option value='Select event'>Select an event to be deleted\n";
while($row = mysql_fetch_row($result))
{
$eventSelect = $row[0];
echo "<option value='$eventSelect'>$eventSelect</option>\n";
}
echo "</select>"
2ND PART OF PHP (DELETION)
if (isset($_POST['eventSelect']))
{
$eventselection = $_POST['eventSelect'];
$query = "DELETE FROM event WHERE event_name = '$eventselection'";
$result = mysql_query($query);
}

Sql Query: 2 tables but looking for all information from one and only one row from the other

I have 2 tables
Photos: stores all photo information
Gallery: stores heading and description about the gallery
I need to echo to a new page the Gallery Description, then all the photos that should be there.
but I keep getting heading and description repeating because its in the same
$row = mysql_fetch_array($result)...
then there is more that one set of photos in that gallery I need also?
anyone help or am I being to vague....
$a="SELECT * from gallery where gallery_category=".$gallery_category;
$result = mysql_query($a,$c);
while($row = mysql_fetch_array($result)) {
echo $row['gallery_name'].'<br>'.$row['gallery_description'].'<br>';
$sql="SELECT * FROM photos WHERE gallery_id =".$gallery_id." ORDER BY photos_filename";
$result2 = mysql_query($sql,$c);
while($row = mysql_fetch_array($result2)) {
echo'<a rel="example_group" href="../galleries/images/'.$row['gallery_id'].'/'.$row['photos_filename'].'" width="130" height="100"><img src="../galleries/images/'.$row['gallery_id'].'/'.$row['photos_filename'].'" height="150px" alt=""/></a>';
}
}
Actually I'll post it up here so I can use some code formatting.
Option 1 - loop within a loop
$headerquery = $db->query("SELECT * FROM tbl1");
while ($headers= $db->fetchNextObject($headerquery )) {
echo "<table><tr><th>".$headers->GalleryName."</th></tr>"; // open table create header
$detailquery = $db->query("SELECT * FROM tbl2 WHERE GalleryID=".$headers->ID);
while ($details= $db->fetchNextObject($detailquery )) {
echo "<tr><td>".$details->Photo."</td></tr>"; //loop through 2nd table and spit out photos
}
echo "</table>"; //close table
}
Option 2 - joined query with selector
$galleryheaderid = 0;
$query = $db->query("SELECT * FROM tbl1 INNER JOIN tbl2 on tbl1.ID=tbl2.GalleryID");
while ($details = $db->fetchNextObject($query )) {
echo "<table>";
if ($galleryheaderid!=$details->ID) { //spit out header row if id's don't match
echo "<tr><th>".$details ->GalleryName."</th></tr>"; //create header
$galleryheaderid = $details->ID; //set header id to gallery id so we don't show header a 2nd time
}
echo "<tr><td>".$details->Photo."</td></tr>"; //spit out gallery information even on first row since all rows include photo information
echo "</table>"; //close table
}
Something like either of these should work obviously they'll need completing properly

Categories