onblur not returning the most updated value - php

Please excuse my ignorance. I want to always retain the current value (that I have supplied by changing the default value) in the input box when I click outside the text box. But the following code returns to the default value if after modification I again click the text box and then click outside the text box. But I want to retain the most updated value always in the textbox.
Perhaps I have to make changes in the area this.value=' <?php echo "$r1[MAJORS1]" ?>';, but not understanding how to do that.
Any help please
onfocus="if(this.value!=''){ this.value=''; this.style.color='#000';}"
onblur="if(this.value==''){ this.value='<?php echo "$r1[MAJORS1]"?>'; this.style.color='#000';}"

I believe you're looking for:
<input type="text"
data-value="<?php echo htmlentities("$r1[MAJORS1]"); ?>"
placeholder="<?php echo htmlentities("$r1[MAJORS1]"); ?>"
onfocus="if(this.value!=''){
this.value='';
this.style.color='#000';
this.setAttribute('placeholder',this.getAttribute('data-value'));
}"
onblur="if(this.value==''){
this.value=this.getAttribute('data-value');
this.style.color='#000';
}else{
this.setAttribute('data-value',this.value);
}"
value="<?php echo htmlentities("$r1[MAJORS1]"); ?>">
Not exactly pretty though. Messing with the default functionality of the user's browser has a tendency to confuse. I believe my placeholder usage, though, will make it less confusing for the user that their input will revert to whatever the placeholder reads.
See my jsfiddle here: http://jsfiddle.net/3Lvs77bv/
I don't, however, know if MAJORS1 is supposed to be a constant or a key in your $r1 array, though. If it's a key, make sure to quote it to prevent warnings otherwise PHP will think it's a constant. But PHP will fallback, in any case, if the constant isn't defined and treat it as a key in the array, although will generate warnings.
Edit:
If you'd like to allow for blank values, you could either add a button to clear the field like so:
http://jsfiddle.net/3Lvs77bv/1/
Or, as I'd suggest, simply get rid of all the clutter you're trying to code, which affect the user's default browser functionally, and simply use this.select() instead when the field is focused:
http://jsfiddle.net/3Lvs77bv/2/

Related

Php: about echoing a null variable

I'm currently learning php using Murach (the book, published in 2010). One of the exercises has these statements:
<label>Investment Amount:</label> <input type="text" name="investment"
value="<?php echo $investment; ?>"/><br />
<label>Yearly Interest Rate:</label> <input type="text" name="interest_rate"
value="<?php echo $interest_rate; ?>"/><br />
<label>Number of Years:</label> <input type="text" name="years"
value="<?php echo $years; ?>"/><br />
The whole gist is that the value attributes above with the echo statements have variables which have not been assigned any value at first, so the textbox is supposed to be empty according to the book. But later on the exercise this same page will be called again and the variables will now have values, thus they will be printed on the textbox. Here's the book's explanation:
These echo statements display the variables that contain the data that
the user has previously entered into the form. The first time this
page is displayed, though, these variables won’t contain data so the
text boxes will be empty.
However, upon running the program for the first time, the textboxes are in fact not empty:
Since this book was published 5 years ago I'm guessing either they worked then but do not now, or the code itself is wrong. Can anyone tell me if this is just obsolete code or is it really broken to begin with? And how can I fix it to get the desired effect of an empty textbox using a null variable?
Thanks!
You should check if they are defined.
i.e.
<?php echo (isset($years)) ? $years : ''; ?>
Also, if you turn off display_errors in your php.ini this won't happen, however this would be an ill-advised solution
The most important way of programming is programming in such a way, that someone else can also understand it. So in that case, if you plan to use this variable, declare and comment it before:
$investment = ''; // Future post investement variable, on startup empty
$interest_rate = ''; // Future interest_rate variable, on startup empty
$years = ''; // Future years variable, on startup empty
In that case everyone is sure what each variable is, and what it will contain. And no undefined error will occur.
Also notice that turning off warning display, as mentioned in comments and answers, isnt a good idea. When you write nice code, no warnings should be displayed. And turning them off is of course not a solution.
The only MUST do is to turn off warnings and errors on production, to not give hackers any possible clue, even if something goes wrong. And save them in some sort of error logger.
If you plan to use this variable with post, I suggest doing something like that:
$investement = (isset($_POST['investment'])) ? safety($_POST['investment']) : '';
Where safety is your own safety check function (remove special characters, and prevent mysql injection if you plan to echo / store data). It is the same as writing:
if (isset($_POST['investment'])) {
$investement = safety($_POST['investment']);
}
else {
$investement = ''; // init value
}
A Notice is what it is, a notice, it doesn't prevent your code from executing as such. Of course if the variable / code generating the notice is used elsewhere you can run into trouble.
So, the book is somewhat right, but I would say that it's bad practice since that you should always aim to have 0 warnings / notices, which means that you should do as #Swifty mentioned and check whether the variable is set.

Wordpress- Echo PHP into Shortcode

I've run into a little bit of a snag with shortcodes. I want it to take the variable and put it in place for the text that should usually go there, but instead of working it just doesn't load it up, even though I've tested it with the echo to see if it's putting anything out and it is.
<?php
$artistslug = the_field('artist_cat_slug');
echo $artistslug; // Here for test reasons
echo do_shortcode('[product_category category="'.$artistslug.'"]');
?>
Any help would be greatly appreciated.
Most probably, the_field() displays the value. The plugin you are using might have a corresponding function to return the value instead, for e.g. get_the_field(). Use that instead.
Edit after clarification in comments
From the documentation for the_field() (emphasis mine):
Displays the value of the specified field. (this is the same as echo get_field($field_name))
Exactly. Use get_field() instead.

In php, using GET command for same parameter multiple times and php tags

First of all, I heard some web-servers allow you to reach parameter with $a instead of $_GET[a], this is not the case here.
Anyway, I have to reach a multiple times, so instead of doing $a = $_GET[a], I instead use $_GET[a] everytime. In single php tag as in <?php ?>, is that an issue, should I absolutely use variables? does it matter?
Another thing is my php file is really scrambled in my html, I wonder if does it matter with multiple gets?(should not, im just worried)
Thanks.
What you refer of using just $a instead of $_GET['a'] (or $_POST['a'] too) is an old feature known as register_globals. This feature was dangerous and leading to messy code, so it was considered deprecated in PHP 5.3 and finally removed in PHP 5.4.
Then, using $_GET['a'] everywhere in your scripts may lead to problems, because you should never trust user input (all things coming from $_GET, $_POST, $_REQUEST, $_COOKIE and some from $_FILES or $_SERVER). It is recommended to do something like $a = sanitize($_GET['a']); (the sanitize function does not exist, depending on what type of value are you expecting, you should check that what you get is an integer, or a valid date, or whatever, depending on your needs). From now on you should stop referencing $_GET['a'] and use instead the new sanitized variable you have just created $a. Because if you were using always $_GET['a'], chances are that you forget to sanitize it someplace.
Also, before sending this sanitized variable into a SQL query, you should escape it or use it inside a prepared statement to avoid SQL injections. Before outputting it to an html for the user to see, use htmlspecialchars to avoid XSS attacks.
And finally, about having multiple php blocks mixed with html blocks, this is only bad for maintenance reasons, because in the long run it will be a complete mess. Try to separate the html you send the user from the php code. Try to read something about the MVC pattern (Model-View-Controller) (this link is probably too complicated or maybe you don't see the utility right now for you that are just beginning with php (at least I didn't see how it was way better than mixing html with php, for all the complexity needed), but try to grasp the idea behind it) .
First of all, I heard some web-servers allow you to reach parameter with $a instead of $_GET[a], this is not the case here.
This is a PHP config setting called register_globals. It is insecure and should NOT be used. See this question for more information.
You can access an element in the $_GET array as many times as you like, it will not cause problems. However if you are printing an element of the $_GET array (or any other user submitted data) to the page, you should run it through htmlspecialchars() or the like before printing it out to prevent XSS vulnerabilities.
using a variable is a preference for you to decide it does not matter. but variable is the way forward if you use the same one multiple times.
<?php echo htmlspecialchars($_GET['a']);?>
using a variable means that it reusable again especially if you have added extra code, which mean just editing one variable for all instances.
<?php $a = htmlspecialchars($_GET['a']);
echo $a;
echo $a;
echo $a;
echo $a;
?>

limit user input by php

I have a username textbox. It should only accept between 3 and 10 characters and it should only accept (0, 9) and (A , Z ) values or maybe (- and _),
nothing more.
And if the user inputs a value like $%^# it should give an error
I want to do this with PHP, not Jquery. Can anyone help me with this?
I know I can use
<input name="1" type="text" value="1" maxlength="10" />
But it doesn't give an error to the user and just filters the input value.
Thank you.
regular expression could work
if (preg_match("%^[A-Za-z0-9-_]{3,10}$%", $_POST["1"])) {
// OK
} else {
// ERROR
}
When the value is submitted to your PHP script, you can look at it via the $_REQUEST global variable. In this case, you would reference $_REQUEST["1"]. To make sure the value it contains is of a certain size, use the strlen() function. To make sure that the value only contains certain characters, you can use preg_match_all() and an appropriate regular expression like the following:
[A-Za-z0-9]

pagination and search form issue

I have very basic pagination script and search form with ~4 fields, and action="get" now my problem is that, when i submit my form, i get url like this:
user/people/1/?search=true&country=uk&age=20&online=true ... and so on
so after i submit form everything is just fine, but when i go to page 2 my url changes to:
user/people/2
so my search parameters disappears, this is how i render my links
href="user/people/<?=$next?>"
So my question is what is the best way to keep my paramenters, because now i can only think of for loop and build my link by merging all $_GET values, should i do it like that?
Just append $_SERVER[ 'QUERY_STRING' ] (make sure to htmlspecialchars() it first).
href="user/people/<?php echo htmlspecialchars( "{$next}?{$_SERVER[ 'QUERY_STRING' ]}" ); ?>"
By the way, the PHP short tags <?= ?> are not portable, so you should consider not using those, and using <?php echo ?> instead.
Update:
#Wrikken raises a couple of good points in their answer:
1) passing ENT_QUOTES as the second argument to htmlspecialchars() would be important if single-quoting the attribute value (or to cover it being changed to being single-quoted in the future). This is easy to forget, for me anyway, since I almost always double-quote attribute values. It's unfortunate that it further bloats a call that's already bloated by a long function name.
2) If you're just passing through the query string as-is, then I'd certainly prefer using $_SERVER[ 'QUERY_STRING' ] instead of http_build_query( $_GET ). If, however, you need to change some of the query params, http_build_query() would be the ticket. You can see an example of that in my PHP faceted browser.
Either:
...ople/?<?php echo htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES);?>"
Or:
...ople/?<?php echo htmlspecialchars(http_build_query($_GET), ENT_QUOTES);?>"
Or:
...ople/?<?php echo htmlspecialchars(http_build_query($some_custom_array), ENT_QUOTES);?>"

Categories