PHP Array Explode Twice - php

I have an array which I need to insert into multiple rows of database. The structure of array is like:
$var = "Name1,Age1,DOB1,Relation1.Name2,Age2,Dob2,Relation2.";//And so on, depending on users input
(Dot indicates new line whereas Comma indicates new column)
I need to insert it into database like this:
I first stored all rows in an array like:
$rowsToInsert = explode (".",$var);
I have now:
$rowsToInsert[0] = Name1,Age1,DOB1,Relation1;
$rowsToInsert[1] = Name2,Age2,DOB2,Relation2;
...And So on...
Problem:
What is the fastest way to store these array elements into database having Name, Age, DOB, Relation columns?

May be this will work
$rows = explode (".",$var);
$addslash = addslashes($rows);
foreach($addslash as $val) {
$val_str = str_replace("," ,"','", $val);
$sql = "INSERT INTO tablename (Name, Age, DOB, Relation) VALUES ('" .$val_str. "')";
}

Related

An easy way to write INSERT INTO table VALUES (value1, value2, ...valueN)

I need to insert values from an array using PHP into my database. The array has 40 positions, each position is a value I have to insert into a table of my database.
I need a quick way to write it down and not write $1,$2,$3 ... $39
I tried:
$query = 'INSERT INTO table VALUES($1,$2, ..... $39)';
$result = pg_query_params($dbh, $s, $a[0]); //$a[0] array with 39 positions
But it's too long to write it down. I have another piece of code where I have 140 positions.
Just build an array range from 1 to the length of the array and add the $ and commas:
$values = '$' . implode(',$', range(1, count($array)));
$query = "INSERT INTO table VALUES($values)";
$result = pg_query_params($dbh, $query, $array);

Can I update a record if it exists, and insert it if not, for multiple rows in a single query?

I am trying to write a query to insert an array of many values (say 1000) in a effective way using 'implode'. Here is the code.
$sql = array();
foreach( $return as $key=>$row ) {
$sql[] = '("'.mysql_real_escape_string($row['fullname']).'", '.$row['age'].','.$row['since'].','.'"'.mysql_real_escape_string($row['description']).'")';
}
mysql_query('INSERT INTO data (name, age, since, description) VALUES '.implode(',', $sql));
My query inserts the record array into the data table. I want to change the query so that it will update the record if it exists, and otherwise it will insert the record.
What you probably want is a version of the "ON DUPLICATE KEY" that actually allows you to reference the data being input.
INSERT INTO data (name, age, since, description) VALUES
("Bob", 23, "01-01-1980", "friend"),
("Bill", 33, "03-01-1980", "tall"),
("Jane", 43, "12-01-1980", "thin")
ON DUPLICATE KEY UPDATE age=VALUES(age),
since=VALUES(since),
description=VALUES(description);
Hopefully self-explanatory when you read it?
$sql = array();
foreach( $return as $key=>$row ) {
$sql[] = '("'.mysql_real_escape_string($row['fullname']).'", '.$row['age'].','.$row['since'].','.'"'.mysql_real_escape_string($row['description']).'")';
}
mysql_query('INSERT INTO data (name, age, since, description) VALUES '.implode(',', $sql). ' ON DUPLICATE KEY UPDATE age=VALUES(age), since=VALUES(since), description=VALUES(description);');
Edit, adding this into the user's code above.

How do i insert arrays into mysql using PHP?

I have a complex form that has 11 columns. As for rows they will vary from about 20 to 50 depending on number of students. I am capturing data via a php script as arrays. Each column produces an array. Example, from the form I have fname[], lname[], exam_no[] etc so when the form is submitted with say, 10 rows, I end up with 11 arrays each with 10 entries, which I pass through some php function to remove empty elements. The arrays are being generated with no issues.
I want to insert data from these arrays into mysql using a loop. Basically, lname array will have all first_name for the first name column, lname array will feed the last_name column of the db and so on.
I am just unable to even start constructing the MySQL query to insert the data, I am well conversant with the 'ordinary' insert where you have columns and values and you already know how many rows will insert, mostly one row per insert.
Is is even possible to populate a MySQL Database Table with an insert using a PHP loop and with this many number of columns and making it flexible to insert any number of rows as that will vary each time a user enters student data?
UPDATE
This is what I came up with. It works but NOT as desired!
Arrays are coming like $fname[], lname[] etc
Then I built the master array to be $master_array=array['$fname, $lname];
$sql = "INSERT INTO testing (date, fname, lname) VALUES ";
foreach($master_array as $subarray) {
$sql .= "(NOW( )";
echo 'A nested array: '.$subarray.'<br />';
foreach($subarray as $value) {
$sql .= ", '$value'";
echo 'A Name: '.$value.'<br />';
}
$sql.= "), ";
}
$sql = substr($sql,0,-2); //removes extraneous , at end.
echo $sql;
$result=mysqli_query($dbc, $sql)
or die('Query Failed!');
?>
Since my query involves conactinating small pieces of code, I was printing it after its built to see what is to be inserted. It looked like so;
INSERT INTO table (date, fname, lname) VALUES (NOW( ), 'Andrew', 'Alex'), (NOW( ), 'Peterson', 'Marlon')
As I suspected, it inserts all first names in the first row, and all last names in the second row. The desired result is to insert first names in the first-name column and second names in the second name column. So now I need a way to insert all elements of one array into a single column and then move to the second array and insert it in the next column. That sounds complex, and I wonder if it's doable! Let me be educated by the masters of the php language as I am an intermediate or may be brand new newbie!
Isn't it better to group the information by student?
Example:
<form...>
<? foreach ($students as $id => $info) : ?>
<input type="text" name="fname;<=$id;?>" value="<?=$info['fname'];?>" />
<input type="text" name="lname;<=$id;?>" value="<?=$info['lname'];?>" />
etc
<? endforeach ?>
</form>
(I'm using PHP short tags here)
Then, when you process the form:
$update = array();
foreach ($_POST as $key => $value) {
// key will look like: fname;1, fname;2, etc
// so, split it on the ; sign to separate the field name from the student's id
$data = explode(';',$key);
// result:
// $data[0] = fname, lname, etc
// $data[1] = 1, 2, etc
// you can add some checks to make sure that this field is valid
// and that the id is in fact a valid id (number, > 0, etc)
// sanitize data (however you want, just an example)
$value = mysql_real_escape_string(trim($value));
// now add it to the update array, grouped by student id
$update[$data[1]][$data[0]] = $value;
// result:
// $update[1]['fname'] = 'First name student 1';
// $update[1]['lname'] = 'Last name student 1';
// $update[2]['fname'] = 'First name student 2';
// $update[2]['lname'] = 'Last name student 2';
// etc
}
After that, go through the update array:
foreach ($update as $id => $info) {
$sql = "UPDATE students
SET fname = '".$info['fname']."', lname = '".$info['lname']."'
WHERE id = $id";
mysql_query($sql);
}

MYSQL - INSERT INTO from left

First of all thanks for your help, I'm asking how can I insert data into fields starting from the left? Depending on the entity sometimes several fields at the end are left blank but I need to insert the filled fields into the table. If I try to do this, I obviously get a column-values mismatch error.
Thanks!
The column count you use and the number of values you try to insert have to match. You can specify what you want to insert, so you don't have to pass the columns which aren't needed (and so you don't need to pass "blanks").
INSERT INTO Store_Information (store_name, Sales, Date)
VALUES ('Los Angeles', 900, 'Jan-10-1999')
More information:
http://www.1keydata.com/sql/sqlinsert.html
Just specify only fields names you gonna insert at the moment:
INSERT INTO table (field1, field2, field3) VALUES (value1, value2, value3)
or this way
INSERT INTO table SET field1=value1, field2=value2, field3=value3
no matter is it from left, right or checkered
as SQL query is just a string, you could use some PHP code to build this string in the way you want.
hereis an example code in the form of very simple helper function to produce SET statement dynamically:
function dbSet($fields) {
$set='';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
it can be controlled by $fields array.
used like this
//if we have full set of data
$fields = explode(" ","name surname lastname address zip fax phone");
$query = "INSERT INTO $table SET ".dbSet($fields);
//if we have only three fields ready
$fields = explode(" ","name surname lastname");
$query = "INSERT INTO $table SET ".dbSet($fields);
but you desperately need to learn basic PHP string operations to be able to do such things yourself.
string operations are most important in PHP, as almost every task for PHP is just string manipulation like in your case.
Use querys like
insert into table set col1=val1, col2=val2;
or
insert into table(col1, col2) values(val1, val2);
That is the only way around it. I think method 2 is the most commonly used.
If there is any way you can supply default values for each column use them for the columns you don't have values for.
if all the data can be "NULL", you can setup your query with variables that, if not set, are NULL, example:
$col1 = null;
$col2 = null;
$col3 = null;
$col4 = null;
$col5 = null;
then populate the columns you need
$col1 = 'val1';
$col2 = 'val2';
$query = "INSERT INTO (col1, col2, col3, col4, col5) VALUES ($col1, $col2, $col3, $col4)";
Sincerely I'll never use something like this... but you asked for it...
mysql_query("INSERT INTO People (First_Name, Last_Name, Age)
VALUES ('Marcus', 'Porter', '28')");
mysql_query("INSERT INTO People (First_Name, Last_Name, Email)
VALUES ('Marcin', 'Kruk', 'marcin.kruk#gmail.com')");

how to add multiple records in mysql using php

how to add multiple records in mysql using php. Is using array the only solution to this problem. Because I tried using array but the record that would be added in the database would look like this:
array
You can use a multivalue insert statement (INSERT... VALUES (record1), (record2) etc)
(see http://dev.mysql.com/doc/refman/5.1/en/insert.html)
This is how you can construct such a statement from array of records
$values = array();
foreach($records_array as $record)
$values[] = sprintf("( '%s' , '%s' )", addslashes($record['name']), addslashes($record['email']));
$sql = "INSERT INTO users(name, email) VALUES " . implode(",", $values);
mysql_query($sql);
You need to go through each member of the array:
foreach($array as $record)
{ ... }
and perform an INSERT query for each member or - better for performance - insert all records in one statement as outlined in user187291's answer.

Categories