Sending delimited from textarea to mysql. Column by "," and row by "\n" - php

I need a user to be able to enter data into a textarea in the following format.
name,email#email.com
name,email#email.com
name,email#email.com
The information would then be sent to the mysql database. My issue is that I want to place the proper name into the first column and the proper email into the second column. Then, when I encounter a line break I would like it to start a new row.
Can anyone help with this? Thanks!

As others have said you can use explode to get the results into an array however, the problem with this approach is there is no guarantee the user will enter the information in the correct order.
What I would do is this. It's still not fool proof (And using separate inputs would be better) but it's better.
<?php
$textareastring = $_POST['textareaname'];
$array = explode("\n",$textareastring );
foreach($array as $value) {
$data = explode(',',$value);
if (strpos($data[1], '#'))
{
$name = $data[0];
$email = $data[1];
}else{
$name = $data[1];
$email = $data[0];
}
}
?>

I would use explode() to separate the different lines and then the fields. Like that:
$lines = explode("\n", $_POST['textarea']);
foreach($lines as $line) {
$fields = explode(',', $line);
$name = $fields[0];
$email = $fields[1];
// DO YOUR MYSQL STUFF HERE
}
There might be better ways out there, but that would work for you.

<?php
$textareastring = $_POST['textareaname'];
$array = explode("\n",$textareastring );
foreach($array as $value) {
$data = explode(',',$value);
$name = $data[0];
$email = $data[1];
//Your mysql query goes here
}
?>

Related

How to loop through a JSON array and put data in variables

I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:
Notice: Trying to get property of non-object
My JSON data looks like this:
{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},
I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?
<?php
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = $data->AttractionInfo[0]->Id;
$attractieType = $data->AttractionInfo[0]->Type;
$attractieStatus = $data->AttractionInfo[0]->State;
$attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
$attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
$attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;
?>
I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.
Update code:
require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);
$sql = "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
echo "success";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.
try this...
$content = json_decode(file_get_contents($url));
foreach($content->AttractionInfo as $data ){
$id = $data->Id;
$type = $data->Type;
$map = $data->MapLocation;
$state = $data->State;
$color = $data->StateColor;
if(!empty($data->WaitingTime)) {
$time = $data->WaitingTime;
}
if(!empty($data->StatePercentage)) {
$percent = $data->StatePercentage;
}
//persist your data into DB....
}
I think you need something like this:
$json = '{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"}]}';
$arr = json_decode($json);
foreach ($arr->AttractionInfo as $key => $attraction) {
foreach($attraction as $key=> $value) {
print_r($key.' - '.$value.'<br>');
$$key = $value;
}
}
echo '<br>';
echo $Id; // it will be last item/attraction id.
We can improve this code. Just say where and how do you want to use it

Php : variable not transmitted into a foreach

Probably a stupid question here, I apologize...
I have a SQL request into a foreach, like below.
The "auth" string is correctly defined, a "echo $auth" returns what I want. But the sql request returns nothing.
// $auth=something;
$val=array(value1,value2,value3);
foreach ($val as $j)
{
$req = mysqli_fetch_array(mysqli_query($link,"select val from user where auth='$auth'"));
$$j=$req[val];
}
My goal is to select the sql fieds contained in the $val array (it perfectly works in others parts of my project). Thanks in advance.
I also tried this, still does not return anything :
$val = array('mail','preferences','info','langue'); // This must be an array
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
$mail = $req[0]; $preferences = $req[1]; $info = $req[2]; $info = $req[3];
My goal is to select the sql fieds contained in the $val array
So the $val contains the fields you want to use on your query. You can use an explode() to retrieve all the fields without a foreach:
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
And the you can get the value:
$value1 = $req[$val[0]]; // First field
Okay, let's resume all that. so we have two methods. First :
$val=array(mail,preferences,info,langue);
foreach ($val as $j)
{
$auth = $_SESSION['auth'];
echo $auth; //this works
$req = "select val from user where auth='$auth'";//this works only in phpMyadmin
$req = mysqli_fetch_array(mysqli_query($link,$req));
$$j=$req[val];
}
echo $mail; //gives nothing of course...
And here's the second one :
val = array('mail','preferences','info','langue');
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
$mail = $req[$val[0]]; $preferences = $req[$val[1]]; $info = $req[$val[2]]; $info = $req[$val[3]];
Still nothing works. No php problem detected, my Mysqli instances work correctly... PLEASE do notice we are in debug mode, so my first code is not optimized of course...
The problem is the use of explode which splits a string on a delimiter and create an array. You already have an array, but you want to make it a string. To do this you can use implode:
$columns = array("mail", "preferences", "info", "language");
$sql = sprintf("SELECT %s FROM user WHERE auth='%s'", implode(",", $columns), $auth);
$query = mysqli_query($sql); //..fetch possible errors
$row = mysqli_fetch_array($query); //..make sure a row was returned
list($mail, $preferences, $info, $language) = $row;
echo $mail;

find and replace a specific string of a a particular line in txt file with php

I want to know that how can I replace a specific word/string of a particular line into a text file with php.
Contents of text file is as below:
1|1|1
nikki|nikki#yahoo.com|nikki
nikki|nikki#gmail.com|nikki
nikki|nikki#hotmail.com|nikki
DETAILS OF FIELDS:
COLUMN:0 = $name,
COLUMN:1 = $email,
COLUMN:2 = $nickname,
DETAILS OF REPLACEMENT:
COLUMN:0 = $newName,
COLUMN:1 = $newEmail,
COLUMN:2 = $newnickName,
From the above content you can guess that the find/search is based on the column:1. Ans if match found, than replace the column:0 OR column:2 [based on the choice].
I tried [for finding the column:1]:
$fileData = file("file.txt");
foreach($fileData as $Key => $Val) {
$Data[$Key] = explode("|", $Val);
if ( trim($Data[$Key][1]) == $email ){
unset($fileData[$Key]);
//REPLACE TAKE PLACE HERE
break;
}
}
[for replace]:
/* REPLACE NAME */
$file = "file.txt";
$oname = "|$name|";$nname = "|$newName|";
file_put_contents($file, str_replace($oname, $nname, file_get_contents($file)));
/* REPLACE NICKNAME */
$file = "file.txt";
$onickname = "|$nickname|";$nnickname = "|$newnickname|";
file_put_contents($file, str_replace($onickname, $nnickname, file_get_contents($file)));
But it was replacing all the matching "$name".
I also tried in the following way:
$fileData[$Key] = str_replace($name, $newName, $fileData[$Key]);
file_put_contents($file,$fileData);
/* $name & $newName -:> $nickname & $newnickname
But it doesn't works.
If i want to replace column:0 ["nikki"] of "nikki#gmail.com" with "nikkigmail", then the data should be:
1|1|1
nikki|nikki#yahoo.com|nikki
nikkigmail|nikki#gmail.com|nikki
nikki|nikki#hotmail.com|nikki
And, if want to replace column:2 ["nikki"] of "nikki#hotmail.com" with "hotmail", then:
1|1|1
nikki|nikki#yahoo.com|nikki
nikkigmail|nikki#gmail.com|nikki
nikki|nikki#hotmail.com|hotmail
May i get the code to be corrected ?
Here is how I would replace something like this. Instead of worrying about str_replace, why not actually modify the array returned by file?
<?php
$email = "nikki#gmail.com"; // Search email
$data = file("file.txt", FILE_IGNORE_NEW_LINES); // Read in the data
foreach($data as $key => $line) {
$bits = explode("|", $line);
if($bits[1] === $email) {
// Update this in place,
$bits[0] = "nikkigmail";
$data[$key] = implode("|", $bits);
}
}
$write = implode("\n", $data); // the data to write however you please.
Keep in mind this can also be expanded to suit your row/column needs. For example, you could use something like this.
/**
* The reason these are named differently is because they don't always
* search/replace. For example, you can find nikki#gmail.com in one row,
* but just be setting a different column in that row to a value..
*/
$match = array('col' => 1, 'str' => 'nikki#gmail.com'); // Search data at row
$update = array('col' => 0, 'str' => 'nikkigmail'); // Replace data at row
$data = file("file.txt", FILE_IGNORE_NEW_LINES); // Read in the data
foreach($data as $key => $line) {
$bits = explode("|", $line);
if($bits[$match['col']] === $match['str']) {
// Update this in place,
$bits[$update['col']] = $update['str'];
$data[$key] = implode("|", $bits);
}
}
$write = implode("\n", $data); // the data to write however you please.

Merging files with php

So, I have two files
In the first file, there is
text:hash
In the other file there is
hash:pass
I wrote some code to match the hash and then print the text (So when ran, I'd get an output of text:pass)
It works fine and it finds all the information, however sometimes it will skip certain ones and just not find anything. (If I go and do it by hand the data is there) So I'm not sure why it will find most of them but not all. Anyway I'm hoping someone can help, the code is below:
<?php
$emailhash = file('emailhash.txt');
$hashpass = file('hashpass.txt');
$list = '';
foreach($emailhash as $data) {
$data = str_replace("\r\n",'', $data);
$array_emailhash = explode(":", $data);
$email = $array_emailhash[0];
$hash = $array_emailhash[1];
foreach($hashpass as $data2) {
$data2 = str_replace("\r\n",'', $data2);
$array_hashpass = explode(":", $data2);
$hash2 = $array_hashpass[0];
$pass = $array_hashpass[1];
if($hash2 == $hash)
$list .= $email.':'.$pass."\r\n";
}
}
file_put_contents('emailpass.txt', $list);
You need to iterate your iterator, for example using multipleIterator, since you reads the entire file into an array, do like this.
$iterator = new MultipleIterator();
$iterator->attachIterator( new ArrayIterator( $emailhash ));
$iterator->attachIterator( new ArrayIterator( $hashpass ));
foreach( $iterator as $value ) {
list($keys1, $keys2) = $iterator->key();
list($value1, $value2) = $value;
}
Take a look at this -> http://br1.php.net/MultipleIterator
This algorithm is very inefficient. try to do this like that
$emailhash = file('emailhash.txt');
$hashpass = file('hashpass.txt');
$hashToEmail = array();
$list = '';
foreach($emailhash as $data) {
$data = str_replace("\r\n",'', $data);
$array_emailhash = explode(":", $data);
$email = $array_emailhash[0];
$hash = $array_emailhash[1];
$hashToEmail[$hash] = $email;
}
foreach($hashpass as $data2) {
$data2 = str_replace("\r\n",'', $data2);
$array_hashpass = explode(":", $data2);
$hash2 = $array_hashpass[0];
$pass = $array_hashpass[1];
if (array_key_exists($hash2, $hashToEmail)) {
$list .= $hashToEmail[$hash2].':'.$pass."\r\n";
} else {
//what to do if you don't have that password hash
}
}
Your design has Big O complexity of n^2 [for 1000 rows it will take 1 000 000 iterations]
the one without nested foreach has a complexity of 2n. [it will take 2000 iterations]. Try to find a solution for that :)
Anyway in both places there is a issue, because you can have a hash collisions (for two different emails you can have the same hash, then for all emails you will print out same (probably wrong password).

how to put array data into text file using php

if i use the following code i got data in text file
{"title":"sankas","description":"sakars","code":"sanrs"}
{"title":"test","description":"test","code":"test"}
but my code is working on
{"title":"sankas","description":"sakars","code":"sanrs"}
so i could not add more rows.where i want to change to get correct results.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
$fd = fopen($file, "a"); // a for append, append text to file
fwrite($fd, $json);
fclose($fd);
use php's file_put_content() more information here http://php.net/manual/en/function.file-put-contents.php
Update :
assuming that the data is correctly being passed. here is what you can do.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
//using the FILE_APPEND flag to append the content.
file_put_contents ($file, $json, FILE_APPEND);
Update 2:
if you want to access the value back from the text file. overlay.txt here is what you can do
$content = file_get_contents($file);
if you want to fetch title, code, and description separately. and if the string is in json then you need to convert it into array first by using.
//this will convert the json data back to array
$data = json_decode($json);
and to access individual value you can do it like this if you have one row
echo $data['title'];
echo $data['code'];
echo $data['description'];
if you have multiple rows then you can use php foreach loop
foreach($data as $key => $value)
{
$key contains the key for example code, title and description
$value contains the value for the correspnding key
}
hope this helps you.
Update 3:
do it like this
$jsonObjects = file_get_contents('./videos/overlay.txt');
$jsonData = json_decode($jsonObjects);
foreach ($jsonData as $key => $value) {
echo $key . $value;
//$key contains the key (code, title, descriotion) and $value contains its corresponding value
}

Categories