I'm trying to update a cross join table which has three columns. The first column studyID will be the same for all the ten row but heuristicID will be 1 to 10 for each row. Third column is h_priority which has only three values either l, m or h. I have retrieved the data and show it inside a table using a while loop in PHP so that all the 10 rows for that particular studyID is shown. The h_priority data is shown inside a select option. When I click the submit button it should update the h_priority column by checking the combination of studyID and heuristicID in the cross join table but for some reason it is not updating anything in the database at the same time "Priority updated successfully" message comes in. Below is the method I used inside the class.
public function updatePriority($studyID, $heuristicID, $h_priority) {
$query = "UPDATE heuristic_priority SET h_priority = ? WHERE studyID = ? AND heuristicID = ?";
$stmt = $this->upc->prepare($query);
$stmt->bind_param("iis", $studyID, $heuristicID, $h_priority);
if ($stmt->execute()) {
return true;
}
else {
return false;
}
}
This is the code for the table
<?php
include_once '../classes/heuristics.php';
$fetchdata=new Heuristic();
$sql=$fetchdata->h_get_priority($passed_studyID);
$cnt=1;
while($row=mysqli_fetch_array($sql))
{
echo '
<tr>
<td id=id'.$cnt.'>
<div class="hide-heuristicid">
<input type="text" name="studyid[]" value="'.$row['studyID'].'" required>
</div>
</td>
<td id=id'.$cnt.'>
<div class="hide-heuristicid">
<input type="text" name="heuristicid[]" value="'.$row['heuristicID'].'" required>
</div>
</td>
<td id=id'.$cnt.'>
<div>
'.$row['h_title'].'
</div>
</td>
<td id=name'.$cnt.'>
<div>
<select name="priority[]">
<option value="'.$row['h_priority'].'" '.($row['h_priority'] == 'l' ? 'selected' : '').'>Low</option>
<option value="'.$row['h_priority'].'" '.($row['h_priority'] == 'm' ? 'selected' : '').'>Medium</option>
<option value="'.$row['h_priority'].'" '.($row['h_priority'] == 'h' ? 'selected' : '').'>High</option>
</select>
</div>
</td>
</tr>
';
}
?>
This is the PHP code
if (isset($_POST['submit'])) {
$studyID = isset($_POST['studyID[]']) ? $_POST['studyID[]'] : '';
$heuristicID = isset($_POST['heuristicID[]']) ? $_POST['heuristicID[]'] : '';
$h_priority = isset($_POST['h_priority[]']) ? $_POST['h_priority[]'] : '';
$updatePriority = new Heuristic();
if ($updatePriority->updatePriority($studyID, $heuristicID, $h_priority)) {
echo "Priority updated successfully";
}
else {
echo "Failed to update priority";
}
}
Related
How to get the value from a drop-down menu list to insert value in db?
My system has 18 holes, users can update the hole value data according to their needs. So how to detect select which hole and update the data in my db?
This is the code
<?php
$result = '';
$doUpdate = isset($_POST['updateButton_x']);
if ($doUpdate) {
$stmtSetParams = $stmtInParams = array();
$validationOptions = array('options' => array('min_range' => 1, 'max_range' => 5));
//Define statement and parameters (Assuming dB field 'item' is the primary key).
$set = '`Hole1` = CASE `Item` ';
foreach ($_POST['Evaluate'] as $Item => $Hole1) {
//Get input value of each table row
if (filter_var($Hole1, FILTER_VALIDATE_INT, $validationOptions) !== false) {
//Field is not blank
$set .= 'WHEN ? THEN ? ';
$stmtSetParams[] = $stmtInParams[] = $Item;
$stmtSetParams[] = $Hole1;
} else {
//Field is not an integer from 1 to 5
$result .= "Field \'Evaluate\' of item \'$Item\' with a value of \'$Hole1\' is not from 1 to 5 and skipped while saving!\\n";
}
}
$set .= 'END';
//Define query placeholders
$placeHolders = implode(', ', array_fill(0, count($stmtInParams), '?'));
$query = <<<SQL
UPDATE `details` SET $set WHERE `Item` IN ($placeHolders)
SQL;
}
//Query the dB.
try {
$dbh = new PDO('mysql:host=localhost;dbname=gcmes', 'root');
if ($doUpdate) {
//Update requested. Prepare and execute update query
$stmt = $dbh->prepare($query);
$stmt->execute(array_merge($stmtSetParams, $stmtInParams));
$result .= 'Update Completed!';
}
//Query for en fetch (updated) table data
$stmt = $dbh->query("SELECT * FROM `details`");
$tableData = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
//A PDO exception is raised
$result = 'Error: ' . addslashes($e->getMessage());
}
//Alert results of database operations
if ($result != '') {
echo "<script>alert('$result')</script>";
}
?>
<form id="form1" name="chooseFormNameIfNeeded" method="post" action="Job.php">
<!-- attribute align is deprecated, define and use a class instead -->
<table class="info" align="center">
<tr>
<!-- use th instead of td for table header -->
<!-- using <b> tag is discouraged -->
<th width="10"><b>Item</b></th>
<th width="100"><b>Category</b></th>
<th width="100"><b>Job</b></th>
<th width="30"><b>Frequency</b></th>
<th width="10"><b>Hole</b></th>
<th width="30"><b>Evaluate</b></th>
</tr>
<?php
foreach ($tableData as $rowData) {
//Print a table row for each of the fetched records
echo <<<HTML
echo <<<HTML
<tr>
<td>{$rowData['Item']}</td>
<td>{$rowData['Category']}</td>
<td>{$rowData['Job']}</td>
<td>{$rowData['Frequency']}</td>
<td><select name="hole">
<option value="Hole1">1</option>
<option value="Hole2">2</option>
<option value="Hole3">3</option>
<option value="Hole4">4</option>
<option value="Hole5">5</option>
<option value="Hole6">6</option>
<option value="Hole7">7</option>
<option value="Hole8">8</option>
<option value="Hole9">9</option>
<option value="Hole10">10</option>
<option value="Hole11">11</option>
<option value="Hole12">12</option>
<option value="Hole13">13</option>
<option value="Hole14">14</option>
<option value="Hole15">15</option>
<option value="Hole16">16</option>
<option value="Hole17">17</option>
<option value="Hole18">18</option>
</select>
<td>
<!-- Assuming dB field 'item' is the primary key. -->
<input type="number" name="Evaluate[{$rowData['Item']}]" id="Evaluate" value="{$rowData['Hole1']}"
min=1 max=5>
</td>
</tr>
HTML;
}
?>
</table>
User can choose any hole to insert the marks
Hole is one of the column in my db
Anyone please help, thank you!
I have listed all the data(Item, Category, Job, Hole(Hole is evaluating marks)) and I display the Hole(mark) in textbox filed.
I want to update the Hole(marks) after user change.
I list all the data using php
<?php
try{
$con = new PDO("mysql:host=localhost;dbname=gcmes", "root", "");
$sql = $con->query("SELECT * FROM details");
echo"<table class='info' align='center'>";
echo"<tr><td width='10'><b>No</b></td>
<td width='30'><b>Category</b></td>
<td width='50'><b>Job</b></td>
<td width='40'><b>Evaluate</b></td><tr>";
foreach($sql as $row) {
$Item = $row["Item"];
$Category = $row["Category"];
$Job = $row["Job"];
$Evaluate = $row["Hole 1"];
echo'
<tr>
<td>' . $Item . '</td>
<td>' . $Category . '</td>
<td>' . $Job . '</td>
<td><input type="input" name="Evaluate" id="Evaluate" value="' . $Evaluate . '">
</td>
</tr>
';
}
echo"</table></form>";
if(isset($_POST['Update_btn'])){
$Evaluate = $_POST["Hole 1"];
if(empty(Evaluate)){
echo "<script type='text/javascript'>alert('Please fill in the required fields to update!')</script>";
}
else{
$insert=$con->prepare("UPDATE details SET Evaluate=:Hole 1 WHERE Item=:Item");
$insert->bindParam(':Hole1',$Evaluate);
$insert->bindParam(":Item",$Item);
$insert->execute();
echo "<script type='text/javascript'>alert('Successful Updated ! ');
window.location.href = 'Hole 1.php';
</script>";
}//else
}//if add button
}//try
catch(PDOException $e)
{
echo "error".$e->getMessage();
}
?>
The html code i just use to display button
<form id="form1" name="Hole 1" method="post" action="Hole 1.php">
<input name="Update_btn" type="image" id="Update_btn" onmouseover="this.src='UpdateO.png'" onmouseout="this.src='UpdateD.png'" value="submit" src="UpdateD.png" alt="submit Button" align="right">
</form>
The problem is will alert message successful updated BUT the value not update in my db. Why? what is the problem?
this is my interface
i want update the marks in textbox filed
I need to change the hole as a selection give the user choose which hole that need to update only, i set the hole have a drop-down menu list. How to dectect which hole?
i just add the code after <td>{$rowData['Frequency']}</td> (dn Fer answer)
<td><select name="hole">
<option value="Hole1">1</option>
<option value="Hole2">2</option>
<option value="Hole3">3</option>
<option value="Hole4">4</option>
<option value="Hole5">5</option>
<option value="Hole6">6</option>
<option value="Hole7">7</option>
<option value="Hole8">8</option>
<option value="Hole9">9</option>
<option value="Hole10">10</option>
<option value="Hole11">11</option>
<option value="Hole12">12</option>
<option value="Hole13">13</option>
<option value="Hole14">14</option>
<option value="Hole15">15</option>
<option value="Hole16">16</option>
<option value="Hole17">17</option>
<option value="Hole18">18</option>
</select>
Keep the following in mind:
I don't have the same environment as yours, so it might not work one
on one.
Spaces in database fieldNames and arrayKeys, etc. are discouraged. I
prefer to use lowerCamelCase, check if dB fieldNames match the code
below!
Read the comments I've placed in the code.
I didn't take psr coding, value validation or safety (sql injection), etc. in consideration. The code is to guide you, you should take these things in consideration yourself.
Hopefully getting you closer to your goals...
Update: The values of the Evaluate field of each row is now validated to be an integer in the range from 1 to 5.
<?php
//Initialize variables
$result = '';
$doUpdate = isset($_POST['updateButton_x']);
//Because button type is 'image', we get parameters buttonName_x and buttonName_y
//from the browsers POST request when the form is sent.
if ($doUpdate) {
//Update button pressed.
//Initialize variables
$stmtSetParams = $stmtInParams = array();
$validationOptions = array('options' => array('min_range' => 1, 'max_range' => 5));
//Define statement and parameters (Assuming dB field 'item' is the primary key).
$set = '`hole1` = CASE `item` ';
foreach ($_POST['evaluate'] as $item => $hole1) {
//Get input value of each table row
if (filter_var($hole1, FILTER_VALIDATE_INT, $validationOptions) !== false) {
//Field is not blank
$set .= 'WHEN ? THEN ? ';
$stmtSetParams[] = $stmtInParams[] = $item;
$stmtSetParams[] = $hole1;
} else {
//Field is not an integer from 1 to 5
$result .= "Field \'Evaluate\' of item \'$item\' with a value of \'$hole1\' is not from 1 to 5 and skipped while saving!\\n";
}
}
$set .= 'END';
//Define query placeholders
$placeHolders = implode(', ', array_fill(0, count($stmtInParams), '?'));
$query = <<<SQL
UPDATE `details` SET $set WHERE `item` IN ($placeHolders)
SQL;
}
//Query the dB.
try {
$dbh = new PDO('mysql:host=localhost;dbname=gcmes', 'root');
if ($doUpdate) {
//Update requested. Prepare and execute update query
$stmt = $dbh->prepare($query);
$stmt->execute(array_merge($stmtSetParams, $stmtInParams));
$result .= 'Update Completed!';
}
//Query for en fetch (updated) table data
$stmt = $dbh->query("SELECT * FROM `details`");
$tableData = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
//A PDO exception is raised
$result = 'Error: ' . addslashes($e->getMessage());
}
//Alert results of database operations
if ($result != '') {
echo "<script>alert('$result')</script>";
}
?>
<form id="form1" name="chooseFormNameIfNeeded" method="post" action="test.php">
<!-- attribute align is deprecated, define and use a class instead -->
<table class="info align-center">
<tr>
<!-- use th instead of td for table header -->
<!-- using <b> tag is discouraged -->
<th width="10"><b>No</b></th>
<th width="30"><b>Category</b></th>
<th width="50"><b>Job</b></th>
<th width="40"><b>Evaluate</b></th>
</tr>
<?php
foreach ($tableData as $rowData) {
//Print a table row for each of the fetched records
echo <<<HTML
<tr>
<td>{$rowData['item']}</td>
<td>{$rowData['category']}</td>
<td>{$rowData['job']}</td>
<td>
<!-- Assuming dB field 'item' is the primary key. -->
<input type="number" name="evaluate[{$rowData['item']}]" id="Evaluate" value="{$rowData['hole1']}"
min=1 max=5
>
</td>
</tr>
HTML;
}
?>
</table>
<!-- Attribute align is deprecated, define and use a class instead -->
<!-- Value attribute should not be specified -->
<input name="updateButton" type="image" id="Update_btn" src="http://via.placeholder.com/100x50/0000FF?text=Update"
alt="submit Button" class="align-right"
onmouseover="this.src='http://via.placeholder.com/100x50/00FF00?text=Update'"
onmouseout="this.src='http://via.placeholder.com/100x50/0000FF?text=Update'"
>
</form>
This "page" is part of many that are all linked together using includes, but because I can't make it work I'm going straight to the url that relates to this exact page, and I still can't make it work, or figure out why.
What is supposed to happen, is the query checks if that stock is in the db, if it is, echo the values of the row, and if a submit button is pressed update the db based on the input values. If it's not in, echo the blank form, and if a submit button gets pressed insert into the db. I can't get either update or insert to work.
I'm going to post the entire page (minus the mysql connect,) so hopefully someone can spot an error.
<?php
$status = 'Active';
$stock = (isset($_GET['stock'])) ? $_GET['stock'] : '';
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : '';
include ('../helper_content/title_data.php');
/* WHAT CATEGORY DO WE WANT? */
if($cat == "Sales") {
$table = "Titles";
if($stock) {$where = "stock = $stock";}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$status = $status;
$title_status = mysqli_real_escape_string($conn,$_POST['title_status']);
$title_number = mysqli_real_escape_string($conn,$_POST['title_number']);
$title_location = mysqli_real_escape_string($conn,$_POST['title_location']);
$title_owners = mysqli_real_escape_string($conn,$_POST['title_owners']);
$stock = $_GET['stock'];
}
}
/* Begin Main Query */
$sql5 = "SELECT * FROM `$table` WHERE $where";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
// Stock exists, so submit will Update dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($update = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$update->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$update->execute();
};
if ($update->execute == TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating: " . $update->error;
}
}
// Display the HTML results
while($row5 = $result5->fetch_assoc()) {
echo "Found In Database";
// Title Number
$title_number = 'value="'.$row5['title_number'].'"';
$TitleStatus = $row5['title_status'];
$TitleLocation = $row5['title_location'];
$Owners = $row5['owners'];
}
} else {
// No Query Results Found
echo "Not Found In Database";
// Insert into dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($add = $conn->prepare("INSERT INTO `Titles` status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$add->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$add->execute();
};
if ($add->execute == TRUE) {
echo "Record added into database";
} else {
echo "Error adding: " . $add->error;
}
}
/* End Main Query */
}
// Title Status
foreach($title_statuses as $title_status){
$selected = ($TitleStatus == $title_status) ? ' selected="selected"' : '';
$Title_status .= '<option value="'.$title_status.'"'.$selected.'>'.$title_status.'</option>';
}
// Title Location
foreach($title_locations as $title_location){
$selected = ($TitleLocation == $title_location) ? ' selected="selected"' : '';
$Title_location .= '<option value="'.$title_location.'"'.$selected.'>'.$title_location.'</option>';
}
// Prior Owners
foreach($prior_owners as $owners){
$selected = ($Owners == $owners) ? ' selected="selected"' : '';
$Owners_drop .= '<option value="'.$owners.'"'.$selected.'>'.$owners.'</option>';
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>?stock=<?php echo $stock; ?>">
<section class="title">
<h3>Title Info - Stock #:<?php echo $stock; ?></h3>
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" <?php echo $title_number; ?>>
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php echo $Title_status; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<?php echo $Title_location; ?>
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<?php echo $Owners_drop; ?>
</select> <a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=<?php echo $vin; ?>"><i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i></a>
</p>
</section>
<input type="submit" id="Submit" value="Submit">
</form>
I would start by organizing your code a little differently. You have one of two things that can be true: either the form was submitted (a POST request), or the page was requested via URL (a GET request). So, start with this:
<?php
# Data for dropdowns
include ('../helper_content/title_data.php');
$error = array();
$status = "Active";
$title_number = "";
$title_status = "";
$title_location = "";
$title_owners = "";
$vin = "";
# Was the form submitted via POST?
if(isset($_POST['Submit']))
{
# Yes
# Is this a new stock item?
if(empty($_POST['stock']))
{
# Yes - insert
/*
... get your variables from the $_POST array
*/
$title_number = filter_var($_POST['title_number'], FILTER_SANITIZE_STRING);
# ... repeat for other variables
if ($stmt = $conn->prepare("INSERT INTO `Titles` (`status`,`title_status`,`title_number`,`title_location`,`title_owners`) VALUES (?,?,?,?,?)"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?inserted=true');
exit();
}
else
{
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
}
else
{
# No - update
$stock = $_POST['stock'];
/*
... get your variables from the $_POST array
*/
if ($stmt = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else
{
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated']))
{
$message = "Record updated";
}
else if(isset($_GET['inserted']))
{
$message = "Record added into database";
}
if($stock != "")
{
# Load the item?
$query = "SELECT * FROM `Sales` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $stock);
if($stmt->execute())
{
$result = $stmt->get_result();
if($result)
{
$row = $result->fetch_assoc();
$title_number = $row['title_number'];
$title_status = $row['title_status'];
$title_location = $row['title_location'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<section class="title">
<h3>Title Info - Stock #:<?= $stock; ?></h3>
<input type="hidden" name="stock" value="<?= $stock; ?>" />
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" value="<?= $title_number; ?>" />
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php foreach($title_statuses as $option): ?>
<option <?= $option == $title_status) ? 'selected="selected"' : '' ?>><?= $option ?></li>
<?php endforeach; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
<a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=$vin">
<i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i>
</a>
</p>
</section>
<input type="submit" id="Submit" value="Submit" />
</form>
Here's a partial re-implementation of your page. I'm starting with the assumption that a stock number was part of the requesting URL, and looking that value up. I (for the moment) am ignoring loading the dropdown values in favor of getting a basic lookup to work.
You'll also notice I've switched to using shorttags in your markup - this is generally a more concise method of templating than sprinkling echos all over the place.
I've added a partial implementation of some save logic. You'll also notice that I added a hidden input to your form - you don't want to rely on a query string value when posting a form.
The code stores some simple error messages in an array, which gets echoed out if the insert or update fails. If successful, we redirect back to the same page with a simple flag variable, which we read on that request to know if we need to display an informational message. This is known as POST-REDIRECT-GET, and prevents users from accidentally (or purposefully) resubmitting the same form data over and over.
I want to run 2 different INSERT queries on the dropdown select option
If user selects option 1 the Insert Query for Table 1 runs.
When the user selects option 2 the other Insert query for Table 2 runs.
<?php
if(isset($_POST['submit_form']) && isset($_POST['listings'])) {
switch ($listings) {
case 'GradeA':
$stmt = "INSERT INTO Packing_listA (Country, Total_bales) VALUES ('$Country' , '$Total_bales')";
break;
case 'GradeB':
$sql = "INSERT INTO Packing_listB (Country, Total_bales) VALUES ('$Country' , '$Total_bales')";
break;
}
if ($mysqli->query($stmt) || $mysqli->query($sql) === TRUE) {
$last_id = $mysqli->insert_id;
$_SESSION['ct_id'] = $last_id;
echo "<p>New record created successfully. Last inserted ID is: '". $last_id."'</p>";
echo "<script>setTimeout('delayer()', 1000)</script>";
}
} ?>
And the HTML is
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" class="form" role="form">
<select style="font-size:1.5em; height:45px;" class="form-control" name="listings" >
<option>Choose Color</option>
<option value="GradeA" <?php if($listings == "GradeA") print('selected="selected"'); ?>>GradeA</option>
<option value="GradeB" <?php if($listings == "GradeB") print('selected="selected"'); ?>>GradeB</option>
</select>
<div class="form-group">
<center>
<button style="height:45px; font-weight:bold;" name="submit_form" class="form-control btn btn-lg btn-info">
Next
</button>
</center>
</div>
</form>
But I am open to any other method Like Radio Buttons or If, Else condition or anything that works.
When the option 1 is selected only associated Query will run and vice versa.
First, I'll go for something like this :
if (isset($_POST['submit_form']) && isset($_POST['listings'])) {
$sql = "INSERT INTO "
."Packing_list".($_POST['listings'] == 'GradeA'? 'A' : 'B')
."(Country, Total_bales)"
."VALUES ('$Country' , '$Total_bales')";
if ($mysqli->query($sql)) {
$_SESSION['ct_id'] = $mysqli->insert_id;
echo "<p>New record created successfully. Last inserted ID is: '".$_SESSION['ct_id'].
"'</p>";
echo "<script>setTimeout('delayer()', 1000)</script>";
}
}
Second , I think you can make a better code (strange think in this one...)
I'm making a dropdown menu with information out of my database. It has to get different brands in my dropdown and when selecting a brand and submit search it will show information about that brand. It gets the brands correct from the database but after submit it only shows my last brand. Can somebody help me out... Here is my dropdown menu and search (submit) code:
<div class="bandwielkolom">
<form action="index.php?lang=nl&p=<?php echo $_GET['p']; ?>#keuze" method="post">
<table class="bandentabel">
<tr>
<th colspan="2">Op merk zoeken<a name="band"></a></th>
</tr>
<tr>
<td>Merk:</td>
<td>
<select name="band_merk">
<option value="0">- Merk -</option>
<?php
$wielen = $wielclass->getMerkenWielen($website);
foreach($wielen as $wiel)
{
echo "\t\t\t\t\t\t\t\t\t\t\t<option value=\"".$wiel->merk_code."\"";
if(isset($_GET['search']) && $_GET['search'] == "band" && isset($_GET['wiel']) && $_GET['wiel'] == $wiel->merk_code || isset($_POST['band_submit']) && $_POST['band_merk'] == $wiel->merk_code) { echo " selected=\"selected\""; }
echo ">".$wiel->merk_naam."</option>\n";
}
?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="band_submit" value="Zoek"/></td>
</tr>
</table>
</form>
</div>
This is my class:
Class:
<?php
class wielen extends connect {
private $wielenlijst;
public function getMerkenWielen($database) {
$sql = "SELECT * FROM ".$database."_wielen ORDER BY merk_nummer";
try {
$stmt = $this->db->prepare($sql);
$stmt->execute();
$this->wielenlijst = $stmt->fetchAll(PDO::FETCH_OBJ);
$stmt->closeCursor();
return $this->wielenlijst;
}
catch (Exception $e) {
die ($e->getMessage());
}
}
public function __construct($dbo) {
parent::__construct($dbo);
}
}
?>
This only show the last brand after submit:
<?php
if(isset($_POST['band_submit']))
echo $wiel->merk_naam;
?>
Can somebody help me with this because I cant get it to work
Maybe a fresh look at it will help
thnx for any help
UPDATE:
I got this peace of code now and I will explain what is happening and what I want:
<div class="bandwielkolom">
<form action="index.php?lang=nl&p=<?php echo $_GET['p']; ?>#keuze" method="post">
<table class="bandentabel">
<tr>
<th colspan="2">Op merk zoeken<a name="band"></a></th>
</tr>
<tr>
<td>Merk:</td>
<td>
<select name="band_merk">
<option value="0">- Merk -</option>
<?php
$wielen = $wielclass->getMerkenWielen($website);
$get_wiel = isset($_GET['wiel']) ? $_GET['wiel'] : '';
$post_wiel = isset($_POST['band_merk']) ? $_POST['band_merk'] : '';
foreach($wielen as $wiel) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$selected = $post_wiel['wiel'] === $wiel->merk_code ? ' selected="selected"' : '' ;
}
else {
$selected = $get_wiel['wiel'] === $wiel->merk_code ? ' selected="selected"' : '' ;
}
echo '\t\t\t\t\t\t\t\t\t\t\t<option value="' . $wiel->merk_code . '"' . $selected . '>' . $wiel->merk_naam . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="band_submit" value="Zoek"/></td>
</tr>
</table>
</form>
</div>
<?php
if(isset($_POST['band_submit']) && $_POST['band_merk'] == $wiel->merk_code)
echo $wiel->merk_naam;
?>
Precess code:
if(isset($_POST['band_submit']) && $_POST['band_merk'] == $wiel->merk_code)
echo $wiel->merk_naam;
I get a selectbox with four options out of my database so that is working correct. These options has data in it like a picture and text. When I select one and press submit he has to show the information of the selected option and that should stay selected.
What is happening now is that when I select a option and press submit nothing happens... The button is working but I dont get any output of the selected option and it wont stay selected.
Doing something wrong but I cant figure out what
Any help is welcome:)
You need to use your for loop again to list them all.
foreach($wielen as $wiel)
{
echo $wiel->merk_naam;
}