imgrooot
-
Posts
383 -
Joined
-
Last visited
-
Days Won
1
Posts posted by imgrooot
-
-
you wouldn't add the date string to the option value. you would convert the submitted option value to the date string right before you insert the data into your database table.
Ahh yes, so that's what you were saying before. Makes sense.
Thank you so much for help me out.
-
you can build the $expiry_options array entries with whatever values you want. store the strtotime offsets - '12 hour', '24 hour' (add them manually), '1 week' up to 'n week' (add the weeks dynamically using a loop) in the array. i'm pretty sure that the 's' is optional in the strtotime, so build the values that you need for display purposes, and the strtotime() should work.
since the permitted values are now in an array, to validate that the submitted value is one of the permitted ones, before using it in your code, you can just use in_array().
see this code -
<select name="expiry_date"> <?php $num_weeks = 10; // define the number of weeks you want in the option list // produce the data for the option list $expiry_options = array(); $expiry_options[] = '12 Hours'; // manually add the two hours entries... $expiry_options[] = '24 Hours'; foreach(range(1,$num_weeks) as $week_no){ // add the week entries $plural = $week_no > 1 ? 's' : ''; $expiry_options[] = "$week_no Week{$plural}"; } ?> <option value="0">Expires In</option> <?php // output the option list foreach($expiry_options as $arr){ $sel = !empty($_POST['expiry_date']) && $_POST['expiry_date'] == $arr ? 'selected' : ''; echo "<option value='$arr' $sel>$arr</option>\n"; } ?> </select>
That's great. It works.
One last thing. How would you add my original date string into your new option value? I tried it like this and it gives me error like this.
Parse error: syntax error, unexpected '$expiry_n' (T_VARIABLE), expecting identifier (T_STRING)
foreach($expiry_options as $arr){ $sel = !empty($_POST['expiry_date']) && $_POST['expiry_date'] == $arr ? 'selected' : '';\ $date = date('Y-m-d H:i:s'); $expiry_n = date("Y-m-d H:i:s", strtotime("$date + $arr")); ?><option value="<?php echo $expiry_n; ?>" <?php echo $sel; ?>><?php echo $arr; ?></option><?php }
-
here's a tip for the expire week number option menu. you should pass the minimum of data through the form, because you must validate all form data. change the code to submit just he the week number as the value, then using the submitted week number, calculate the actual expire date in the form processing code code.
Your options input code works great. That solves that problem.
For the expiry date. I should mention that I also have expiry dates listed in hours as well. Like this.
<select name="expiry_date"> <?php $date = date('Y-m-d H:i:s'); $expiry_1 = date("Y-m-d H:i:s", strtotime("$date + 12 hours")); $expiry_2 = date("Y-m-d H:i:s", strtotime("$date + 24 hours")); $expiry_3 = date("Y-m-d H:i:s", strtotime("$date + 1 week")); $expiry_4 = date("Y-m-d H:i:s", strtotime("$date + 2 weeks")); ?> <option value="0">Expires In</option> <option value="<?php echo $expiry_1; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_1) { echo 'selected'; } } ?> >1 week</option> <option value="<?php echo $expiry_2; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_2) { echo 'selected'; } } ?> >2 weeks</option> <option value="<?php echo $expiry_3; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_3) { echo 'selected'; } } ?> >1 week</option> <option value="<?php echo $expiry_4; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_4) { echo 'selected'; } } ?> >2 weeks</option> </select>
-
for the part one problem, you are testing the wrong variable in the second <option.... code. you have - if($_POST['expiry_date'] == $expiry_1 for both <options. the second one should be $expiry_2. if you dynamically produce your option lists, from a data definition (usually an array or data stored in a database table), you can avoid errors like this, since the general purpose php code that makes use of the data definition will not make copy/paste errors or typos.
for the part two problem, when you display the form, your php code needs to produce enough form fields to hold the data you have on the server-side to to redisplay. initially, with no data to display, output the the single set of form fields you now have, which wouldn't have anything to put into the value='....' attributes, but any time there is existing submitted form data, loop over the data, outputting the set of form fields with the correct data in the value='....' attributes.
edit: for the html markup in your jquery code to dynamically add form fields, see the following link for a 'template' method so that you don't have to repeat the markup in your html and in the javascirpt - http://forums.phpfreaks.com/topic/298777-dynamic-for-additions/?hl=%2Btemplate&do=findComment&comment=1524053
1. That was a mistake when I was adding the code in the message. My normal expiry_date has many more fields, so I simplified it to only 2 options. But rest assured, they have correct variables.
Normally I would get the data list from the db, but in this case I have no other option. I need to insert an expiry date into the db and this is the best method I found that worked.
2. I did follow the instruction on the provided link. It works..in a sense that I can get a new row of the inputs data by clicking + or delete it with -. Still have the same issue regarding them disappearing after submit.
Just to make it clear, this is the for loop I am using.
for($i = 0; $i < count($_POST['option_title']); $i++) { if(trim($_POST['option_title'][$i]) != '' && trim($_POST['option_quantity'][$i]) != '' && trim($_POST['option_retail_price'][$i]) != '' && trim($_POST['option_discount_price'][$i]) != '') { $insert_options->execute(array( $get_item_id, $_POST['option_title'][$i], $_POST['option_quantity'][$i], $_POST['option_retail_price'][$i], $_POST['option_discount_price'][$i] )); } }
-
OP, Just learned something new. if(isset($_POST['submit']) can FAIL in Internet Explorer if form is submitted with all empty fields, and there is no name attritbute for submit therefore anything within that code will fail since it will never run.
The no fail way is to do:
if($_SERVER['REQUEST_METHOD'] == 'POST')
I am digging deep into if ($_POST) to see if there are any issues I don't know about with that method.
Got ya. Will keep it in mind. Thanks.
-
There are two parts to my question.
Part 1.
I have a form. You know when you submit a form and if there is an error, the form will reset the input values unless you have the them "selected"? Well I have an issue with one of those inputs.
Here is the code. For some reason the input value doesn't get selected on form reset. It inserts to the database fine.
<fieldset> <label>Expiry Date</label> <select name="expiry_date"> <?php $date = date('Y-m-d H:i:s'); $expiry_1 = date("Y-m-d H:i:s", strtotime("$date + 1 week")); $expiry_2 = date("Y-m-d H:i:s", strtotime("$date + 2 weeks")); ?> <option value="0">Expires In</option> <option value="<?php echo $expiry_1; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_1) { echo 'selected'; } } ?> >1 week</option> <option value="<?php echo $expiry_2; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_1) { echo 'selected'; } } ?> >2 weeks</option> </select> </fieldset>
This is another example of select drop down. But this one below works fine.
// this select option's input values get selected on form reset. <fieldset> <label>City</label> <select name="city_id"> <option value="0">Select City</option> <?php $get_city = $db->prepare("SELECT city_id, city_name FROM cities WHERE city_id > :city_id"); $get_city->bindValue(':city_id', 0); $get_city->execute(); $result_city = $get_city->fetchAll(PDO::FETCH_ASSOC); if(count($result_city) > 0){ foreach($result_city as $row) { $get_city_id = intval($row['city_id']); $get_city_name = $row['city_name']; ?><option value="<?php echo $get_city_id; ?>" <?php if(empty($_POST['city_id'])) {} else { if($_POST['city_id'] == $get_city_id) { echo 'selected'; } } ?> ><?php echo $get_city_name; ?></option><?php } } else {} ?> </select> </fieldset>
Part 2.
This relates to my previous topic.
I am trying to do the same thing as above, which is show input values on form reset. But this is slightly more complicated as it is an array.
Looking at the code, you can see that you can add more fields through jquery. That all works. Inserting their values from multiple groups of fields into the db also works fine. But once again, if the form resets or submits, only the 1st group of fields show the selected values in the input fields. The 2nd or 3rd group of fields generated through the jquery disappear after submit. But again, their values do insert into the db fine.
Here's the html and jquery code.
<div id="options-parent"> <h2>Add Options</h2> <button class="add_field_button">Add More Fields</button> <div class="options-child-row"> <div class="option-float"> <label>Quantity</label> <input type="number" name="option_quantity[]" multiple min="1" max="1000000" step="1" value="<?php if(!empty($_POST['option_quantity'])) { echo $_POST['option_quantity'][0]; } else {}; ?>" /> </div> <div class="option-float"> <label>Retail Price</label> <input type="number" name="option_retail_price[]" multiple min="5" max="1000000" step="1" value="<?php if(!empty($_POST['option_retail_price'])) { echo $_POST['option_retail_price'][0]; } else {}; ?>" /> </div> <div class="option-float"> <label>Discount Price</label> <input type="number" name="option_discount_price[]" multiple min="1" max="1000000" step="1" value="<?php if(!empty($_POST['option_discount_price'])) { echo $_POST['option_discount_price'][0]; } else {}; ?>" /> </div> </div> </div> <script> $(document).ready(function() { var max_fields = 20; //maximum input boxes allowed var wrapper = $("#options-parent"); //Fields wrapper var add_button = $(".add_field_button"); //Add button ID var x = 1; //initlal text box count $(add_button).click(function(e){ //on add input button click e.preventDefault(); if(x < max_fields){ //max input box allowed x++; //text box increment $(wrapper).append( '<div class="options-child-row">'+ '<div class="option-float">'+ '<label>Quantity</label>'+ '<input type="number" name="option_quantity[]" min="1" max="1000000" step="10" value="" />'+ '</div>'+ '<div class="option-float">'+ '<label>Retail Price</label>'+ '<input type="number" name="option_retail_price[]" min="1" max="1000000" step="10" value="" />'+ '</div>'+ '<div class="option-float">'+ '<label>Discount Price</label>'+ '<input type="number" name="option_discount_price[]" min="1" max="1000000" step="10" value="" />'+ '</div>'+ '</div>' ); //add input box } }); $(wrapper).on("click",".remove_field", function(e){ //user click on remove text e.preventDefault(); $(this).parent('.options-child-row').remove(); x--; }) }); </script>
What do you think?
-
for($i = 0; $i < count($_POST['option_title']); $i++) { if (trim($_POST['option_title'][$i]) != '' && trim($_POST['option_quantity'][$i]) != '' && trim($_POST['option_retail_price'][$i]) != '' && trim($_POST['option_discount_price'][$i]) != '') { $insert_options->execute(array( $get_item_id, $_POST['option_title'][$i], $_POST['option_quantity'][$i], $_POST['option_retail_price'][$i], $_POST['option_discount_price'][$i] )); } }
Perfect. That works.
Thank you for clearing it up.
-
Check the individual values inside the loop, before calling execute()
I take it it's something like this? If so, it doesn't work.
$insert_options = $db->prepare("INSERT INTO item_options(item_id, option_title, option_quantity, option_retail_price, option_discount_price) VALUES(?,?,?,?,?)"); for($i = 0; $i < count($_POST['option_title']) && $i < count($_POST['option_quantity']) && $i < count($_POST['option_retail_price']) && $i < count($_POST['option_discount_price']); $i++) { $insert_options->execute(array( $get_item_id, $_POST['option_title'][$i], $_POST['option_quantity'][$i], $_POST['option_retail_price'][$i], $_POST['option_discount_price'][$i] )); }
-
That will only make things worse and remove the empty items. You could now have a situation where
title array quantity array price array ----------- -------------- ------------ item 1 5 10.00 item 2 3 item 3 2 1000.00
After filtering the array, you get
title array quantity array price array ----------- -------------- ------------ item 1 5 10.00 item 2 3 1000.00 item 3 2
so you are now charging for item 2 at the item 3 price
I see. So what would be the alternative solution to this problem?
-
You are testing that the title, quantity and price arrays are not empty, but you could still have blank values inside those arrays
Got it.
I have the solution now. I have to add array_filter to it like this.
!empty(array_filter($_POST['option_title']))
-
I have one more question "benanamen".
The code seems to always insert in the db, even if I don't require it. For eg. I have it set so that if input fields are not empty, it insert. If not, do nothing. But it still inserts for some reason.
What do you think is going on?if(!empty($_POST['option_title']) && !empty($_POST['option_quantity']) && !empty($_POST['option_retail_price']) && !empty($_POST['option_discount_price'])) { $insert_options = $db->prepare("INSERT INTO item_options(item_id, option_title, option_quantity, option_retail_price, option_discount_price) VALUES(?,?,?,?,?)"); for($i = 0; $i < count($_POST['option_title']); $i++) { $insert_options->execute(array( $get_item_id, $_POST['option_title'][$i], $_POST['option_quantity'][$i], $_POST['option_retail_price'][$i], $_POST['option_discount_price'][$i] )); } } else { echo 'do nothing.'; }
-
I know a record id is needed. What I am saying is you don't need to create an extra variable unless you are transforming it somehow.
If $_POST is true, your form has been submitted so no need to see if submit isset. Less code, much cleaner and does the same exact thing.
Yes, but no. You dont want to display the system error messages to the user. The way I handle errors is display some generic message to the user, log the error to my error log and have the system email me the details as soon as there is an error. I have an option to turn debugging on in which case it will display the full errors in the app during development.
If you use set_exception_handler you don't have to keep writing try/catch blocks all over.
Ahh I see. I will check out set_exception_handler.
Thanks for clearing it up.
-
FYI: This is completely unnecessary. Don't create extra code that does nothing.
$record_id = $_GET['record_id'];
You dont need all this either:
if(isset($_POST['submit'])
Just use:
if ($_POST)
Also, all the following is unnecessary. Just put your query in a try/catch block. If the query fails you will catch the error. For a global solution to catching errors you can use set_exception_handler. What you have below will not tell you anything about the error should you have one.
if($insertStmt == true) {
echo 'success';
} else {
echo 'false';
}
I am only showing part of my real code. This record id is needed my case.
$record_id = $_GET['record_id'];
As for this. Can you please explain why having only $_POST is better than isset method?
if(isset($_POST['submit'])
As for the try/catch block. Are you saying to do something like this instead?
for ($i = 0; $i < count($_POST['title']); $i++) { try { $insertStmt->execute(array( $record_id, $_POST['title'][$i], $_POST['description'][$i] )); echo 'Your post was a success.'; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; echo 'Your post was a failure.'; } }
-
Alright so I have it working now. For future reference, here's the entire code based on what "benanamen" wrote.
// get record id from url parameter $record_id = $_GET['record_id']; if(isset($_POST['submit']) { $insertStmt = $db->prepare("INSERT INTO datatable (record_id, title, description) VALUES (?,?,?)"); for ($i = 0; $i < count($_POST['title']); $i++) { $insertStmt->execute(array( $record_id, $_POST['title'][$i], $_POST['description'][$i] )); if($insertStmt == true) { echo 'success'; } else { echo 'false'; } } } <form action="" method="post"> <input type="text" name="title[]" value="" /> <input type="text" name="title[]" value="" /> <input type="text" name="description[]" value="" /> <input type="text" name="description[]" value="" /> <input type="submit" name="submit" value="Post" /> </form>
-
if ($_POST)
{
$insertStmt = $db->prepare("INSERT INTO datatable (record_id, field1, field2) VALUES (?,?,?)");
for ($i = 0; $i < count($_POST['field1']); $i++)
{
$insertStmt->execute(array(
$_POST['record_id'],
$_POST['field1'][$i],
$_POST['field2'][$i]
));
}
}
Got it. Last question. Do I subsitute the $_POST fields with my title and description I have from input values?
Like this.
for ($i = 0; $i < count($_POST['field1']); $i++) { $insertStmt->execute(array( $_POST['record_id'], $_POST['title'][$i], $_POST['description'][$i] )); } }
If so, does the "count($_POST['field1'])" stays the same or what?
-
if ($_POST)
{
$insertStmt = $db->prepare("INSERT INTO datatable (field1, field2) VALUES (?,?)");
for ($i = 0; $i < count($_POST['field1']); $i++)
{
$insertStmt->execute(array(
$_POST['field1'][$i],
$_POST['field2'][$i]
));
}
}
Well that's a unique approach. One more thing. What if I want to insert a unique non array field in the same stmt as the array fields?
Like this. Where would I add that in your code?
$_POST['record_id'];
-
For eg. I have this code. Right now it only inserts 1 row with 1 value each. How can I make it in a array so that it inserts 2 rows with 2 different values each?
<?php $title = $_POST['title']; $desc = $_POST['description']; $insert = $db->prepare("INSERT INTO record(title, description) VALUES(:title, :description)"); $insert->bindParam(':title', $title); $insert->bindParam(':description', $desc); if($insert->execute()) { echo 'success.'; } else { echo 'failed.'; } ?> <input type="text" name="title[]" value="" /> <input type="text" name="title[]" value="" /> <input type="text" name="description[]" value="" /> <input type="text" name="description[]" value="" />
-
Make sure you are referencing the timer javascript file (and jquery) before the foreach loop?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript" src="timer.js"></script>
Ahh yes. I had it in the footer originally. I didn't think it mattered if I put it in the header or footer, but apparently it does. It works now.
Thank you so much Ch0cu3r. Your simple steps really made it clear for me to understand. Other wise I would be chasing in circles from all the other tutorials.
-
You will have to create a new timers inside the foreach loop. Example
foreach($rows as $k => $row) { $target_date = $row['target_date']; $timeLeft = (strtotime($target_date) - time()) * 1000; // append the array key to make a unique name for each counter $counterName = "counter_$k"; ?> <input type="hidden" class="target-date" value="<?php echo $timeLeft; ?>" /> <div class="counter <?php echo $counterName ?>"> <span class="hour">00</span> <span class="min">00</span> <span class="sec">00</span> </div> <script> // initiate new timer new Timer($('.<?php echo $counterName; ?>'), <?php echo $timeLeft; ?>); </script> <?php }
Can you please double check your above code? It's giving me an error "ReferenceError: Timer is not defined".
Which is this line.
new Timer($('.<?php echo $counterName; ?>'), <?php echo $timeLeft; ?>);
-
So the target date is coming from the database. In that case use PHP to calculate the difference between the two dates. Then have PHP set the value for the timeLeft javascript variable
// subtract the two dates and then multiply by 1000 to get milliseconds $timeLeft = (strtotime($target_date) - time()) * 1000; <script> $(document).ready(function(){ // echo $timeLeft value to set timeLeft javascript variable var timeLeft = <?php echo $timeLeft ; ?>; var timer = new Timer($('#counter'), timeLeft); }); </script>
That does work.
One last thing. I am retrieving multiple records from the db. Each of the records have their own unique countdown timer. Right now, it's only showing the countdown timer for the newest record created, while the rest of the records(that are not expired) show 00:00:00. So I was wondering, what can I do so that the countdown works for all the records?
Here is the setup of foreach loop.
foreach($rows as $row) { $target_date = $row['target_date']; $timeLeft = (strtotime($target_date) - time()) * 1000; ?> <input type="hidden" class="target-date" value="<?php echo $timeLeft; ?>" /> <div id="counter"> <span class="hour">00</span> <span class="min">00</span> <span class="sec">00</span> </div> <?php }
-
You don't need to use cookie at all.
All you need to do is to dynamically calculate the timeLeft value by subtracting todays date/time from your target date/time.
For example if you want your timer to countdown until 8pm today (16th October 2015). Then do
// get todays date today = new Date(); // the target date, this will get the date/time for 8PM 16th October 16th 2015 targetDate = new Date(2015, 9, 16, 20); // subtract the two dates to get the difference in millisecons var timeLeft = targetDate - today;
Ahh yes that does work.
Now my question is, since you are using two dates to find the difference in time left, how can I properly add the php date into the javascript "targetDate"? I can't seem to get it to work.
Here is the full code.
// this is the date format when adding to mysql db $target_date = date('Y-m-d H:i:s'); // this is how the date looks in the html when getting the value from the db <input type="hidden" class="target-date" value="2015-10-17 00:17:21" /> // this is the variable I am using to get the above input value to the javascript/jquery var getDate = $(".target-date").val(); // so all together, this is what the code looks like, with your code included. <script> $(document).ready(function(){ var getDate = $(".target-date").val(); // get todays date today = new Date(); // the target date, this will get the date/time for 8PM 16th October 16th 2015 targetDate = new Date(2015, 9, 16, 20); // subtract the two dates to get the difference in millisecons var timeLeft = targetDate - today; var timer = new Timer($('#counter'), timeLeft); }); </script>
-
Simply put, I would like the countdown timer to NOT reset if the page is refreshed. From what I know, I have to use cookies for that. Can you tell me how I can incorporate a cookie in the following code?
I am using this example. http://www.onextrapixel.com/2011/12/01/creating-a-groupon-like-count-down-timer/
The setup is like this.
<html> <head> <!-- 1 --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript" src="timer.js"></script> <!-- 3 --> <script> $(document).ready(function(){ var timeLeft = 12796000; // this is in milliseconds. var timer = new Timer($('#counter'), timeLeft); }); </script> <!-- 4 --> <style> div#counter{ margin: 100px auto; width: 305px; padding:20px; border:1px solid #000000; } div#counter span{ background-color: #00CAF6; padding:5px; margin:1px; font-size:30px; } </style> </head> <body> <!-- 2 --> <div id="counter"> <span class="hour">00</span> <span class="min">00</span> <span class="sec">00</span> </div> </body> </html>
timer.js
function Timer(container, timeLeft) { // get hour, minute and second element using jQuery selector var hoursContainer = $(container).find('.hour'); var minsContainer = $(container).find('.min'); var secsContainer = $(container).find('.sec'); // hold time left var currentTimeLeft = timeLeft; // 1 second = 1000 ms var secondsForTimer = 1000; // hold ID value return by setInterval() var timerInterval; // call setInteval() only when timeLeft is greater than 0 if (currentTimeLeft == 0) { return; } else { //Call setInterval()function and store ID value to timerInterval. timerInterval = setInterval(countdown, secondsForTimer); } //function being passed to setInterval() function countdown() { currentTimeLeft = parseInt(currentTimeLeft - secondsForTimer); if (currentTimeLeft == 0) { //stop calling countdown function by calling clearInterval() clearInterval(timerInterval); return; } else { //calculate hours left var wholeSeconds = parseInt(currentTimeLeft / 1000,10); var wholeMinutes = parseInt(currentTimeLeft / 60000,10); var wholeHours = parseInt(wholeMinutes / 60,10); //calculate minutes left var minutes = parseInt(wholeMinutes % 60,10); //calculate seconds left var seconds = parseInt(wholeSeconds % 60,10); //prefix 0 to hour, min and second counter $(hoursContainer).text((wholeHours < 10 ? "0" : "") + wholeHours + (wholeHours <=0 ? " hr" : " hrs")); $(minsContainer).text((minutes < 10 ? "0" : "") + minutes + (minutes <=0 ? " min" : " mins")); $(secsContainer).text((seconds < 10 ? "0" : "") + seconds + (seconds <=0 ? " sec" : " secs")); } } }
Is there a way to pass the php script through ajax, as oppose to form action?
in PHP Coding Help
Posted
I am trying out a new script for image upload and resize using ajax method. All the ones I've found so far process the php file through the form action="". Since I am inserting other data into the database and calling the other php code directly on the same page as a the html form, I would like to know if there is another way I can run that specific image upload php code through ajax.
This is one the scripts I have looked at .
http://www.sanwebe.com/2012/05/ajax-image-upload-and-resize-with-jquery-and-php
This is what their html form looks like.
I would like to process the "processupload.php" above through the ajax code below and leave the form action="" empty, as I am running other php code on the same page to insert other data as well.
How would you do that?