$sql = "SELECT * FROM item";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input type="hidden" name="itemName" value="'.$row['itemName'].'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
I want to be able to add an if statement in this result_2 string.
This is for displaying a product, and i would like to display price depending on users session value?
eg.
if ($_SESSION['customer_x'] == a) {
display price a
}
else if ($_SESSION['customer_x'] == b) {
display price b
}
Is this the correct method to be able to add an if statement to a JSON query?
After Starting your while loop, put a if else there,
$price ="";
if ($__SESSION['customer_x'] == a) {
$price='display price a';
}
else if ($_SESSION['customer_x'] == b) {
$price='display price b';
}
and now echo this price where ever you want to in your html
this is more neet and less messy way
You can use a ternary if operator to have conditional statements inside strings, example
$bool = false;
echo "The value of \$bool is " . ($bool == true ? "TRUE" : "FALSE");
Example in use
To add that you can keep doing the same but:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ // the next of the content
$priceOfSession = ($__SESSION['customer_x'] == a) ? 'pricea' : 'priceb';
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
'.$priceOfSession.'
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
</div>
';
}
So if you want to evaluate only two conditions if otherwise the if you want, simply add it there. Do as you add the $ row but before defining value.
Related
var html3 = '<div class="row" id="parent-autor"> <p id="auth-del"><i class="fa fa-minus-square" aria-hidden="true"></i></p> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" name="altautorprenume[]" placeholder="Prename"> </div> </div> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" name="altautornume[]" placeholder="Name"> </div> </div><div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" name="institutie[]" id="institutie" placeholder="Institutions"> </div> </div></div>';
$("#add_aut").click(function(e){
$('#auth-rows').append(html3);
});
$('#auth-rows').on('click', '#auth-del', function(E){
$(this).parent('div').remove();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="add-plus"></div>
<div class="col-md-12">
<h5>Add more persons </h5>
<span class="btn btn-primary" id="add_aut" style="">Click here to add</span>
</div>
</div>
<div id="auth-rows"></div>
i have an formular which user can add more clients to invite at party when user click on Add a new row with 3 fields appear he can add how many he want,
these values dynamically i want to show on email, for example:
User fill all fields and add 3 more users where they have Name PreName Instituional,look what i did:
$personName= $_POST['personname'];
$personPrename= $_POST['personprename'];
$institution= $_POST['institution'];
$otherPersonName=" ";
$otherPersonPreName="";
$otherPersonInstitution= "";
foreach($personName as $product) {
$otherPersonPreName.= "$product";
}
foreach($personPrename as $products) {
$altiautoriNume .= "$products";
}
foreach($institution as $productss) {
$otherPersonInstitution.= "$productss";
}
EXAMPLE:
And in email content i want to display like this:
<hr>
John(first name of person added) Doe(first Prename of person added) Microsoft(first Institution of person added)
<hr>
Mike(second name of person added) Stuart(second Prename of person added) Facebook(second Institution of person added)
<hr>
I know i did something wrong.
I put even html to see truly what i want to do, i want to group Name Prename Institution per line
You can use array-map with null as first parameter to group the array and then use implode to concat the strings.
Consider the following:
$arr = array_map(null, $personName, $personPrename, $institution);
foreach($arr as $e)
echo implode(" ", $e) . PHP_EOL;
Live example: 3v4l
My Form Look like this, here i wanted to send grade of Nepali subject database by taking and converting numeric marks from form mepali_th_num but what ever input numeric mark are it only send 'E' Grade to database after conversion of grade. What is wrong in this code mainly in if else part.
<form class="form-horizontal" method="post">
<div class="box-body">
<div class="form-group">
<label for="nepali_th_num" class="col-sm-2 control-label">Nepali(TH)
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="nepali_th_num"
name="nepali_th_num" step="any" min="0">
</div>
</div>
<div class="box-footer">
<button type="submit" name="btnSave" class="btn btn-
primary">Submit</button>
<button type="reset" class="btn btn-info">Reset</button>
</div>
</form>
my php look like this:
if (isset($_POST['btnSave'])){
$marksdetails = new Marksdetails();
$marksdetails->set('nepali_th_num', $_POST['nepali_th_num']);
$nep_per=((('nepali_th_num')*100)/75);
if($nep_per>=90){
$nepali_th_grade='A+';
}elseif ($nep_per>=80 && $nep_per<90) {
$nepali_th_grade='A';
}elseif ($nep_per>=70 && $nep_per<80){
$nepali_th_grade='B+';
}elseif($nep_per>=60 && $nep_per<70) {
$nepali_th_grade='B';
}elseif($nep_per>=50 && $nep_per<60){
$nepali_th_grade='C+';
}elseif($nep_per>=40 && $nep_per<50){
$nepali_th_grade='C';
}elseif($nep_per>=30 or $nep_per<40){
$nepali_th_grade='D+';
}elseif($nep_per>=20 or $nep_per<30){
$nepali_th_grade='D';
}else{
$nepali_th_grade='E';
}
$marksdetails->set('nepali_th_grade', $nepali_th_grade);
$marksdetails->set('symbol_number', $symbolnumber);
$marksdetails->set('student_name', $studentname);
$status=$marksdetails->checkDuplicate(); //to check duplicate and sql part
is in this
}
nepali_th_num in this line
$nep_per=((('nepali_th_num')*100)/75);
is just a string, its not a variable containing something useful
Try
$nep_per=((($_POST['nepali_th_num'])*100)/75);
So I'm trying to insert some text into a already existing table. If I insert the text into the text field and press submit, I'll get a var_dump on a other page that shows the information that I want to insert but it doesnt send it to the database or something. I hope you can help me with what I'm doing wrong.
This is my insert query
public function insertComment($commentaar, $idBestelling){
try{
$stmt = $this->_db->prepare('UPDATE `apotheek`.`Bestelling` SET `commentaar` = :commentaar WHERE `Bestelling`.`idBestelling` = :idBestelling;');
if($stmt->execute(array(
':commentaar' => $commentaar,
':idBestelling' => $idBestelling))){
return true;
} else {
return false;
}
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
And here you can find the code from the webpage.
<div class="row">
<form role="form" method="post" action="/?content=bezorgen">
<div class="col-xs-12 col-sm-12 col-md-12 loginborder">
<h2 class="loginhead">Bestelling no. <?php print($data['idBestelling']); ?> <?php ($data['isSpoed'] == '0') ? print('') : print('deze bestelling is met SPOED') ?></h2>
<hr>
<div class="row col-6 col-md-6 col-sm-12 col-xs-12">
<div class="loginhead">
<h3>Commentaar</h3>
<hr>
</div>
<div>
<textarea rows="9" cols="74" name="commentaar"><?php print($data['commentaar']); ?></textarea>
</div>
</div>
<div class="row registerbtn">
<div class="col-xs-12 col-md-12" style="text-align:right;"><input type="submit" name="submit" value="Verstuur" class="btn btn-lg" tabindex="5"></div>
</div>
</div>
</form>
And the php
$data = $user->getBestellingPatient($_POST['idBestelling']);
if(isset($_POST['submit'])){
$user->insertComment($_POST['commentaar'], $_POST['idBestelling']);
};
I think you are trying to update a comment which is already exist in the database.
You should add a hidden field in the form to hold the id of the the post (Mostly auto incremented id from DB)
Add the below element below your textarea element
<input type='hidden' name='idBestelling'<?php print($data['idBestelling']); ?>/>
So when you are updating id will be passed as a part of the form then you can receive it usinig $_POST
you should try this:
$stmt = $this->_db->query('UPDATE `apotheek`.`Bestelling` SET `commentaar` = :commentaar WHERE `Bestelling`.`idBestelling` = :idBestelling;');
I am working with a fairly straight forward form yet for some reason it is not submitting NULL results and instead submits them as empty results.
<div class="span6">
<form action="" method="POST">
<div class="block-fluid without-head">
<div class="toolbar clearfix">
<div class="right">
<div class="btn-group">
<button type="submit" class="btn btn-small btn-warning tip" data-original-title="Submit Aritcle">
<span class="icon-ok icon-white"></span>
</button>
<button type="button" class="btn btn-small btn-danger tip" data-original-title="Delete Article">
<span class="icon-remove icon-white"></span>
</button>
</div>
</div>
<div class="left">
<div style="font-size: 11pt; font-family: -webkit-body; font-weight: bolder;">Article Exchange Request</div>
</div>
</div>
<div class="row-form clearfix">
<div class="span3">Title</div>
<div class="span9"><input type="text" name="title" value="" placeholder="main subject title"></div>
</div>
<div class="row-form clearfix">
<div class="span3">First Sentence</div>
<div class="span9"><input type="text" name="s1" value="" placeholder="Sentence with max of 200 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Second Sentence</div>
<div class="span9"><input type="text" name="s2" value="" placeholder="Optional sentence with max of 200 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Third Sentence</div>
<div class="span9"><input type="text" name="s3" value="" placeholder="Optional Sentence with max of 200 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Website Url</div>
<div class="span9"><input type="text" name="link" value="" placeholder="Url to be included in articles"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Website Url Title</div>
<div class="span9"><input type="text" name="link_text" value="" placeholder="Url text to be included in articles limit 150 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Credit Offer</div>
<div class="span9"><input type="text" name="cost_value" value="" placeholder="Example: 100"></div>
</div>
</div>
</form>
</div>
The problem is someone can just come along and submit the form without entering any data at all, and it still submits, and adds empty results to every column in the database. Meaning no NULL values are being set in the database.
My form processing
<?
if (isset($_POST[cost_value])) {
$stmt = $db->prepare("SELECT credits from member_credits WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$row = $stmt->fetch();
$count = $row[credits];
if ($count > $_POST[cost_value]) {
$stmt = $db->prepare('INSERT INTO article_requests (title, s1, s2, s3, link, link_text, offer, username) VALUES (:title, :s1, :s2, :s3, :link, :link_text, :offer, :username)');
$stmt->bindValue(':title', $_POST[title]);
$stmt->bindValue(':s1', $_POST[s1]);
$stmt->bindValue(':s2', $_POST[s2]);
$stmt->bindValue(':s3', $_POST[s3]);
$stmt->bindValue(':link', $_POST[link]);
$stmt->bindValue(':link_text', $_POST[link_text]);
$stmt->bindValue(':offer', $_POST[cost_value]);
$stmt->bindValue(':username', $username);
$stmt->execute();
}
}
?>
What I expect to happen on submission is if no value is entered in the form it should be set to NULL... that would mean if no $_POST[cost_value] was set, the form wouldn't submit. As it stands now, it is ALWAYS seeing $_POST[cost_value] as being set - sometimes to a value such as $_POST[cost_value] = '100'; and other times $_POST[cost_value] = ''; but in both cases, the form will submit. Equally I have the database set so that only the values of s2 and s3 should be able to be null, however when everything is submitting empty instead of null, thats mostly useless.
What exactly am I missing? Why will it not say $_POST[cost_value] = NULL; if the user has not input a value? Why is it submitting ''?? I have a feeling its going to be something basic I am overlooking, I just don't see it....
UPDATE FOR CLARITY
I know there are a number of ways to fix this. I can use if then tests, I can use temporary variables, I can check for the value itself is something other than ''. I know WHAT the work arounds are. I don't understand WHY they are needed. Why is it I make forms every day of the week using if isset, and everyday that works. If a form has no values input from the user, the form won't submit because an if isset returns false. So why is it on this particular form it is submitting '' instead of saying !isset don't process.
// Assign a var to the post.
$DIRTY_Var = $_POST['varinputname'];
// ensure the var is cleaned (no funny business when submitting)
$CLEAN_Var = filter_var($DIRTY_Var,` FILTER_SANITIZE_STRING);
// check if the var is empty, or has value. If empty it will set the var to null;
if (!$CLEAN_Var) { return $CLEAN_Var = null; }
// validate input
$valid = true;
// insert data
if ($valid) {
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO Table ("
."ColumnNames"
.")"
."VALUES("
."?"
.")";
$q = $pdo->prepare($sql);
$q->execute(array($CLEAN_Var));
// Once INSERT is completed, we will redirect.
header("Location:" 'link.php'); exit;
}
Try
If(isset($_POST['cost_value']) && !empty($_POST['cost_value']){
// your code
}
I am trying to build a bidding application. I want to a associate a textfield with the primary key of the row outputted. e.g textfield is bid_amount.
When entering the bid amount I want the bid_amount entered and the person who bid (truckerid) and the product bid on (luggage_id) to be stored in a bids table.
The outputted products to bid for are stored in another table (consignment table) Below is my model, view and controller.
View
<h2 class="page-header">
<i class="fa fa-legal"></i>   <font color="orange"> Loads To Bid For </font>
</h2>
</div><!-- /.col -->
</div>
<?php
foreach ($h->result() as $row) {}
?>
<div class="row invoice-info">
<div class="col-sm-1 invoice-col">
</div>
<div class="col-sm-3 invoice-col">
<img src="<?php echo base_url()?>/res/images/goods/1.png">
</div>
<div class="col-sm-4 invoice-col">
<address>
Description: <?php echo $row->description;?><br>
Location Address: <?php echo $row->l_area;?><br>
Destination Address: <?php echo $row->d_area;?><br>
Date: <?php echo $row->dom;?><br>
Time: <?php echo $row->tom;?>
</address>
</div>
<div class="col-sm-2 invoice-col">
<address>
</address>
</div><!-- /.col -->
<div class="col-sm-2 invoice-col">
<?php echo form_open('truckeraccount_ctrl/bid'); ?>
<input type="hidden" class="form-control" name="truckerid" value="<?php
$truckerid = $this->session->userdata('truckerid');
echo $truckerid; ?>" required>
<input type="text" class="form-control" name="bid_amount[$row->luggage_id]" placeholder="Bid">
<button type="submit" class="btn bg-orange btn-flat margin">Place Bid</button>
</div>
</div>
Controller
public function bid() {
$this->load->model('Truckeraccount_model');
// $luggage_id = $this->uri->segment(3);
$this->Truckeraccount_model->bid();
redirect('truckeraccount_ctrl');
}
Model
function bid() {
$data = array(
'luggage_id' => $this->input->post('luggage_id'),
'bid_amount' => $this->input->post('bid_amount'),
'truckerid' => $this->input->post('truckerid')
);
//$this->db->where('luggage_id', $luggage_id);
$query=$this->db->update('bids', $data);
return $query;
}
You can use the input as an associative array by changing the name. This will make the keys in the array the product ids
try
<input type="text" name="bidAmount[$row->productId]" />
then in your PHP you can loop through the values
foreach ($_POST['bidAmount'] as $productId => $bidAmount) {
// do your logic here
}
You can use hidden text box to get bid.
<?php
foreach ($products->result() as $row)
{ ?>
<?php echo $row->price;?>
<input type="hidden" name="bid[]" value="<?php echo $row->bid;?>">
<input type="text" name="bidAmount[]" placeholder="place bid amount">
<?php } ?>
Now bid and bidAmount both will have same counts of array. So that use for loop to get bid value and bidAmount value.
for ($i=0; $i < count($_POST['bid']); $i++) {
$bid = $_POST['bid'][$i]; \\ You can get bid value here
$bidAmount = $_POST['bidAmount'][$i]; \\ You can get bid amount value here
}
Hope this answer will be helpful. If it is correct then don't forget to mark as correct answer. Cheers.