I'm trying to do a search with multiple keywords. For testing purposes ,the search string looks like this
http://localhost/admin/search.php?search=live+concert
So far, the search works perfectly!!!
If there is no parameters, im able to echo a message
if (isset($_GET['search'])) {
// split keywords
$keywords = preg_split('/[\s]+/', $_GET['search']);
// search
} else {
echo 'Nothing to search';
}
Here's my problem. When I hit the search button without entering keywords, i get an empty string , like this
http://localhost/admin/search.php?search=
I want to echo an error to the user saying that there is no keywords to search for. I've tried using count($keywords), but i always get 1 as a result when no keywords have been entered.
How do i check if the user hit the search button without entering keyword(s) ?
Thanks
You can use trim($_GET['search']) where you remove any additional spaces and check if then $_GET['search'] is not '' this way even if the user only submits space, your error message shows
if (isset($_GET['search']) && trim($_GET['search']) != '') {
You might be able try something like this:
if (empty($_GET['search'])) {
echo 'You did not enter anything';
}
empty checks to see if the var is either 0, empty, or not set at all. Not that this matters but as of PHP 5.5 empty() supports expressions, rather than only variables.
You can use simple validation as below, this will check if "search" is posted and its not NULL or not having a while space and length is greater than 0
if (isset($_GET['search']) && strlen(trim($_GET['search']))>0) {
// do the search
}else{
echo 'Nothing to search';
}
If the user has clicked the search button, $_GET['search'] will be set but empty, which is why your 'isset' condition is failing. Why not a simple:
if (!trim($_GET['search'])){ //trim removes whitespace from beginning and end
The empty function should work -
if ( isset($_GET['search']) && !empty(trim($_GET['search'])) )
You can use if ($_GET['search'] == '') {/*ERROR*/} or if (strlen($_GET['search']) < 1) {/*ERROR*/}.
These could also be added to your already existing if statement.
The problem with using count is that when you place an empty string as the second argument for preg_split(), an array with one empty string value will be returned: array(''). Therefore, the amount of values in the array will be one.
Related
I need to know how I can detect if my SQL Server column is empty, with spaces or null.
At the moment I have tested the following ways:
if($prof != NULL)
{
echo 'Test';
} else {
}
This 3 ways below:
if($prof != NULL)
if(empty($prof))
if(is_null($prof))
Any of them is working, my $prof is one column from SQL table, I'm getting the column correctly.
In SQL server the column appears like this:
It looks like that I have spaces in there, but I can't tell PHP to do something if there are those spaces.
I need someone who can help me with this because I already tried more than this and I can't figure out how to solve this, I need to echo test, only if the field is not empty, but since it looks like it contains spaces it also does the echo to the ones that are "empty" it stills echo it.
You can use trim to remove all spaces on the beginning and end of the value:
echo (empty(trim($prof))) ? 'Test' : '';
You can also normalize your values on the SELECT directly:
SELECT LTRIM(RTRIM(ISNULL(Profession, ''))) FROM table_name
After using LTRIM, RTRIM and ISNULL you only need to check for empty string:
echo ($prof === '') ? 'Test' : '';
The pattern I use most often is:
SQL:
SELECT COALESCE( RTRIM(prof), '') FROM MyTable
PHP:
If ($prof == '') {
echo 'Empty!'
}
Note that in SQL, a trimmed NULL is a NULL, not an empty string.
I'm designing a semi-basic tool in php, I have more experience server side, and not in php.
My tool contains 10-15 pages, and I am doing the navigation between them with the $_GET parameter.
I would like to check if the query string is empty (to know if I'm in the home page). Is there any php function for this ? Of course I can do it manually, but still?
EDIT: My question is if there is a function that replaces
if(! isset("param1") && .....&& ! isset("paramN")){
...
}
Try below
if(isset($_GET['YOUR_VARIABLE_NAME']) && !empty($_GET['YOUR_VARIABLE_NAME'])) {
}
isset() is used to check whether there is any such variable or not
empty() to check whether the variable is not empty or not
As per your comment, assume your URL as below
http://192.168.100.68/stack/php/get.php?id=&name=&action=delete&type=category
And your PHP script as below
<?php
$qs = $_GET;
$result = '';
foreach($qs as $key=>$val){
if(empty($val)){
$result .= 'Query String \''.$key.'\' is empty. <br />';
}
}
echo '<pre>'; print_r($result);
?>
In my above URL I passed id and name as empty.
Hence, Result will be like below
id is empty.
name is empty.
but I dont think its standard way.
If you want to process something only if all parameters are having some values, they you can move those process inside a if as below
if(empty($result)) {
// YOUR PROCESS CODE GOES HERE
} else {
echo 'Some Required Parameters are missing. Check again';
}
if(isset($_POST['n']) ){
$n = $_POST['n'];
if(!empty($n) || $n==0){
echo "n is any number including 0 but not blank";
}
}
How do I check if the form values are blank but can be 0 ? isset($_POST['$var']) is returning true even if the html form is blank. I tried doing the above code but it still isnt working. I can't seem to find a way to separate a blank form and 0.
Text inputs are considered successfull even if they are empty so don't use isset(). An empty string and 0 are both empty() so don't use it here. Try checking for an empty string:
($_POST['n'] != '')
Or since you are expecting numbers look at is_numeric() or ctype_digit().
I have a problem with $_GET array. On my page a value comes from URL like this.
http://localhost/search.php?subject=Mathematics
I check this $_GET value something like this..
// Check for a valid keyword from search input:
if ( (isset($_GET['subject'])) && (is_string ($_GET['subject'])) ) { // From SESSION
foreach ( $_GET AS $key => $subject) {
$searchKey = $key;
$searchKeyword = '%'.$subject.'%';
}
} else { // No valid keyword, kill the script.
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
Now its working for me. But my problem is I am using another two variables to pass through URL on same page to filter my database values.
echo '<li>Tutor</li>
<li>Institute</li>';
This two links I used to filter my database values (clicking on this link).
$tutor = isset($_GET['institute']) ? '0' : '1';
$institute = isset($_GET['tutor']) ? '0' : '1';
My problem is when I am trying filter database result clicking on the above link its always going this code instead of displaying filtered result.
} else { // No valid keyword, kill the script.
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
Can anybody tell me how I use this 3 $_GET values.
Why not just add a clause in the else:
elseif(!isset($_GET['institute']) && !isset($_GET['tutor']))
{
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
You need to make sure the url looks like this:
http://localhost/search.php?subject=Mathematics&tutor=tutorName&institute=instituteName
A ? denotes the beginning of the URL parameters, an & marks the separation between url parameters
Your problem doesn't seem to be, that you're running into the else loop (or better said: not the only problem). It looks like your first parameter gets lost with the second link. I think, the second link should react like some kind of extended search filter, that shoud be applied to the recently displayed content, or am I totally wrong at understanding you?
Perhaps this could solve your problem for creating the follow-up URLs.
$params = array();
foreach($_GET as $key => $value) {
$params[] = '&'.$key.'='.$value;
}
$url1 = '?tutor=link'.implode('', $params);
$url2 = '?institute=link'.implode('', $params);
And when you output the links:
echo '<li>Tutor</li>
<li>Institute</li>';
Your problem is that you are only checking the $_GET['subject'] variable, which is no being passed in. You could do this in a few ways, all resulting in changing:
if ( (isset($_GET['subject'])) && (is_string ($_GET['subject'])) ) { // From SESSION
1) include all variables in the conditional string:
if ( ((isset($_GET['subject'])) && (is_string ($_GET['subject']))) || ((isset($_GET['institute'])) && (is_string ($_GET['institute']))) || ((isset($_GET['tutor'])) && (is_string ($_GET['tutor']))) ) {
2) Pass in searchKey=1 or something in all your links and use:
if ( isset($_GET['searchKey']) ) { // From SESSION
Revised links:
echo '<li>Tutor</li>
<li>Institute</li>';
If you are looking to pass in more than one variable at once, you will need to put the search keys into an array.
I have a sign up form with about 10 fields and they are all required to be filled in before processing, so trying to avoid all those if checks I came up with this, is this a good method?
foreach($list as $items) {
if(empty($items)) {
$error[] = "All fields are required.";
break;
}
}
or should I make if(empty($field_1) || empty($field_2) etc.. then output the error?
Assuming that your data is coming from $_GET or $_POST, all data fields will be strings. This means that you should be able to do the check in a single function call:
if (in_array('', $list, TRUE)) {
$error[] = "All fields are required.";
}
This looks for strings which are exactly equal to an empty string. If you want to make the comparisons loose (more or less identical to the check that empty() does) just remove the final TRUE.
EDIT Thinking about it, you don't need the strict comparison. I did this to allow for a legitimate field value of '0' (which empty() would not allow) but this will also be permitted with loose comparisons, since '0' != ''.
ANOTHER EDIT If you want to check that the length of the sting is greater than two, you will have to loop:
foreach ($list as $item) {
if (strlen($item) < 2) {
$error[] = "All fields are required.";
break;
}
}
This will also "clear out 0" assuming that by this you mean "not allow a value to be 0". If you also want to disallow '00' (or any other string that results in 0) you can change the if clause to this:
if (strlen($item) < 2 || (!(int) $item)) {
it's ok. If you just want to show message "All fields are required." without showing which field in blank.
Otherwise it will be more user friendly if you check and show which field is left empty.
It's good idea to put it into loop as you did but please note that this will fail even when user inputs 0 and will pass for string containing only spaces, so you may want to make better checks than empty()
I would approach this with an in_array check.
<?php
$fields=array('name','age','yadayada','something_else');
foreach ($_POST as $key=>$value){
if(in_array($key,$fields) && $value!=''){
$$key=$value;
}else{
$error[$key]='This field is required.';
}
}
?>