Save Inputs into database & class errors - building coupon system - php

Okay, I'm building (trying) a coupon code system for my admin panel, what I want to achieve is allow admin to manually create coupons by setting its coupon_code and coupon_discount (1% TO 100%). When he will submit, it will be stored in two different tables of two dbs.
TABLE coupons:
coupon_id INT(10) NOT NULL AUTO INCREMENT - Primary key
coupon_code VARCHAR(15) NOT NULL - unique
discount DECIMAL(3,2)
expire DATETIME -NULL
count INT(10) -NULL
I checked lots of examples on the net and this is my probably poorly written class:
class ProductDiscount {
static public function validate($coupon_code);
private $_coupon_code; // string
private $_coupon_discount; // integer??
private $_expire; // null cause unlimited
private $_count; // null
private function __construct(); //for this line I got an error
public function getCouponCode(); // return string
public function getCouponDiscount(); // return
public function getCount(); // returns null unlimited
public function getExpireDate();// null
public function useDiscount(); // apply this discount now
public function useAllDiscount(); // invalidate this discount for future use
COUPONS.PHP - new coupon creation
On the admin side, I am totally lost about how to pass the coupon_code and coupon_discount to the database...How to utilize the functions that I wrote in the class...This is what I did:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$coupon_code = $_POST['coupon_code'];
$coupon_discount = $_POST['coupon_discount'];
//insert into db for admin
$connect = new mysqli("localhost","-----","-------","--------");
$stmt = $connect->prepare("INSERT INTO `coupons` (`coupon_code`, `coupon_discount`) VALUES (?,?)");
$stmt->bind_param('si', $coupon_code, $coupon_discount);
$stmt->execute();
$connect->close();
}
?>
I'm getting undefined index errors for both the coupon_code and coupon_discount..
If I require_once my class file here, I'm getting Non-abstract method ProductDiscount::create() must contain body error.
<form class="form-horizontal" role="form" action="createcoupon.php">
<div class="form-group">
<label class="col-sm-2 control-label">Coupon Code</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="coupon_code" id="couponCode" placeholder="e.g SAVE10">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Coupon Discount</label>
<div class="col-sm-2">
<input type="number" class="form-control" name="coupon_discount" id="couponDiscount" placeholder="e.g 10 for 10%">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-3">
<input type="submit" style="background-color:#7575DD; padding:0 !important; color:white;" name="create_coupon" value="Create Coupon" class="btn btn-default"/>
</div>
</div>
</form>
Here is my createcoupon.php:
<?php
//Connect to the 1st db
$coupon_code = $_POST['coupon-code'];
$coupon_discount = $_POST['coupon-discount'];
//the prepared stmt to insert into db1
//Connect to the 2nd tb
$coupon_code = $_POST['coupon-code'];
$coupon_discount = $_POST['coupon-discount'];
//prepared stmt to insert into db2
header("location: http://example.com/admin/coupons");
?>
It's 4am and been hours that I'm trying to learn these.
So my question is: "How can I save the necessary form data to the table in the correct way and save the coupon into the table?"
(edited and specified my current problem only, can you reopen?)
(commented the long/unnecessary parts to clarify)
Thank you so much for your time!

Okay so far, I managed to solve it. Using bootstrap table.
With an "add coupon" button:
<button data-toggle='modal' data-target='#myModal' type='button' class='btn btn-primary' style="margin: 20px;" name='add-btn' id='add-btn'>Add Coupon</button>
data-toggle='modal' and data-target='#myModal' to link the modal div to the button
SELECT statement to get the coupon table and pull the data into a bootstrap table.
<div style="padding: 20px;">
<?php
$con = new mysqli("------","--------","--------","-----");
$query = "SELECT * FROM coupons WHERE expire > NOW() OR expire IS NULL OR expire = '0000-00-00 00:00:00'";
if ($result = $con->query($query))
{
echo "<table border='1' class='table table-hover' data-toggle='table'>
<tr>
<th>Coupon Code</th>
<th>Amount</th>
<th>Expiry</th>
<th></th>
</tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['coupon_code'] . "</td>";
echo "<td>" . $row['coupon_discount'] . "</td>";
echo "<td>" . $row['expire'] . "</td>";
echo "<td><button data-toggle='modal' data-target='#myModal' type='button' class='btn btn-primary' name='submit-btn' data-id='" . $row["coupon_id"] ."'>Edit</button></td>";
echo "</tr>";
}
echo "</table>";
}
mysqli_close($con);
?>
These are the modal divs and form to post the inputs and save it to the table.
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Coupon Information</h4>
</div>
<div class="modal-footer">
<form action='createcoupon.php' method='POST'>
<input type='hidden' name='coupon_id' id='couponId' value='0'/>
<input type="text" class="form-control" style="margin-bottom:10px;" name="coupon_code" id="couponCode" placeholder="e.g SAVE10">
<input type="number" class="form-control" style="margin-bottom:10px;" name="coupon_discount" id="couponDiscount" placeholder="e.g 10 for 10%">
<input type="text" class="form-control" style="margin-bottom:10px;" name="coupon_expire" id="couponExpire" placeholder="e.g 01/01/2015">
<input class="btn btn-primary" type='submit' name='submit-btn' value='Save' />
</form>
</div>
</div>
</div>
</div>
</div>
This is the javascript
<script>
// Function added to each edit button. Sets the ID to the button "data-id" value.
// Finds the parent (td) of the button, then goes to each sibling with the correct class name
// and changes the modal input value to the inner text of the TD
var editfunction = function() {
$('#couponId').val($(this).attr('data-id'));
var parent = $(this).parent();
$('#couponCode').val($(parent).siblings('.coupon_code').text());
$('#couponDiscount').val($(parent).siblings('.coupon_discount').text());
$('#couponExpire').val($(parent).siblings('.coupon_expire').text());
};
// Called on the ADD button only
// Sets the ID to 0 (to INSERT the record on the form submit)
// Sets the other inputs to blank values
function addNewCoupon()
{
$('#couponId').val('0');
$('#couponCode').val('');
$('#couponDiscount').val('');
$('#couponExpire').val('');
}
// When the page has loaded...
// Attach the edit function call to the click event of each edit button
// Attach the add new coupon to the click event of the add button
$(document).ready(function() {
$('button[name="submit-btn"]').click(editfunction);
$('#add-btn').click(function() { addNewCoupon(); });
});
</script>
Then on the createcoupon.php I did this:
// Check connection
$coupon_id = intval($_POST['coupon_id']);
$coupon_code = $_POST['coupon_code'];
$coupon_discount = $_POST['coupon_discount'];
and after with mysqli connection I inserted/updated (in an if else statement, "if is 'add coupon' or 'edit coupon') them.
I solved this in the end, If you have any ideas about it, please share with me so that I can improve.
I hope these codes can be useful for someone!
Thanks for your time.

Related

Breaking login flow if already logged in with another session

I am working on a codeigniter 3 app and ive recently implemented a session checker that deletes a user session if they're already logged in. Now we want a modal box to pop up if the user is already logged in with another session. I am able to get a modal box to pop up using a button but i want to implement it into the original flow of the login system. As it is the login form takes you straight to the validate login system. This is the login form now:
<form action="<?php echo site_url('login/validate_login/user'); ?>" method="post">
<div class="content-box">
<div class="basic-group">
<div class="form-group">
<label for="login-email"><span class="input-field-icon"><i class="fas fa-envelope"></i></span> <?php echo get_phrase('email'); ?>:</label>
<input type="email" class="form-control" name = "email" id="login-email" placeholder="<?php echo get_phrase('email'); ?>" value="" required>
</div>
<div class="form-group">
<label for="login-password"><span class="input-field-icon"><i class="fas fa-lock"></i></span> <?php echo get_phrase('password'); ?>:</label>
<input type="password" class="form-control" name = "password" placeholder="<?php echo get_phrase('password'); ?>" value="" required>
</div>
</div>
</div>
<div class="content-update-box">
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
<!-- Modal -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You are already logged in</h4>
</div>
<div class="modal-body">
<p>You are currently logged in on a different session on the site. Please note that if you continue, the existing session will be terminated. Please change your password if you suspect that your account has been conpromised.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel Login</button>
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
</div>
</div>
</div>
<div class="forgot-pass text-center">
<span><?php echo get_phrase('or'); ?></span>
<?php echo get_phrase('forgot_password'); ?>
</div>
<div class="account-have text-center">
<?php echo get_phrase('do_not_have_an_account'); ?>? <?php echo get_phrase('sign_up'); ?>
</div>
</form>
The button at the moment goes straight to this login function:
public function validate_login($from = "") {
$email = $this->input->post('email');
$password = $this->input->post('password');
$credential = array('email' => $email, 'password' => sha1($password), 'status' => 1);
// Checking login credential for admin
$query = $this->db->get_where('users', $credential);
if ($query->num_rows() > 0) {
$row = $query->row();
$this->session->set_userdata('user_id', $row->id);
$this->session->set_userdata('role_id', $row->role_id);
$this->session->set_userdata('role', get_user_role('user_role', $row->id));
$this->session->set_userdata('name', $row->first_name.' '.$row->last_name);
$this->delete_session_user_id();
$this->session->set_flashdata('flash_message', get_phrase('welcome').' '.$row->first_name.' '.$row->last_name);
if ($row->role_id == 1) {
$this->session->set_userdata('admin_login', '1');
redirect(site_url('admin/dashboard'), 'refresh');
}else if($row->role_id == 2){
$this->session->set_userdata('user_login', '1');
$this->set_session_user_id();
redirect(site_url('home/my_courses'), 'refresh');
}
}else {
$this->session->set_flashdata('error_message',get_phrase('invalid_login_credentials'));
redirect(site_url('home/login'), 'refresh');
}
}
I created this function to pull the user id from the emails:
public function get_user_id($user_email = "") {
$this->db->select('id');
$this->db->where('email', $user_email);
$user_id=$this->db->get('users');
return $user_id;
}
This function can get the user id based on the email supplied.
Then I use this function to check if there is a session and return false if there are 0 results and true if there is a session with that user id. So if its false they should be able to log in and the modal pop-up shouldnt open but if its true it should open.
public function user_has_session($user_id=''){
$this->db->where('user_id',$user_id);
$this->db->from('ci_sessions');
$total=$this->db->count_all_results();
if($total<0)
return false;
else
return true;
}
I think this is the best approach without having to redo the entire login flow. Perhaps someone can advise if this is the best approach or if in fact i should change the entire flow.
Thanks
Here is the previous problem I had which I have answered myself
https://stackoverflow.com/questions/62458226/codeigniter-3-stop-multiple-logins-using-ci-sessions-database
UPDATE Added to clarify my problem
Well the problem is when a login is attempted from another device it should logout the other active session. So if o logged in on my desktop in a new browser or even my phone with the same user ID the active session should end, at the moment it does so without warning the user. So I want to have a modal pop up warning the user that there is an active session currently running with this user id
You need to implement an Ajax call which will check whether the user is already logged in or not. If the user is not logged In than you can proceed to login otherwise trigger your popup open to display the message.
Here the user has choices to log in or not, If users choose to login then you can unbind the event on submit and let the user go ahead.
I have made some changes to your HTML file. Please check below -
Your HTML template
<form action="<?php echo site_url('login/validate_login/user'); ?>" id="login-form" onSubmit="return checkUserSession();" method="post">
<div class="content-box">
<div class="basic-group">
<div class="form-group">
<label for="login-email"><span class="input-field-icon"><i class="fas fa-envelope"></i></span> <?php echo get_phrase('email'); ?>:</label>
<input type="email" class="form-control" name = "email" id="login-email" placeholder="<?php echo get_phrase('email'); ?>" value="" required>
</div>
<div class="form-group">
<label for="login-password"><span class="input-field-icon"><i class="fas fa-lock"></i></span> <?php echo get_phrase('password'); ?>:</label>
<input type="password" class="form-control" name = "password" placeholder="<?php echo get_phrase('password'); ?>" value="" required>
</div>
</div>
</div>
<div class="content-update-box">
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
<!-- Modal -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You are already logged in</h4>
</div>
<div class="modal-body">
<p>You are currently logged in on a different session on the site. Please note that if you continue, the existing session will be terminated. Please change your password if you suspect that your account has been conpromised.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel Login</button>
<button type="button" id="modal-submit-button" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
</div>
</div>
</div>
<div class="forgot-pass text-center">
<span><?php echo get_phrase('or'); ?></span>
<?php echo get_phrase('forgot_password'); ?>
</div>
<div class="account-have text-center">
<?php echo get_phrase('do_not_have_an_account'); ?>? <?php echo get_phrase('sign_up'); ?>
</div>
</form>
<script>
/** Trigger function on form submit whether to check user logged in */
function checkUserSession(){
var email = $("#login-email").val();
$.ajax({
url: "<?php echo site_url('login/checkUserSession'); ?>",
type: 'POST',
data: { 'email': email},
success: function(status){
if(status == true) { // User is already logged in somewhere, display the messege.
$("#login").modal();
return false;
} else { // User is not logged in, submit the form
return true;
}
}
});
}
/** Allow user to log in with exception */
$("#modal-submit-button").on("click", function(){
$("#login").modal('hide'); // hide the modal
$("#login-form").attr("onSubmit", ""); // unbind the function
$("#login-form").submit(); // submit login form
})
</script>
Controller -
<?php
/** Function to check user logged in or not */
public function checkUserSession() {
$user_email = $this->input->post('email');
$userId = $this->get_user_id($user_email);
$response = $this->user_has_session($userId);
echo $response;
}
public function get_user_id($user_email = "") {
$this->db->select('id');
$this->db->where('email', $user_email);
$user_id=$this->db->get('users');
return $user_id;
}
public function user_has_session($user_id=''){
$this->db->where('user_id',$user_id);
$this->db->from('ci_sessions');
$total=$this->db->count_all_results();
if($total<0)
return false;
else
return true;
}
?>

Insert query not inserting in database

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;');

Button form submission not submitting NULL

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
}

How to add an PHP IF statement in this Script?

$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.

Cannot pass hidden form value to php

When i pass the hidden value to the php file it gives (true) 1 as a answer.
I am passing the value from the modal to the php file.
The span value was retrieved using jquery.
PHP CODE:
<?php
include "dbcon.php";
if(isset($_POST['pd_del']))
{
echo mysql_error();
$delid=isset($_POST['delidd']);
echo $delid;
}else
{
echo mysql_error();
}
?>
HTML CODE:
Form thats send the product id to the php file
<form name="prd_del" action="del_prod.php" method="post">
<div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="delModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">DELETE PRODUCT</h4>
</div>
<div class="modal-body">
<h5>Do you want to Delete this Product ??? <span id="delid" name="delid"></span></h5>
<input type="hidden" name="delidd" id="delid">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="pd_del" >Delete It!</button>
</div>
</div>
</div>
</div>
</form>
Your HTML :
<h5>Do you want to Delete this Product ??? <span id="delid" name="delid"></span></h5>
<input type="hidden" name="delidd" id="delid">
Your JS :
$(".modal-body #delid").text( pd_del_id);
First problem is that you have 2 elements with the same id value (the sppan and the input field). You shouldn't.
Change one of your ids, something like that :
<h5>Do you want to Delete this Product ??? <span id="delid" name="delid"></span></h5>
<input type="hidden" name="delidd" id="delid_value">
And in your JS, if I understood what you want to do :
$(".modal-body #delid").text(pd_del_id); // Here you put the product's ID in your span to show it to the user.
$(".modal-body #delid_value").val(pd_del_id); // Here you put the product's ID in your hidden field to send it with your form.
Now, your PHP :
$delid=isset($_POST['delidd']);
echo $delid;
isset() function returns either true or false if the variable is set or not.
The variable $_POST['delidd'] is set (the hidden field is always sent to your PHP).
If you want to get the value (your product's ID) :
if (!empty($_POST['delidd'])) {
// The value is not empty
$delid = $_POST['delidd'];
} else {
// The value is empty : there is a problem (For example echo an error message or do whatever you have to do in that case.)
}

Categories