I have a form where the user enters their first and last names. I want to check if their full name is present in my CSV file, which I use to store all current members / users of my form. The format in which data is stored is firstname,lastname. And if they are present, I want to print out You are already a member.
But that is not what I see in output, when I run my code. It doesn't output that, even if I input names which are present in the CSV file.
Here is my source code:
$JLMembers = Array();
// Open the file of Members
if ($handle = fopen("JLMembers.csv", "r")) {
// Get the next CSV line
while ($data = fgetcsv($handle, 1000, ",")) {
// Add that line to the array
array_push($JLMembers, $data);
}
}
foreach($JLMembers as $JLMember) {
$FirstName = $_GET['FirstName'];
$CurrentMemberFirstName = $JLMembers[0];
if ($FirstName === $CurrentMemberFirstName) {
foreach($JLMembers as $JLMember) {
$SecondName = $_GET['LastName'];
$CurrentMemberSecondName = $JLMembers[1];
if ($SecondName === $CurrentMemberSecondName) {
print "<br>You are already a member<br>";
}
}
}
}
You're using $JLMembers[0], which contains the first row of the CSV, when you should be using $JLMember[0], which contains the first column of the current row in the foreach loop. And you don't need two loops, just compare both columns in one loop.
The code should be:
$FirstName = $_GET['FirstName'];
$LastName = $_GET['LastName'];
foreach ($JLMembers as $JLMember) {
if ($FirstName == $JLMember[0] && $LastName == $JLMember[1]) {
echo "<br>You are a member<br>";
break; // Exit the loop once we found a match
}
}
Related
Here is the PHP / xAjax function we are calling when we click a submit CSV button, I can get a response at the end of the function using a pop up modal that has the correct data but it doesn't get inserted into our database. I want to know why i can return data on the page but once I try to send it to mysql there is no response. There is also HTML code and Javascript involved but I believe there are no issues with those.
$fileHandle = fopen("test.csv", "r");
// Skips Headers in csv file
fgets($fileHandle);
//Loop through the CSV rows.
while (($row = fgetcsv($fileHandle, 10000, ",")) !== FALSE) {
//Print out my column data.
$orderFormData['testdata1'] = $row[0];
if(strlen($orderFormData['testdata1']) == '' ){
$VerifyStatus = 'Missing data in CSV file, please take a look for empty cells.';
}
$orderFormData['testdata2'] = $row[1];
if(strlen($orderFormData['testdata2']) == '' ){
$VerifyStatus = 'Missing data in CSV file, please take a look for empty cells.';
}
$orderFormData['testdata3'] = $row[2];
if(strlen($orderFormData['testdata3']) == '' ){
$VerifyStatus = 'Missing data in CSV file, please take a look for empty cells.';
}
$orderFormData['testdata4'] = $row[3];
if(strlen($orderFormData['testdata4']) == '' ){
$VerifyStatus = 'Missing data in CSV file, please take a look for empty cells.';
}
// Rob //
$orderFormData['Note'] = preg_replace('/[^\da-z \-,#$%&()_+=*#?.]/i', '', $orderFormData['Note']);
if(strlen($contactFormData['testdata5']) == '' ){
$VerifyStatus = 'Please enter a company contact so that we can get in touch if there are any issues with your order!';
}
$DebugText .= "<BR>".$VerifyStatus;
if ($VerifyStatus == 'OK') {
$query = "INSERT INTO testtable set ".
"Status = \"Open\", ".
"Source = \"testportal\", ".
"data1 = \"".$orderFormData['testdata1']."\",".
"data2 = \"".$orderFormData['testdata2']."\",".
"data3 = \"".$orderFormData['testdata3']."\",".
"RecordDate= \"".$q_time."\"";
$DebugText.= "<BR>".$query;
$result = mysqli_query($GLOBALS['link'], $query);
if (!$result){
$objResponse->addScript('swal("Oops...", "'.$VerifyStatus.'", "error");');
};
$rows_affected=mysql_affected_rows();
$DebugText.= "<BR>rows affected: ".$rows_affected;
if($rows_affected>0){
$objResponse->addScript('Swal("Order Recieved", "Check orders page for updates!");');
$objResponse->addScript('clearForms();');
}
} else{
$objResponse->addScript('swal("Oops...", "'.$VerifyStatus.'", "error");');
}
return $objResponse->getXML();
}
You never set $VerifyStatus to 'OK', it should be done just after the While starts then, if you find no errors that will set it to something else the database query will run
while (($row = fgetcsv($fileHandle, 10000, ",")) !== FALSE) {
$VerifyStatus = 'OK';
This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
I need to delete a specific string set from a txt file. Currently, the code works in a similar manner to post the data directly to the file. However, trying to remove the same data, inputted in the same manner, will not allow it. In it's current state, the code looks like this for the string removal.
We were NOT allowed to use prebuilt sorting functions or use functions like str_replace or similar code.
Here is the current code for the string removal:
$blankReplace = "";
$found = false;
$fileData = file($fileInput,FILE_IGNORE_NEW_LINES);
for($i = 0; ($i < count($fileData)) && != $found; $i ++)
{
if($fullNameAndEmail == $fileData[$i])
{
$pos = $i;
$name = $fileData[$i];
$found = true;
}
}
if($found == true)
{
// Exit path. Go to for($j = 0) path
unset($fileData[$pos]);
shuffle($fileData);
}
else
{
//Error Msg
}
$writeToFile = fopen($inputFile,'w+');
for($j = 0;$j<count($fileData);$j++)
{
if(trim($fileData[$j]) != " ")
{
$rewrittenList = trim($fileData[$j])."\n";
fwrite($writeToFile, $rewrittenList);
}
}
The code outputs an error of T_IS_NOT_EQUAL in code upon researching the error. The data comes in as direct data from the file() read, so it should work. The error is pointing at for($i = 0; ($i < count($fileData)) && != $found; $i ++) line currently, but likely also references a similar occurrence in the code.
The data is inputted in the format:
firstname lastname emailaddress
I also need to be able to handle if multiple instances of the mentioned name occur so say we have:
Matt Person emailaddr#email.com
Matt Person emailaddr#email.com
That it will delete one instance, and not all, in cases similar to this.
Any help is appreciated, Thank you for your time in advance.
EDIT:
Example input:
Matthew person person#email.com
John holton person#email.com
Person Name person#gmail.com
The user will input a person's name (in format above) and it will result in removing a person. Say they input into the form:
$fullName = "Matthew person";
$emailAddr = "person#email.com";
The output will edit the data to put the data into a single line again
$fullNameAndEmail = $firstName." ".$lastName." ".$emailAddr;
The output of the code, in this example will remove "Matthew person person#email.com"
So the output in the text file will output:
John holton person#email.com
Person Name person#gmail.com
Edit 2: Code in it's current state
<!doctype HTML>
<html>
<meta charset="utf-8">
<head>
<title>Updating the guest book!</title>
</head>
<body>
<?php
$fileInput = "guestBook.txt";
$fileInputInData = file_get_contents($fileInput); // Gets data from file
$testBool = file_exists($fileInput);
$fullName = trim($_POST["fullName"]);
$emailAddr = trim($_POST["emailAddr"]);
$fileSize = filesize($fileInput);
if(!empty($fullName) and !empty($emailAddr))
{
if($testBool == 0)
{
echo "There was an issue with the file. Please have it checked.</br>";
}
else
{
echo "Made it into else path for testBool </br>";
if($fileSize > 0)
{ #code for truth
echo "Made it into filesize check. Filesize: $fileSize </br>";
$fullNameLen = strlen($fullName);
$emailAddrLen = strlen($emailAddr);
$fullNameArr = explode(" ", $fullName);
$firstName = trim($fullNameArr[0]);
$lastName = trim($fullNameArr[1]);
$fullNameToWrite =$firstName." ".$lastName;
$emailAddrCheck=substr_count($emailAddr, "#");
if ($emailAddrCheck == 1)
{
echo "Email address check passed</br>";
#email addr entered right path
$fullNameAndEmail =$fullNameToWrite." ".$emailAddr." has signed in.\n";
$inputFile = "guestBook.txt";
//$pos = strpos($writeToFile, $fullNameAndEmail);
//$writeToFileEx = explode("\n", $fileInputInData);
$blankReplace = "";
$str = $fileInputInData;
$find = $fullNameAndEmail;
$arr=explode("\n", $str);
Foreach($arr as $key => &$line)
{
If($line == $find)
{
Unset($arr[$key]);
shuffle($arr);
}
}
$writeToFile = fopen($inputFile,'w+');
$rewrittenList = trim($arr)."\n";
fwrite($writeToFile, $rewrittenList);
fclose($inputFile);
}
else {
echo "Email address check failed. Invalid email address entered. </br>
Line 55 occured.</br>";
#email addr entered wrong message
}
//asort(array) sorts array low to high (ascending)
//arsort(array) sorts array high to low (descending)
}
else
{
echo "Did not make it into filesize check. Filesize: $fileSize. Line 63 occured </br>";
}
}
}
else if (empty($fullName) or empty($emailAddr))
{
echo "Error! Line 23: One of the inputs was left empty. Line 69 occured </br>";
}
else
{
echo "Error! Line 23: Did not detect any values in either data area,</br>and program
did not go into first error. Line 73 occured </br>";
}
?>
<br>
</body>
</html>
I think you have overcomplicated it.
I foreach each line and check if it matches.
If it does I unset the line.
After the loop I implode on new line and the string is back to normal but without the $find's.
$str = "Matt Person emailaddr#email.com
John doe doesoe#gmail
Matt Person emailaddr#email.com
Trump donald#whitehouse";
$find = "Matt Person emailaddr#email.com";
$arr=explode("\n", $str);
Foreach($arr as $key => &$line){
If($line == $find){
Unset($arr[$key]);
}
}
Echo implode("\n", $arr);
https://3v4l.org/hmSr7
Okay, I am getting a Undefiend Offset Error on [1] and [2] which should be $Event_Date and $Event_Organization.
The weird thing is that I also have it set to display the row and the data entered for said row. It even displays this data correctly via echo.
Another strange thing is I have a second CSV upload area on the site that is a carbon copy that work correctly. The only differance is the $_GET ($Type) for the url passed Variable.
Maybe I should change it to a $_POST instead? They only thing $Type does is determine if it is a Bulk Entry or Single Entry.
Edit 1
I changed it from a $_GET to a $_POST by adding a hidden field in the form on the prior page, and still received the same error.
$Type = $_GET["Type"];
if($Type == 'Bulk')
{
if ($_FILES['Excel']['size'] > 0)
{
//get the csv file
$file = $_FILES['Excel']['tmp_name'];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
$column_headers = array();
$row_count = 0;
$Count = 1;
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE)
{
if ($row_count != 0)
{
//user input
$Event_Name = $data[0];
$Event_Date = $data[1];
$Event_Organization = $data[2];
echo ' '.$Event_Name.' '.$Event_Date.' '.$Event_Organization.'<br> <br>';
//Add Account Informaion | Login
$Create_Event_Query ='INSERT INTO Event(Event_Name,
Event_Date, Event_Organization)
VALUES(?,?,?)';
$Create_Event_stmt = $conn->prepare($Create_Event_Query);
$Create_Event_stmt->bind_param('sss',$Event_Name,$Event_Date,$Event_Organization);
$Create_Event_stmt->execute();
if(!$Create_Event_stmt)
{
Echo'<h2>Try Again</h2>';
}
else
{
echo'Enter Row: '.$row_count.'<br>';
echo ' '.$Event_Name.' '.$Event_Date.' '.$Event_Organization.'<br> <br>';
}
$Create_Event_stmt->close();
$row_count = $row_count + 1;
}
else
{
$column_headers = $data;
$row_count = $row_count + 1;
}
}
Echo'<h2>GO Back</h2>';
}
else
{
}
}
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));
}
?>
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).