insert in database from each line of textarea field by php - php

How i can insert in database from textarea field that each line is a table in database
means I want insert in database from each line of textarea field by php
my information like this:
Name | FullName | Age
and database table:
id (auto insert),
name,
fullname,
age
thanks

i would suggest using a delimiter at the end of the line and then convert it into an array using explode(), here is what you could do.
//Make sure your text have (,) comma at the end of every line
$text = 'My Name,
My Full Name,
24';
//Convert it into an array
$text = explode(',', $text);
//fetch the value and assign it to variables then do an insert operation
//Use mysql_real_escape_string() to escape SQL injections.
$name = mysql_real_escape_string($text[0]);
$FullName = mysql_real_escape_string($text[1]);
$age = mysql_real_escape_string($text[2]);
and then you can create query like this.
$query = "INSERT INTO persons(name, fullName, age) values($name, $fullName, $age)";
$result = mysql_query($query);

// assuming the text area value is in $_GET["text"]
$lines = explode("\n", $_GET["text"]);
foreach($lines as $line) {
list($name, $fullName, $age) = explode(" | ", $line);
mysql_query("INSERT INTO table (name, fullname, age) VALUES ('$name', '$fullName', $age)");
}

Hope this helps:
// assuming textarea name is $_POST['data']
$_POST['data'] = 'Jane | Jane Doe | 23
zxc
sadas
John | John Doe | 48
';
// Set and trim data
$data = (array_key_exists('data', $_POST)) ? trim($_POST['data']) : '';
if ($data !== '') {
$lines = explode("\n", $data);
$sql = 'insert into table (name, fullname, age) values ';
$sql_parts = array();
foreach ($lines as $line) {
$sql_part = array(
'name' => null,
'full_name' => null,
'age' => null,
);
// If no divider found, skip this line
if (strpos($line, ' | ') === false)
{
continue;
}
list($sql_part['name'], $sql_part['full_name'], $sql_part['age']) = explode(' | ', $line);
// For the sake of this example
// i will assume all fields are required
// so let's check for that:
foreach ($sql_part as $key => $item) {
// Trim and sanitize the data:
$item = mysql_real_escape_string(trim($item));
// If any item is empty continue to the next line of data
if ($item === '') {
continue 2;
}
$sql_part[$key] = "'".$item."'";
}
$sql_parts[] = '('.implode(',', $sql_part).')';
}
if (empty($sql_parts) === false) {
$sql .= implode(',', $sql_parts);
mysql_query($sql);
}
}

Split the string, for example http://php.net/manual/en/function.explode.php

Related

PHP - Change values in array result

I have part of a code:
$array = (json_encode($data, true));
which gives me a result of:
"["Id\tFirstName\tLastName\tDateOfBirth\tPhone\tAddress1\tAddress2\tCity\tState\tPostCode\tCountry\tEmail"]"
I need to post it in a filed of a database but it looks harder to view and read.
I would want to get result like
"{Id, FirstName , LastName, DateOfBirth, ...}"
It tried some functions like array_implode, array_replace but no success.
My $data content:
array:1 [
0 => "Id\tFirstName\tLastName\tDateOfBirth\tPhone\tAddress1\tAddress2\tCity\tState\tPostCode\tCountry\tEmail"
1 => "Id\tAnna\tGreen\t199/12/12\t25413698\tMemoryLane\t..."
]
What can I try?
1.if you want results to be array of json strings
$results = [];
foreach($data as $dat){
$results[] = json_encode(explode("\t", $dat));
}
var_dump($results);
2.if you want all results to be json string
$results = [];
foreach($data as $dat){
$results[] = explode("\t", $dat);
}
var_dump(json_encode($results));
Old answer -> Before encoding, explode first value od array (string) by '\t' and after that encode array.
$data = explode("\t", $data[0]);
$results = json_encode($data);
// Example data
$data = array(
"Id\tFirstName\tLastName\tDateOfBirth\tPhone\tAddress1\tAddress2\tCity\tState\tPostCode\tCountry\tEmail",
"May\tBe\tMore\tLines\tHere"
);
// Processing
$a = $data;
// Change all \t to comma and put { } around in each item
array_walk($a, function(&$item) { $item = '{ ' .str_replace("\t", ', ', $item) . ' }'; });
// combine all items into a line
$result = implode(', ', $a);
print($result);
// { Id, FirstName, LastName, DateOfBirth, Phone, Address1, Address2, City, State, PostCode, Country, Email }, { May, Be, More, Lines, Here }

How to find a database row that matches a string?

I have a databse table with 100K rows and an array of 100 items. And I need to find if an array item is found in my Users table username row.
My database table Users
| id | username | fullname |
1 John John Smith
2 Elliot Jim Elliot
3 Max Max Richard
My array looks like this
[
{
string: 'Hello, this is Elliot from downtown Las Vegas!'
},
{
string: 'Hey how are you?'
}
]
My idea was to do a foreach loop through every row in my Users table (100k records) and find if it matches in my array, but it is so slow.
foreach ($MyArray as $Array) {
foreach ($dbrows as $dbrow) {
if (strpos($Array['string'], $dbrow['username']) !== false) {
echo 'found it!';
break;
}
}
}
It will be a bit hit and miss as you may find users with all sorts of weird names that match normal words, this approach splits the input into words and then uses them to form an in clause to search the database. So it only looks at records that match rather than all records...
$search = 'Hello, this is Elliot from downtown Las a1 Vegas!';
$words = str_word_count($search, 1);
$bind = str_repeat("?,", count($words));
$bind = trim($bind, ",");
$query = $conn->prepare("select * from users where username in ($bind)" );
$types = str_repeat("s", count($words));
$query->bind_param($types, ...$words);
$query->execute();
$res = $query->get_result();
while($row = $res->fetch_assoc()) {
// Process result
}
It also uses prepared statements, which is where all of the $bind and $types processing comes in. If you look at $query you will see how it's built up.
I think the better way was to separate your search arrays into words, and use it in the query, like:
<?php
// Assuming your search array is $search...
$words = array ();
foreach ( $search as $text)
{
$words = array_merge ( $words, explode ( " ", trim ( preg_replace ( "/[^0-9a-z]+/i", " ", $text))));
}
$words = array_unique ( $words);
$in = "";
foreach ( $words as $text)
{
$in .= ",'" . $mysqli->real_escape_string ( $text) . "'";
}
if ( ! $result = $mysqli->query ( "SELECT * FROM `Users` WHERE `username` IN (" . substr ( $in, 1) . ")"))
{
echo "MySQL error!";
}
// Results at $result
?>
You can use regular expressions:
<?php
$query_string = "bla bla bla...";
$qry = $mysqli_query($conn, "SELECT *FROM table WHERE username REGEXP '$query_string'");
?>
Regular expression matches data individually from table.

How to insert the multiple values in mysql using php

i have the mysql table 'persons' with 3 columns as,
Name Salary Profession
I am sending 3 parameters with values using php get method as,
$name = raj|lokesh|amar
$salary = 10000|20000|30000
$job = telecom|marine|shipyard
I have to insert them in 'persons' table as,
Name Salaray Profession
raj 10000 telecom
lokesh 20000 marine
amar 30000 shipyard
Can any one tell me how can i do this?
You can turn string into an array using the explode function.
You can surely use this in your case, using my little demonstration:
$name = "raj|lokesh|amar";
$salary = "10000|20000|30000";
$job = "telecom|marine|shipyard";
You just set the variables.
Now turn them into exploded arrays:
$name = explode("|", $name);
$salary = explode("|", $salary);
$job = explode("|", $job);
You basically want to get all of the words between the character | and turn each word into an array item, so each word will have it's own index.
now, $name[0] (the first array index),
echo $name[0]; // echoes 'raj'
echo $name[1]; // echoes lokesh'
echo $job[3]; // echoes 'shipyard';
And now you have to loop trough these arrays and insert it in the query:
for ($i = 0; $i < count($name); $i++) {
echo $name[$i];
}
So final solution will look like this:
for ($i = 0; $i < count($name); $i++) {
$query = $pdoObject->prepare("INSERT INTO table (name, salary, profession) VALUES (:name, :salary, :jobs)");
$query->execute(array(
":name" => $name[$i],
":salary" => $salary[$i],
":jobs" => $jobs[$i]
);
}
This is not a direct answer , since you haven't showed us any code.
Try something like this.
<?php
$name = "raj|lokesh|amar";
$salary = "10000|20000|30000";
$job = "telecom|marine|shipyard";
$name = explode("|",$name);
$salary=explode("|",$salary);
$job=explode("|",$job);
for($i=0;$i<count($name);$i++)
{
$q = mysql_query("INSERT INTO `yourtable` VALUES ('$name[$i]','$salary[$i]','$job[$i]')");
}
Try to use
$names = explode("|", $name);
$salaries = explode("|", $salary);
$professions = explode("|", $profession);
and then loop through the arrays ($names, $salaries, $professions) to insert the values in your database.
http://php.net/manual/fr/function.explode.php
Like this
INSERT INTO `persons`(`Name`, `Salaray`, `Profession`) values('raj', '10000','telecom'),('lokesh', '20000','marine'),('amar', '30000','30000')
//ASSIGN THE VARIABLES TO INSERT
$name= '';
$salary='';
$job='';
//INSERT DATA INTO DATABASE
$Input = mysql_query('INSERT INTO persons (name, salary, profession) VALUES ($name, $salary, $job)');
//SEARCH FOR PERSONS
$output= mysql_query('SELECT * FROM persons ORDER BY id ASC');
$personsCount = mysql_num_rows($output); //count output amount
//LOOP PERSONS OUTPUT
if($personsCount > 0){
while($row=mysql_fetch_array($output)){
$id = $row['id'];
$name = $row['name'];
$salary = $row['salary'];
$job = $row['job'];
$personsList .= $name.' '.$salary.' '.$job.'';
}
}
echo $personsList;

In PHP, how to achieve the same purpose like StringTokenizer in Java?

Say I have a String 030512 Jack 25 Male\n030513 David 23 Male\n030514 ..., how to extract the info from this String as a two dimensional table in PHP?
In Java, I can use StringTokenizer, like:
StringTokenizer lineTokenizer = new StringTokenizer("030512 Jack ...", "\n");
List<Student> students = new ArrayList<Student>();
while(lineTokenizer.hasMoreTokens()) {
String line = lineTokenizer.nextToken();
StringTokenizer itemTokenizer = new StringTokenizer(line, " ");
String id = itemTokenizer.nextToken();
String name = itemTokenizer.nextToken();
String age = itemTokenizer.nextToken();
String sext = itemTokenizer.nextToken();
students.add(new Student(id, name, age, sex));
}
Actually, my final goal is extracting this "table-like" info and store them into a Mysql database.
I am not familiar with PHP, could you show me how to do this in PHP, or what is a good practice to implement this two-dimensional data insertion into a Mysql database?
You can use the explode or split functions. E.g.
$records = explode("\n", $raw_data);
foreach($record in $records) {
$fields = explode(" ", $record);
$id = fields[0];
$name = fields[1];
///....
}
Not fancy but easier to understand in my opinion (requires that the string doesn't end with newline though, and that the information is always correctly formatted):
$students = array();
//no newline at the end, or you'll have to add a check for that in the loop.
$str = "030512 Jack 25 Male\n030513 David 23 Male";
foreach(explode("\n", $str) as $student_str) {
list($id, $name, $age, $sex) = explode(" ", $student_str);
array_push($students, array(":id"=>$id,":name"=>$name, ":age"=>$age, ":sex"=>$sex));
}
//For the DB part which has been quite absent.
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$query = "INSERT INTO students (id, name, age, sex) VALUES (:id, :name, :age, :sex)";
$prepared_query = $conn->prepare($query);
foreach($students as $student) {
$prepared_query->execute($student);
}
You could of course execute the queries in the first loop instead if thats what you want.
You can use explode() coupled with list():
foreach (explode("\n", $yourString) as $line) {
list($id, $name, $age, $sex) = explode(' ', $line);
// ...
}
Edit:
Updated the solution to correct a misunderstanding of the original data structure.
You could do like this
$string = "030512 Jack 25 Male\n030513 David 23 Male\n030514";
$array = array_map(function($v) {
return explode(' ', $v);
}, explode("\n", $string));

MYSQL insert comma separated values into separate fields?

I know its a strange question, but I have one input field that does a live search for locations. The final value is displayed like this:
State,Suburb,Post Code
NSW,Sydney,2210
What I need to do now is split the three values into single values and update them into my separate fields for one row.
I don't want to update multiple rows but just one.
e.g.:
fields ( state | suburb | postcode )
values ( NSW | sydney | 2210 )
What php commands would I use to split those commas off and create single $values for each item?
Use explode on the string.
$values = 'A,B,C,D';
$values = explode(',', $values);
Each item can then be accessed from an array indexed from 0.
$val = "NSW,Sydney,2210";
$valArr = explode(",", $val);
$query = "UPDATE MyTbl SET State = '$valArr[0]', Suburb = '$valArr[1]', Post_Code = '$valArr[2]' WHERE ...";
The easiest way I think, see the manual for explode:
$result_array = explode(',', $your_variable);
list($state, $suburb, $postcode) = explode(',', $value);
Would this work?
$header = "State,Suburb,Post Code"
$items = explode(",", $input)
$output = implode("|", $items)
so the output would become State|Suburb|Post Code
to access each value separately, you can use $items[0], $items[1] ..
$data = "NSW,Sydney,2210"
$items = explode(",", $input)
$output = implode("|", $items)
so the output would become NSW|Sydney|2210

Categories