get textarea value, separate by new line, save to database php - php

I have a textarea in my html named add-list. I want to get the value of the textarea per line break and then save it to my database. The problem is, when it saves the input to the database, the second and succeeding entries have a whitespace before the input.
Here is my function for getting the value:
public function add(){
$checker = false;
$names = $this->input->post('add-list');
if (strpos($names, "\n") == TRUE ) { //newline found
$names = nl2br(trim($this->input->post('add-list')));
$namesArray = explode('<br />', $names);
foreach($namesArray as $name) {
$checker = false;
$checker = $this->checkDatabase($name); //check if name already exists in database
if ($checker) {
echo "<script type='text/javascript'>alert('A site in your list already exists. Duplicate sites are not allowed.');</script>";
}
if (!$checker) {
$this->data_model->addCommunity($name);
}
}
$this->index();
redirect(base_url());
}
else if (strpos($names, "\n") == FALSE) {
$checker = $this->checkDatabase($names);
if ($checker) {
echo "<script type='text/javascript'>alert('" . $names . " already exists. Duplicate sites are not allowed.'); window.location.href='".base_url()."'</script>";
}
if (!$checker) {
$this->data_model->addCommunity($names);
$this->index();
redirect(base_url());
}
}
}
What I get in my database is like this:
firstName
secondName //there's a whitespace before 's'
Help me please!!!

Why do you go all the way through nl2br and then explode instead of using explode with a line break? But just use the search or a search engine, e.g. Explode PHP string by new line (long time no PHP, so I might not be quite right).

Related

Creating a simple php page that allows the user to input characters to search for names

I am trying to make a php page where we can input characters and select year of birth
After submitting it should show all the corresponding name but it doesn't work.
For example I input 'a' and the name containing 'a' having the same year as selected should appear.
This is my code:
In data.php I have like this
$person[0]=array('name'=>'Daniel','dateofbirth'=>2000);
$person[1]=array('name'=>'Gaetan','dateofbirth'=>1980);
My function.php
<?php
function comparator($word,$dateofbirth) {
include("data.php");
$p=1;
for($i=0;$i<count($person);$i++) {
$position=strpos(strtolower($person[$i]['name']),$word);
if($position === false) {
$p++;
}
else {
if($dateofbirth==$person[$i]['dateofbirth']) {
echo $person[$i]['name'] ;?><br /><?php
}
}
}
if($p==count($person)) {
echo "No results found";
}
}
?>
And the index.php, I used get method
I think my function.php is the problem but I don't know how to fix it.
I think this should solve your problem - https://3v4l.org/oQ1BC - however I feel it's necessary to say that it's inefficient and in production data are never stored that way, you should store the details of people in a database and connect to it and perform an SQL query. This only answers the original question.
function findPeople($searchString, $YoB, $listOfPeople){
$peopleFound = [];
foreach($listOfPeople as $individual){
if(strpos($individual['name'], $searchString) !== false && $individual['dateofbirth'] == $YoB){
$peopleFound[] = $individual;
}
}
return $peopleFound;
}
$listOfPeople = array();
$listOfPeople[0]=array('name'=>'Daniel','dateofbirth'=>2000);
$listOfPeople[1]=array('name'=>'Gaetan','dateofbirth'=>1980);
print_r(findPeople('a', 2000, $listOfPeople));

Comparison of words from the database and output of the result

I need to check the words received from the database with the user's entered word and if there is a match, then output its value from the database, and if not, then output what the user entered.
The code below works fine if there is a match.
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
}
}
}
}
I'm an amateur in PHP, just learning. And I can't figure out how to output $d_typeplace if no match is found.
I tried to add
else {
echo $d_typeplace;
}
, but I get an array of words from the user entered.
I will be grateful for any help. Also for any suggestions for improving this code.
---Addition---
I apologize for my English. This is a problem in the Russian language, I need to take into account the morphology. To do this, the database has a list of words and their analog, for example, X = Y. I get these words and compare what the user entered. If he entered X, then we output Y. If he led Z, which is not in the database, then we output Z.
Thus, we check $d_typeplace with $d_typeplace_raw and if there is a match, we output $d_typeplace_morf, which is equal to $d_typeplace_raw. And if not, then $d_typeplace (it contains the value that the user entered).
Oh, I'm sorry, I understand myself that I'm explaining stupidly)
I cannot quite understand what you are asking: you need to output the string entered by the user, but you can only print an array?
If this is the case, I think you parsed the string before, in order to therefore you need to do join again the values contained in the array.
Try with:
else {
echo implode(" ", $d_typeplace);
}
--- EDITED ---
Try with:
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
$found = false;
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
$found = true;
break;
}
}
if (!$found) {
echo $d_typeplace;
}
}
}
But I think it would be more efficient, if you implemented the second code snippet written by #Luke.T
I'm presuming you were trying to add the else like this?
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
} else {
echo $d_typeplace;
}
}
}
}
Which was outputting an array because the for loop was continuing, if you add a break like so...
echo $d_typeplace;
break;
It should stop outputting an array. Depending on your use case you could however perform similar functionality directly in your sql query using LIKE ...
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('
SELECT ego_slovoforma_v_predlozhnom_padezhe
FROM dEzpra_jet_cct_tip_mest_obrabotki
WHERE vozmozhnyi_variant_mesta LIKE %' . $d_typeplace . '%');
if ($typeplace_results) {
//Echo result
} else {
echo $d_typeplace;
}
}

How to read a file line by line in php and compare it with an existing string?

I tried to write this program to compare a user-name in a file with an entered user-name to check whether it exists, but the program doesn't seem to work. Please help. The program was supposed to open a file called allusernames to compare the usernames. If the user name was not found, add it to the file.
<?php
$valid=1;
$username = $_POST["username"];
$listofusernames = fopen("allusernames.txt", "r") or die("Unable to open");
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
if($valid != 0) {
$finalusers = fopen("allusernames.txt", "a+");
fwrite($finalusers, $username.PHP_EOL);
fclose($finalusers);
?>
you need to replace linefeed/newline character from each line to compare.
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$cmp = str_replace(array("\r", "\n"), '',$cmp);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
i have added following line in you code
$cmp = str_replace(array("\r", "\n"), '',$cmp);
I havent tested this but I wonder if you could use something like
<?php
$user = $_POST["username"];
$contents = file_get_contents("allusernames.txt");
$usernames = explode("\n",$contents);
if(in_array($user,$usernames))
{
echo "Choose another username";
}
else
{
$contents .= "\n".$user;
file_put_contents("allusernames.txt",$contents);
}
I think things like file get contents etc. need a certain version of PHP but they do make things a lot nicer to work with.
This also assumes that your usernames are seperated by new lines.
Yo can do this more simple with this code:
<?php
$username = $_POST["username"];
$listofusernames = 'allusernames.txt';
$content = file($listofusernames);
if(in_array($username, $content)) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
} else {
$content[] = $username . PHP_EOL;
file_put_contents($listofusernames, implode('', $content));
}
?>

Numeric PHP validation?

I have some code written in php to validate a postcode field in my form. The code is meant to check that the field is not empty (mandatory) and matches one of 5 usable postcodes, if not it displays an alert. The problem i am having is that when i leave the field empty and hit the submit button the proper alert is show but if i enter a wrong value and hit submit the form just loads to a blank screen, can anyone spot a mistake in my code? :
<?php
if (isset($_POST['submit'])) {
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "";
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
return true;
}
$msgp = '<span class="error"><b>Please enter correct postcode</b></span>';
return false;
} else if(empty($post)) {
$msgp = '<span class="error"><b>Please enter postcode</b></span>';
}
}
?>
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi">
<b>Post Code</b>
<br>
<input type="text" id="post" name="post" /><?php echo $msgp; ?>
</form>
return? Return where?
When you return in your main code, it's (nearly) the same as die()'ing.
So when you return, the remaining PHP won't be executed anymore.
I'd consider to set some variable like $success = true/false; instead of returning.
You return false after $msgp = '<span class="error"><b>Please enter correct postcode</b></span>'; therefor you do not continue to the form below... remove the returns from your code to be able to handle and show an error.
You are using return. Are you in a function() {} ? If so, all your variables are in function scope. You could do global $msgp; to make the variable accessible outside of the function.
If not... then you shouldn't use return.
Change php code to
<?php
if (isset($_POST['post'])) {
$post = intval($_POST["post"],0);
$words = array(2747,2750,2756,2760,2777);
$msgp = '<span class="error"><b>'.in_array($post,$words) ? "Please enter postcode" : "Please enter correct postcode" .'</b></span>';
}
There are a lot of things that can be simplified. For example codes as int array and using in_array() function. Return statement should be used to return something from method/function using it in global scope then execution of the current script file is ended. There is no need for it here. If there are more $words values you should consider using simple REGEX /[0-9]{4}/ and preg_match()
You want to display $msgp right? Use echo $msgp;. But you can return to nowhere in your code. (put it in a function).
Try this
<?php
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "<span class='error'><b>Please enter correct postcode</b></span>";
function check($post){
global $words;
$return=true;
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
//$return=true;
}
} else if(empty($post)) {
$return=false;
}
return $result;
}
$return=check($post);
if($return === true){
// echo you are right!
}
else {
echo $msgp;
}

How to determine if file text search returns no matches?

I have created a piece of code that checks files for a user-submitted string within a set of files. The code searches a directory, returns the file, then searches for the string in the file. The user will input the custom string through an input field and then clicking a submit button.
I have successfully been able to create a condition where, if the user does not enter any information, the output will say, "Your search produced no results". However, I have not been able to figure out how to create a condition where, if the user enters a string that isn't found within the files, that the output will also be, "Your search produced no results".
The code for the existing conditional I have as of now is this:
if ((isset($query)) && (empty($query))) {
echo "Your search produced no results";
}
The code that searches for the files and also searches for the string is found here (this is the entire PHP file, actually, and it includes the conditional I posted above.) I need help on how to create another conditional that throws a message if the user-input isn't found in any of the files.
If this seems unclear, I apologize and will clarify any information you need if you think it will help.
Calling Code
$query = $_POST['query'];
if ((isset($query)) && (empty($query))) {
echo "Your search produced no results.";
}
else {
find_files('.');
}
find_files()
function find_files($seed)
{
if (! is_dir($seed))
return false;
$files = array();
$dirs = array($seed);
while(NULL !== ($dir = array_pop($dirs)))
{
if($dh = opendir($dir))
{
while( false !== ($file = readdir($dh)))
{
if($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if (is_dir($path)) {
$dirs[] = $path;
}
else {
if (preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) {
check_files($path);
}
}
}
}
closedir($dh);
}
}
check_files()
function check_files($this_file)
{
$query = $_POST['query'];
$str_to_find = $query;
if(!($content = file_get_contents($this_file))) {
echo("Could not check $this_file");
}
else {
if (stristr($content, $str_to_find)) {
echo("$this_file -> contains $str_to_find");
}
}
unset($content);
}
If the query is not empty the find_files function is simply executed with no instructions of doing something if it returns false, hence you need to evaluate the result of calling find_files. For example you could do:
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
elseif (!find_files('.'))
{
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
with the condition that you update you find_files function to return false for all cases that fail.
or you could update the find_files function to return a string in case of errors and a string empty for succesful execution
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
else
{
$result = find_files('.');
if (!empty($result))
{
echo "<p style=\"color:darkgray; font-family:arial\">".$result."</p>";
}
}
A couple of notes regarding your code that will improve the readability and code quality:
proper indentation will save a lot of time spent in maintenance;
when using if else imbrications ALWAYS use curly braces even if it is only one instructions. Improves readability and avoids errors.
when accessing a variable declared outside a function (in procedural code) use global keyword. For example for accessing the query variable inside the check_files function use global $query; instead of retrieving the variable again from the post.
use $_REQUEST instead of $_POST or $_GET unless there is a special reason for doing otherwise. Unifies code, makes for more readable code and changing from GET to POST or vice-versa can be done without changing code.
You may make your find_files function to return a boolean value: true if at least one matching file was found, false otherwise. Then update your if condition:
if ((isset($query)) && (empty($query)) && !find_files('.')) {
echo "<p style=\"color:darkgray...";
}
Because && is lazily evaluated, find_files will be called only if $query isn't empty.

Categories