i have table service in database db.
it has 3 fields
id,
service_type,
amount.
i have html form which has checkbox to select service type,i got service type selected but amount must be calculated auto and store in database amount column. but one error when i select service from checkbox it is selected and store in database but price is not stored.
my script is as follow:
<input type="checkbox" name="services[]" value="oilchange"
<input type="checkbox" name="services[]" value="acrepair"
<input type="checkbox" name="services[]" value="tyrechange"
<input type="submit" name="btnservice" value="Confirm Services">
now php script is as follow:
<?php $price=0.0;if (isset($_POST['services'])) {
$service=$_POST['services'];
$c=count($service);
for ($i=0; $i < $c; $i++) {
if ($service[$i]==fullservice) {
$price=$price+5000;
$iq="INSERT INTO tblservices( amount) VALUES ('$price')";
$run=mysqli_query($con,$iq);
if ($run) {
}
}
elseif ($service[$i]==tyrebalance) {
# code...
$price=$price+4000;
$iq="INSERT INTO tblservices( amount) VALUES ('$price')";
$run=mysqli_query($con,$iq);
if ($run) {
}
}
elseif($service[$i]==oilchange) {
# code...
$price=$price+3000;
$iq="INSERT INTO tblservices( amount) VALUES ('$price')";
$run=mysqli_query($con,$iq);
if ($run) {
}
}
elseif ($service[$i]==acrepair) {
# code...
$price=$price+2000;
$iq="INSERT INTO tblservices( amount) VALUES ('$price')";
$run=mysqli_query($con,$iq);
if ($run) {
}
}
elseif ($service[$i]==tyrechange) {
# code...
$price=$price+1000;
$iq="INSERT INTO tblservices( amount) VALUES ('$price')";
$run=mysqli_query($con,$iq);
if ($run) {
}
}
}
}if (isset($_POST['btnservice'])) {
$a=$_POST['services'];
$type=implode("/",$a);
$query="insert into tblservices(service_type,amount) values('$type','$price')";
$run=mysqli_query($con,$query);
if ($run) {
echo "<script type = \"text/javascript\">
alert(\"Services Selected.................\");
window.location = (\"services.php\")
</script>";
}
else{
echo "<script type = \"text/javascript\">
alert(\"Login Failed. Try Again................\");
window.location = (\"services.php\")
</script>";
}
}?>
i'm new guys sorry that's why i cann't upload images i need to earn reputations so i could able to post images for better or detailed explanation of my question.
i could see two type of queries in your sample.
Sharing here single service types insertion and insertion with total price. Hope this helps!!
<div class="container">
<form action="" method="post">
<input type="checkbox" name="services[]" value="oilchange" />oilchange
<input type="checkbox" name="services[]" value="acrepair" />acrepair
<input type="checkbox" name="services[]" value="tyrechange" />tyrechange
<br/>
<input type="submit" name="btnservice" value="Confirm Services">
</form> <?php
$serviceChargeArr = array(
'fullservice' => 5000,
'tyrebalance' => 4000,
'oilchange' => 3000,
'acrepair' => 2000,
'tyrechange' => 1000
);
$priceTotal = 0.0;
if (isset($_POST['btnservice'])) {
if (isset($_POST['services'])) {
$serviceArr = $_POST['services'];
$serviceArrCnt = count($serviceArr);
//QUERY 1 - insert each with respect to clicked checkboxes
for ($i = 0; $i < $serviceArrCnt; $i++) {
if ($eachPrice = $serviceChargeArr[$serviceArr[$i]]) {
$insertArr[] = "('$serviceArr[$i]', '$eachPrice')";
}
}
if (!empty($insertArr)) {//sigle insert query -each service and its price will be inserted
$query="insert into tblservices (service_type, amount)
values".implode(", ",$insertArr ).";";
echo $query."<br/>";
}//QUERY 1 ENDS
//QUERY 2 - insert single row with comma separated values and total price
for ($i = 0; $i < $serviceArrCnt; $i++) {
if ($eachPrice = $serviceChargeArr[$serviceArr[$i]]) {
$priceTotal += $eachPrice;
}
}
if (!empty($serviceArr)) {
$seviceList = implode(',', $serviceArr);
$query="insert into tblservices (service_type, amount)
values ('{$seviceList}' , '{$priceTotal}') ;";
echo $query."<br/>";
}//QUERY 2 ENDS
if($query) {
$run = mysqli_query($con, $query);
if ($run) {
echo "<br/> SUCCESS : inserted";
} else {
echo "<br/> ERROR : try again<br/>Mysql Error: ".$con->error;
}
}
}
} ?>
</div>
Related
I want to display checked checkbox which are stored as values in a mysql database.
For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.
Here's the code for inserting the data.
$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table table-hover">
<thead>
<?php
echo '<tr><th>Goals</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
for ($y = 0; $y < count($goals); $y++) {
echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>
</tr>';
?>
<?php
for( $z = 0; $z < count($mainobj); $z++){
if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>
</tr>';
?>
<?php
for ($j = 0; $j< count($subobj); $j++) {
if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
}
echo '</tr>';
}
}
}
}
}
?>
</tbody>
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>
</form>
report-functions.php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql= " insert into `Report` (`ColRow`) values (:value) ";
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
echo '
<script>
alert("Error, please try submitting again. Error code 1");
window.history.back();
</script>';
}
}
$conn->commit();
echo '<script>
alert("Report was submitted successfully.");
window.location = ".../";
</script>';
}
} catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.
Please comment if I need to provide any additional information.
When you display your page (in your first section of code), at some point you do this:
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
The value is set to:
value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";
This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).
Right. So before you do that echo, add a new if condition.
$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
$checked_code = "checked=\"checked\"";
}
else {
$checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";
The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):
function verify_checked($value)
{
// Connect to the database if needed
// Perform: SELECT count($value) FROM Report
// If the result is >0, return TRUE
// Else return FALSE
}
The idea here is to query the database every time your are about to echo the <input> element.
Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.
code:
<script>
$(document).ready(function(){
$(".choose").click(function(){
job_type = $(':checked').map(function() {
return this.value;
}).get().join(',');
category = $("#cat_gory").val();
$.ajax({
type:"POST",
data:{"job_type":job_type,"category":category},
url:"type-jobs.php",
success:function(data){
$(".success").html(data);
}
});
});
});
</script>
<input type="hidden" name="cat_gory" id="cat_gory" value="<?php echo $job_category; ?>" />
<p class="flchek">
<input type="checkbox" name="choosetype" value="freelance" class="choose" id="33r">
<label for="33r">Freelance</label>
</p>
<p class="ftchek">
<input type="checkbox" name="choosetype" value="full time" class="choose" id="dsf">
<label for="dsf">Full Time</label>
</p>
<p class="ischek">
<input type="checkbox" name="choosetype" value="internship" class="choose" id="sdd">
<label for="sdd">Internship</label>
</p>
<div class="success"></div>
type-jobs.php
<?php
include("config.php");
$job_category = mysqli_real_escape_string($con,$_POST['category']);
$job_type = mysqli_real_escape_string($con,$_POST['job_type']);
$tag = explode(",",$job_type);
foreach($tag as $type)
{
$sql_job = mysqli_query($con,"select p.job_title,c.state,c.city from company c inner join jobs p on p.company_name = c.company_name where p.category = '".$job_category."' and job_type='".$type."'");
$result_job = mysqli_num_rows($sql_job);
if($result_job > 0)
{
while($row_jobs = mysqli_fetch_array($sql_job))
{
echo '<h3>'.$row_jobs['job_title'].'</h3>';
}
}
else
{
echo '<p id="c_mm">record not found</p>';
}
}
?>
In this code I have multiple checkbox. Now, When I click on checkbox to get data through jquery/ajax it return data to me but the problem is if I click on freelance checkbox it show me record not found again when I click on full time then it showing record not found as well as jobs. Now, I want if data was not found in my database it will show single message to me and if data found then hide message and show database record. So, How can I do this? Please help me.
Thank You
NO need to explode the $jobtype Use 'jobtype IN('.$jobtype.') '
<?php
include("config.php");
$job_category = mysqli_real_escape_string($con,$_POST['category']);
$job_type = mysqli_real_escape_string($con,$_POST['job_type']);
$sql_job = mysqli_query($con,"select p.job_title,c.state,c.city from company c inner join jobs p on p.company_name = c.company_name where p.category = '".$job_category."' and job_type IN('".$jobtype."') ');
$count = mysqli_num_rows($sql_job);
$row_data = mysqli_fetch_array($chek_result);
if($count > 0){
foreach($row_data as $data){
$message = '<h3>'.$data['job_title'].'</h3>';
}
}else{
$message = "No Data found";
}
echo $message;exit;
?>
If you want to show record not found message only if you don't find any record then you can use a flag in php something like this:
<?php
include("config.php");
$job_category = mysqli_real_escape_string($con,$_POST['category']);
$job_type = mysqli_real_escape_string($con,$_POST['job_type']);
$found = 0;
$message = '';
$tag = explode(",",$job_type);
foreach($tag as $type)
{
$sql_job = mysqli_query($con,"select p.job_title,c.state,c.city from company c inner join jobs p on p.company_name = c.company_name where p.category = '".$job_category."' and job_type='".$type."'");
$result_job = mysqli_num_rows($sql_job);
if($result_job > 0)
{
$found = 1;
while($row_jobs = mysqli_fetch_array($sql_job))
{
$message .= '<h3>'.$row_jobs['job_title'].'</h3>';
}
}
}
if(found == 0) {
$message = '<p id="c_mm">record not found</p>';
}
echo message;
?>
Notice $found flag here in code. HTH.
I'm making a form where i have to insert in my dB several values from a checkbox btn group into different columns. I also have to insert two different values depending if the btn is checked or not.
I made it work in the following way, but is there another way for this became more simple? It´s a lot of issets :).
Thanks for your time.
Best regards!
NM
<?php
if(isset($_POST["submit"])){
// Create connection
include ('connection.php');
if(isset($_POST['fixvalue']) && ($_POST['fixvalue'] == 0)) {
$fixvalue= "fixvalue";
} else {
$fixvalue= 0;
};
if(isset($_POST['frtvalue']) && ($_POST['frtvalue'] == 0)) {
$valueone= "valueone";
} else {
$valueone= 0;
};
if(isset($_POST['secvalue']) && ($_POST['secvalue'] == 0)) {
$valuetwo= "valuetwo";
} else {
$valuetwo= 0;
};
if(isset($_POST['thevalue']) && ($_POST['thevalue'] == 0)) {
$valuethree= "valuethree";
} else {
$valuethree= 0;
};
if(isset($_POST['fovalue']) && ($_POST['fovalue'] == 0)) {
$valuefour= "valuefour";
} else {
$valuefour= 0;
};
if(isset($_POST['fitvalue']) && ($_POST['fitvalue'] == 0)) {
$valuefive= "valuefive";
} else {
$valuefive= 0;
};
$sql = "INSERT INTO values(fixvalue,valueone,valuetwo,
valuethree,valuefour,valuefive)
VALUES('".$fixvalue."','".$valueone."','".$valuetwo."',
'".$valuethree."','".$valuefour."','".$valuefive."')";
if ($con->query($sql) === TRUE) {
echo'<button class="btn btn-success" style="left:400px;bottom:20px;width:200px;">Sucess</button>';
echo "<script type= 'text/javascript'>alert('New record OK');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" $con->error."');</script>";
}
$con->close();
}
?>
Here's what I would do:
<form action="" method="post">
<input type="checkbox" name="fixvalue"> Checkbox<br>
<input type="checkbox" name="valueone"> Checkbox 1<br>
<input type="checkbox" name="valuetwo"> Checkbox 2<br>
<input type="checkbox" name="valuethree"> Checkbox 3<br>
<input type="checkbox" name="valuefour"> Checkbox 4<br>
<input type="checkbox" name="valuefive"> Checkbox 5<br>
<input type="submit" name="submit">
</form>
<?php
$fields = [
'fixvalue' => 0,
'valueone' => 0,
'valuetwo' => 0,
'valuethree' => 0,
'valuefour' => 0,
'valuefive' => 0
];
if($_POST['submit']){
foreach($_POST as $key => $value) {
if($key !== 'submit') {
$fields[$key] = $key;
}
}
extract($fields);
$sql = $db->prepare("INSERT INTO table_name (fixvalue, valueone, valuetwo, valuethree, valuefour, valuefive) VALUES(:fixvalue, :valueone, :valuetwo, :valuethree, :valuefour, :valuefive)");
foreach ($fields as $key => $value) {
$sql->bindValue(':'.$key, $$value);
}
$sql->execute();
}
?>
$checks = array(
'fixvalue',
'frtvalue',
'secvalue',
'thevalue',
'fovalue',
'fitvalue'
);
$data = array();
foreach( $checks as $value){
$data[$value] = isset($_POST[$value]) && $_POST[$value] != '' ? $_POST[$value] : 0;
}
Than use $data['frtvalue'] etc in a prepared sql statement
This question already has answers here:
Best way to INSERT many values in mysqli?
(4 answers)
Closed 2 years ago.
I need to insert entries to mysql table from the form below.
1-form contains many rows.
2-entry will not be always consecutive in the rows (meaning row 1 can be empty and next row not)
3-all rows containing entries should be saved in the db table.
i want to INSERT INTO oz2ts_custompc_details (part_id, quantity, price)
Here is my entry form (custompc_form2.php)
<!DOCTYPE html>
<html>
<body>
<form action="../subs/custompcorder2.php/" method="post" id="form">
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<input id="submit" type="submit" value="Submit Order" name="submission"/>
</form>
</body>
</html>
here is What I came up with but still not working.
here is the summary of how it is working: ||Rows 1 to 4 has data > all 4 are saved || row 1 is empty and rows 2 to 3 contains data > only rows 2 and 3 are saved not row 4|| Row 2 only has data all other are empty > Data not saved || Rows 2 and 3 has data > Row 2 only is saved
<?php
include '../db/connect.php';
foreach (array('part_id', 'quantity', 'price') as $pos) {
foreach ($_POST[$pos] as $id => $row) {
$_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
}
}
$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices = $_POST['price'];
$items = array();
$size = count($ids);
for($i = 0 ; $i < $size ; $i++){
// Check for part id
if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
continue;
}
$items[]=array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
if (!empty($items)) {
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
$result = mysqli_query($con, $sql );
if ($result) {
echo 'Successful inserts: ' . mysqli_affected_rows($con);
} else {
echo 'query failed: ' . mysqli_error($con);
}
}
?>
The first is a simplified entry form. The reel entry form looks like this:
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="../subs/custompcorder2.php/" method="post" id="form">
<div id="orderwrap">
<div id="orderheather">
<select id="platform" name="platform">
<option selected="selected" disabled="disabled">Select the
platform</option>
<option value="Intel">Intel</option>
<option value="AMD">AMD</option>
</select>
</div>
<div id="orderbody">
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part1 </option>
<?php query() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part2 </option>
<?php query2() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part3 </option>
<?php query3() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part4 </option>
<?php query4() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<input id="submit" type="submit" value="Submit Order"name="submission"/>
</div>
</div>
</form>
</body>
</html>
Here is the php page containing function query(),query1(),..
<?php
include '../db/connect.php';
function query(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query2(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query3(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query4(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function close(){
mysqli_close($con);
}
?>
Sanitize input correctly using array_map
Check for input before adding to array
Only run SQL if anything to be added
Use the following code:
<?php
include '../db/connect.php';
foreach (array('part_id', 'quantity', 'price') as $pos) {
foreach ($_POST[$pos] as $id => $row) {
$_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
}
}
$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices = $_POST['price'];
$items = array();
$size = count($ids);
for($i = 0 ; $i < $size ; $i++){
// Check for part id
if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
continue;
}
$items[] = array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
if (!empty($items)) {
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
$result = mysqli_query($con, $sql );
if ($result) {
echo 'Successful inserts: ' . mysqli_affected_rows($con);
} else {
echo 'query failed: ' . mysqli_error($con);
}
}
Here is a rough code, modify indeces by your own needs.
$ids = $_POST['part_id'] ;
$quantities = $_POST['quantity'] ;
$prices = $_POST['price'];
$items = array();
$size = count($names);
for($i = 0 ; $i < $size ; $i++){
$items[$i] = array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "
INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
Here's an example of basic issue handling while inserting data. Included in error checks are
Confirm that we received all 3 fields - part_id, quantity and price
If there were 3 rows of part_id, there must be 3 rows of quantity and price
Add safety by preparing INSERT statement
Bind variables to the prepared statements
Pick up only those rows in which all 3 fields (part_id, quantity and price) were entered, and that they were valid numbers
Code that receives POST
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// debug information. Let's find what the page is receiving
echo '<pre>', print_r($_POST, true), '</pre>';
$postedData = $_POST;
// confirm that we received all 3 fields - part_id, quantity, price
$fieldsReceived = true;
if ( !confirmFields('part_id')
|| !confirmFields('quantity')
|| !confirmFields('price')
) {
echo 'part_id, quantity or price has not been received. Exiting.';
exit;
}
// confirm that each of them have identical item-count
if ( count($postedData['part_id']) !== count($postedData['quantity'])
|| count($postedData['part_id']) !== count($postedData['price'])
) {
echo count($postedData['price_id']) .
' fields received for price_id, but different number of fields
were received for quantity or price. Please ensure that part_id,
quantity and price have the same number of fields. Exiting.';
exit;
}
// establish connection using mysqli_connect
$connection = mysqli_connect('localhost', 'user', 'pass', 'selected_db');
// prepare an insert statement
$sql = 'insert into oz2ts_custompc_details
(part_id, quantity, price) values
(?, ?, ?)';
$statement = mysqli_prepare($connection, $sql);
// bind integer, integer, double to the parameters in insert statement
// corresponding to the question marks
$part = 0;
$qty = 0;
$prc = 0.0000;
mysqli_stmt_bind_param($statement, 'iid', $part, $qty, $prc);
// loop through received data and only insert those that have valid values
// in part_id, quantity and price
$partsReceived = count($postedData['part_id']);
for ($i = 0; $i < $partsReceived; $i++) {
// if drop down boxes are used and default value for part is
// Choose part, let's see if user left the selection to default
// and ignore that line
if (strpos($postedData['part_id'][$i], 'Choose part') !== false) {
continue;
}
// do we have numeric data in current line?
// although not done here, one can check if part_id is integer (is_int)
// quantity is_int and price is_float before proceeding further
if ( !is_numeric($postedData['part_id'][$i])
|| !is_numeric($postedData['quantity'][$i])
|| !is_numeric($postedData['price'][$i])
) {
echo '<p>Entry # ' . ($i + 1) . '
will be ignored because of missing
or invalid part_id, quantity, or price</p>';
continue;
}
// update bind parameters
$part = $postedData['part_id'][$i];
$qty = $postedData['quantity'][$i];
$prc = $postedData['price'][$i];
// execute statement and move on to the next one
try {
mysqli_stmt_execute($statement);
echo '<p>Inserted part_id ' . $postedData['part_id'][$i] . '</p>';
} catch (Exception $e) {
echo '<p>Could not enter data with part_id '
. $postedData['part_id'][$i] . '<br>'
. 'Error ' . $e->getMessage() . '</p>';
}
}
// --------------------------
// FUNCTIONS
// --------------------------
/**
* Confirm that we received part_id, quantity and price from POST
*
* #param string $fieldName Name of the field to verify
*
* #return bool True if fieldname is set as an array; False otherwise
*/
function confirmFields($fieldName)
{
global $postedData;
return
(!isset($postedData[$fieldName]))
&& !is_array($postedData[$fieldName]) ? false : true;
}
?>
I have a script wher users can find exercise from a database, I have checkboxes for the user to find specific exercises the script works fine when a least 1 checkbox is selected from each checkbox group however I would like it that if no checkboxes was selected then it would the results of all checkboxes.
my checkbox form looks like this
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
ect...
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
ect....
<input type="submit" name="sub" value="Generate Query" />
</form>
and here is my script
<?php
if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
//get the function
include ($_SERVER['DOCUMENT_ROOT'] .'/scripts/functions.php');
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 14;
$startpoint = ($page * $limit) - $limit;
// Runs mysql_real_escape_string() on every value encountered.
$clean_muscle = array_map('mysql_real_escape_string', $_REQUEST['muscle']);
$clean_equipment = array_map('mysql_real_escape_string', $_REQUEST['equipment']);
// Convert the array into a string.
$muscle = implode("','", $clean_muscle);
$equipment = implode("','", $clean_equipment);
$options = array();
if(array($muscle))
{
$options[] = "muscle IN ('$muscle')";
}
if(array($equipment))
{
$options[] = "equipment IN ('$equipment')";
}
$fullsearch = implode(' AND ', $options);
$statement = "mytable";
if ($fullsearch <> '') {
$statement .= " WHERE " . $fullsearch;
}
if(!$query=mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint} , {$limit}"))
{
echo "Cannot parse query";
}
elseif(mysql_num_rows($query) == 0) {
echo "No records found";
}
else {
echo "";
while($row = mysql_fetch_assoc($query)) {
echo "".$row['name'] ."</br>
".$row['description'] ."";
}
}
echo "<div class=\"new-pagination\">";
echo pagination($statement,$limit,$page);
echo "</div>";
}
}
Im new with php so my code may not be the best. If anyone can help me or point me in the right direction I would be very greatful.
OK - I think I have figured it all out. You were right - the main problem was in your isset and isempty calls. I created some variations on your file, and this shows what is going on. Note - since I don't have some of your "other" functions, I am only showing what is going wrong in the outer parts of your function.
Part 1: validating function
In the following code, I have added two JavaScript functions to the input form; these were loosely based on scripts you can find when you google "JavaScript validation checkbox". The oneBoxSet(groupName) function will look through all document elements; find the ones of type checkBox, see if one of them is checked, and if so, confirms that it belongs to groupName. For now, it returns "true" or "false". The calling function, validateMe(formName), runs your validation. It is called by adding
onclick="validateMe('criteria'); return false;"
to the code of the submit button. This basically says "call this function with this parameter to validate the form". In this case the function "fixes" the data and submits; but you could imagine that it returns "false", in which case the submit action will be canceled.
In the validateMe function we check whether at least one box is checked in each group; if it is not, then a hidden box in the "all[]" group is set accordingly.
I changed the code a little bit - it calls a different script (muscle.php) instead of the <?php echo $_SERVER['PHP_SELF']; ?> you had... obviously the principle is the same.
After this initial code we will look at some stuff I added in muscle.php to confirm what your original problem was.
<html>
<head>
<script type="text/javascript">
// go through all checkboxes; see if at least one with name 'groupName' is set
// if so, return true; otherwise return false
function oneBoxSet(groupName)
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked) {
if (c[i].name == groupName) {
return true; // at least one box in this group is checked
}
}
}
}
return false; // never found a good checkbox
}
function setAllBoxes(groupName, TF)
{
// set the 'checked' property of all inputs in this group to 'TF' (true or false)
var c=document.getElementsByTagName('input');
// alert("setting all boxes for " + groupName + " to " + TF);
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].name == groupName) {
c[i].checked = TF;
}
}
}
return 0;
}
// this function is run when submit is pressed:
function validateMe(formName) {
if (oneBoxSet('muscle[]')) {
document.getElementById("allMuscles").value = "selectedMuscles";
//alert("muscle OK!");
}
else {
document.getElementById("allMuscles").value = "allMuscles";
// and/or insert code that sets all boxes in this group:
setAllBoxes('muscle[]', true);
alert("No muscle group was selected - has been set to ALL");
}
if (oneBoxSet('equipment[]')) {
document.getElementById("allEquipment").value = "selectedEquipment";
//alert("equipment OK!");
}
else {
document.getElementById("allEquipment").value = "allEquipment";
// instead, you could insert code here that sets all boxes in this category to true
setAllBoxes('equipment[]', true);
alert("No equipment was selected - has been set to ALL");
}
// submit the form - function never returns
document.forms[formName].submit();
}
</script>
</head>
<body>
<form action="muscle.php" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
<input type="hidden" name="all[]" id="allMuscles" value="selectedMuscles" />
etc...<br>
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
<input type="hidden" name="all[]" id="allEquipment" value="selectedEquipment" />
<br>
<input type="submit" name="sub" value="Generate Query" onclick="validateMe('criteria'); return false;" />
</form>
</body>
</html>
Part 2: what's wrong with the PHP?
Now here is a new start to the php script. It checks the conditions that you were testing at the start of your original script, and demonstrates that you never get past the initial if statements if a check box wasn't set in one of the groups. I suggest that you leave these tests out altogether, and instead get inspiration from the code I wrote to fix any issues. For example, you can test whether equipmentAll or muscleAll were set, and create the appropriate query string accordingly.
<?php
echo 'file was called successfully<br><br>';
if(isset($_POST['muscle'])) {
echo "_POST[muscle] is set<br>";
print_r($_POST[muscle]);
echo "<br>";
if (!empty($_POST['muscle'])) {
echo "_POST[muscle] is not empty!<br>";
}
else {
echo "_POST[muscle] is empty!<br>";
}
}
else {
echo "_POST[muscle] is not set: it is empty!<br>";
}
if(isset($_POST['equipment'])) {
echo "_POST[equipment] is set<br>";
print_r($_POST['equipment']);
echo "<br>";
if (!empty($_POST['equipment'])) {
echo "_POST[equipment] is not empty!<br>";
}
else {
echo "_POST[equipment] is empty!<br>";
}
}
else {
echo "_POST[equipment] is not set: it is empty!<br>";
}
if(isset($_POST['all'])) {
echo "this is what you have to do:<br>";
print_r($_POST['all']);
echo "<br>";
}
// if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
// if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
If you call this with no check boxes selected, you get two dialogs ('not OK!'), then the following output:
file was called successfully
_POST[muscle] is not set: it is empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => allMuscles [1] => allEquipment )
If you select a couple of boxes in the first group, and none in the second:
file was called successfully
_POST[muscle] is set
Array ( [0] => abdominals [1] => calves )
_POST[muscle] is not empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => selectedMuscles [1] => allEquipment )
I do not claim to write beautiful code; but I hope this is functional, and gets you out of the fix you were in. Good luck!