I'm a beginner in PHP and mySQL. I pass a string to the PHP with AJAX and then I split the string after new lines. Later I assign each element in the array to a variable. I want to pass the variables to mySQL database.
Please assume:
$q = "John \n Doe \n 07589334009 \n john.doe#john.com";
Here is my attempt:
$date = date('Y/m/d H:i:s');
$q = $_REQUEST["q"];
$arr = explode(PHP_EOL, $q);
$name = $arr[0];
$surname = $arr[1];
$phone = $arr[2];
$email = $arr[3];
$sql = "INSERT INTO `database`.`myTable` (`Name`, `Surname`, `Phone`, `Email`, `reg_date`, `Valid`)
VALUES ('$name' , '$surname', '$phone', '$email', '$date', '1');";
$result = $conn->query($sql);
When I check my database I only see "JohnDoe07589334009john.doe#john.com" in the name column. Apart from that name and valid are columns are okay.
Just try to do it like
$arr = explode("\n", $q);
$name = $arr[0];
$surname = $arr[1];
$phone = $arr[2];
$email = $arr[3];
Explode using \n and remove spaces from it after exploding
PHP_EOL is not necessary to be "\n", it's a constant holding the line break character used by the server platform. Therefore, it can be used when you are writing to the file system such as logs but not as an equivalent to "\n".
So, you have to replace PHP_EOL with "\n"
Related
It's relatively a common requirement to split a string from a potential splitter:
$name = 'John'; // or can be 'John Smith'
I use
list($firstName, $lastName) = explode(' ', $name) + [1 => null];
or
#list($firstName, $lastName) = explode(' ', $name);
I wonder if you guys use a more concise or more legible method for this?
Oh, I found it!
list($firstName, $lastName) = explode(' ', $name.' ');
The simple trick is appending the glue string to the end of the main string. Tadda!
This make accessing to the second part of the string really easy:
$domain = explode('#', $filter->email . '#')[1]; // for an invalid input the domain will be ''.
Use array_pop to get last_name and all in first_name. Your code not works for name which have three words. Example below also works for three words in name like Niklesh Kumar Raut
Uncomment one $name and comment two to check
//$name = "Niklesh";
//$name = "Niklesh Raut";
$name = "Niklesh Kumar Raut";
$name_arr = explode(" ",$name);
$last_name = array_pop($name_arr);
$first_name = implode(" ",$name_arr);
echo "First Name : $first_name\n";//Niklesh Kumar
echo "Last Name : $last_name";//Raut
Live demo : https://eval.in/871971
you can use regex to check if the string contains space in between, and then explode using the space to get the first and last string.
$name = 'john smith';
$first_name = $name;
$last_name = '';
if(preg_match('/\s/',$name)) {
list($first_name, $last_name) = explode(' ', $name);
}
echo "Hello ".$first_name." ".$last_name;
I am stuck with a problem, I have fetched some values from a MySQL query and put them in to an array like so:
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = rtrim(implode(',', $fullAddress), ',');
echo $string;
so that I can echo out a users address. The problem I am getting is that even if one of these values does not exist (and some don't because they are not all required fields), the comma is still echoed to the screen like:
add1,, town, br2 5lp
because there is an empty value in the database.
What I want to achieve is something like:
add1, town, br2 5lp
if the second part of the address is missing.
Can anyone help me figure this out?
try this.
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = implode(',', array_filter($fullAddress, 'strlen'));
echo $string;
The problem I am getting is that even if one of these values does not
exist (and some dont because they are not all required fields),
the comma is still echoed to the screen
That is what the implode function in php is supposed to do. If you want a different behavior, you will have to either change the way you create your CSV string or do some extra processing on the information you obtain from the implode function.
So use a for loop or a foreach loop to go through the address array. A for loop is faster than a foreach loop.
Using Foreach:
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = "";
foreach($fullAddress as $value)
{
if(!empty($value))
$string .= $value.", ";
}
$string = rtrim($string, ", ");
echo $string;
You can do some extra processing on the created csv string of your own solution by maybe doing a str_replace() of all occurances of ,, with ,. This could be dangerous because if any of the values in your $fullAddress array contain a ,, as a valid string then that will also be replaced too with ,.
What you need is to assure array $fullAddress have no empty value, so php built-in function array_filter make this purpose very easy.
Just change your last codes to:
$string = implode(',', array_filter($fullAddress));
echo $string;
If the second parameter of array_filter is not supplied, all entries of array equal to FALSE will be removed. So just simply use array_filter($fullAddress) it make the code more clear and simple.
Im trying to explode a line where ":" is the first thing to explode and i need to put the 2 pieces into a database after. Then it should read the next line and do the same with that line.
$ex = explode(":", $list);
$array = array($ex);
$ex2 = explode("\r\n", $array);
foreach ($array as $acc)
{
$data = "INSERT INTO `accounts` (username, password) VALUES('$acc[0]', '$acc[1]')";
$query = mysql_query($data);
}
Here is a example of what im trying to do: whodeynati85#yahoo.com:strokeme1
Make that into:
whodeynati85#yahoo.com
strokeme1
Then input the pieces into the Database.
Then look on next line and do the same.
whodeynati85#yahoo.com:strokem221 <-- Explode - Insert
tim#currentelectricsupply.com:3gir2ls <-- Explode - Insert
eliasevans#fuse.net:eulee1922 <-- Explode - Insert
tony#braswellscale.com:Abbey82822 <-- Explode - Insert
I think your explodes are backwards. First you want to explode $list by '\r\n' to get the individual rows. Then, for each row, explode by ':' to get the pieces of data. I'd also highly highly highly highly recommend not storing passwords as plaintext.
$lines = explode("\r\n", $list);
foreach ($lines as $nextLine) {
$lineVals = explode(":", $nextLine);
$lineVals[1] = sha1($lineVals[1]);
$data = "INSERT INTO `accounts` (username, password) VALUES('$lineVals[0]', '$lineVals[1]')";
$query = mysql_query($data);
}
And holy crap I hope that isn't real user account information.
I know the pure basics of PHP, and I need help converting text into variables from a .txt file.
The text inside the .txt file (lets call it 'info.txt') is in a single line as follows:
Robert | 21 | male | japanesse |
So what I need is to convert the information in variables as follows:
<?php
$name = 'Robert';
$age = '21';
$sex = 'male';
$nacionality = 'japanesse';
?>
Note that I want to discard the '|' between every data.
How could I do that using PHP? Using arrays? How?
<?php
$file_content = file_get_contents($fileName);
list($name, $age, $sex, $nationality) = explode("|", $file_content);
echo "Hello ". $name;
Use explode to get information in an array.
You can use php's file_get_contents() & explode() functions
$data = file_get_contents('info.txt');
$parsedData = explode("|", $data);
var_dump($parsedData);
You can "explode" a string in PHP using the explode function. You can also use file_get_contents to get the contents of a file. Assuming that the format of the file is always consistent, you can couple explode with list to assign directly to your variables.
For example
<?php
$string = file_get_contents("file.txt");
$lines = explode("\n", $string);
list($name, $age, $sex, $nationality) = explode("|", $lines[0]);
This reads the contents of "file.txt" into an array, and then assigns the first line's contents to the variables $name, $age, $sex, $nationality
Code
//Step 1
$content = file_get_contents('info.txt');
//Step 2
$info = explode('|', $content);
//Step 3
$name = $info[0];
$age = $info[1];
$sex = $info[2];
$nationality = $info[3];
Explaination
First load the contents in info.txt in a variable using the
file_get_contents() function:
$content = file_get_contents('info.txt');
Second, break up the content into little pieces based on the | character using the explode() function. The broken bits will be stored in an array.
$info = explode('|', $content);
Now assign each value in the array from step 2 to a variable
$name = $info[0];
$age = $info[1];
$sex = $info[2];
$nationality = $info[3];
you can do this step in a shorter way using the list() function as shown in the other answers!
Ultra short, one line code for fun
list($name, $age, $sex, $nationality) = explode("|", file_get_contents("file.txt"));
Here is my PHP Code
It cannot be save to my database I wonder why..
txt = str_replace("♣","'", $string);
First of all write your insert query then we can tell what is the issue
Also you are assigning return value to a variable while variable name doesn't start with $
Change
txt = str_replace("♣","'", $string);
to
$txt = str_replace("♣","'", $string);
Please use function mysql_real_escape_string
$txt = str_replace("♣","'", $string);
$query = "INSERT INTO tbl_contents( functionname,editorcontent) VALUES('". $name ."','". mysql_real_escape_string($str) ."')";
$res = mysql_query($query,$con); //DO QUERY
For more detail read http://in1.php.net/mysql_real_escape_string