how to add multiple records in mysql using php - 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.

Related

Insert an array to the database like a separate rows

Sorry if this is a duplicate, but I can't reached the result using answers in similar questions.
Here is my situation:
I have a table (users_temp) with 1 column - Users_id;
And I have an array of values, for example - $usersIds = [1,2,3,4,5];
I want to Insert this array to my table and create 5 new rows.
I was trying smth like that, but it doesn't work:
$newdata = "'" . implode("','", $usersIds) . "'";
db_query("INSERT INTO db.users_temp (user_id) VALUES ($newdata)");
Can you help me, please?
Assuming that the $userIds field is safe (all INTs) then just amend your implode a touch.
$newdata = implode("),(", $usersIds);
db_query("INSERT INTO db.users_temp (user_id) VALUES ($newdata)");
You might want to add a check that the array has more than 0 elements.
You can do this
$usersIds = [1,2,3,4,5];
foreach ($usersIds as $user_id) {
db_query("INSERT INTO db.users_temp (user_id) VALUES ($user_id)");
}
To insert multiple rows in a single statement:
sql:
insert into users_temp (user_id)
values (?), (?), (?) [...]
php:
$userIds = array(1, 2, 3, 4, 5);
$placeholders = rtrim(str_repeat('(?),', count($userIds)), ',');
$sql = "insert into users_temp (user_id) values ($placeholders)";
$stmt = $pdo->prepare($sql);
$stmt->execute($userIds);
Your code can build up the placeholders string as above.

Using On Duplicate Key Update with an array

I'm relatively new to MYSQL and am having trouble combining idea I have read about. I have a form generated from a query. I want to be able to insert or update depending on whether there is currently a matching row. I have the following code which works for inserting but I;m struggling with the On DUPLICATE UPDATE part I keep getting a message saying there is an error in my syntax or unexpeted ON depending on how I put the ' .
require_once("connect_db.php");
$row_data = array();
foreach($_POST['attendancerecordid'] as $row=>$attendancerecordid) {
$attendancerecordid=mysqli_real_escape_string($dbc,$attendancerecordid);
$employeeid=mysqli_real_escape_string($dbc,($_POST['employeeid'][$row]));
$linemanagerid=mysqli_real_escape_string($dbc,($_POST['linemanagerid'][$row]));
$abscencecode=mysqli_real_escape_string($dbc,($_POST['abscencecode'][$row]));
$date=mysqli_real_escape_string($dbc,($_POST['date'][$row]));
$row_data[] = "('$attendancerecordid', '$employeeid', '$linemanagerid', '$abscencecode', '$date')";
}
if (!empty($row_data)) {
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES '.implode(',', $row_data)
ON DUPLICATE KEY UPDATE abscencecode = $row_data[abscencecode];
echo $sql;
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
}
The various echo statements are showing that the correct data is coming through and my select statement was as expected before I added in the ON DUPLICATE statement.
You need to fix the way the sql statement is constructed via string concatenation. When you create an sql statement, echo it and run it in your favourite mysql manager app for testing.
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES ('.implode(',', $row_data).') ON DUPLICATE KEY UPDATE abscencecode = 1'; //1 is a fixed value yiu choose
UPDATE: Just noticed that your $row_data array does not have named keys, it just contains the entire new rows values as string. Since you do bulk insert (multiple rows inserted in 1 statement), you have to provide a single absencecode in the on duplicate key clause, or you have to execute each row in a separate insert to get the absence code for each row in a loop.

PHP Array Explode Twice

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. "')";
}

Using arrays and loops with SELECT AS syntax in SQL

I am generating a table in HTML from a MySQL database, so that stored data can be displayed on a web page, and ultimately downloaded as a spread sheet.
I have a large set of SQL headers (probably the wrong name for this), that is to say the 'Title' of any given column.
I am using SELECT to get the data from MySQL via PDO:
$sql ="
SELECT
`sv_20` AS `Name`,
`sv_21` AS `Age`,
`sv_22` AS `Height`,
`sv_23` AS `Weight`,
...
...
`sv_999` AS `Something`
FROM
database.table";
In PHP I would define two arrays (the database headers and the titles I'd like them to have) and then write a foreach loop saying:
foreach(array_combine($headers, $titles) as $header => $title)
{
echo "`$header` AS `$title`,";
}
Which would give me the complete set of calls, is there a way to do this in SQL when querying a database? Thank you
It's basic string manipulation, instead of echo, you want to append this to the string with $sql .=
You'll have some problems with the extra comma after the last item, it's better to
$sql = array();
foreach(....)
$sql[] = "`$header` AS `$title`";
and then do a join(',', $sql);

PHP INSERT INTO - Can I use an array to populate field names?

What I am wondering is how you can use INSERT INTO if you don't know how many fields there will be in advance. My project involves adding columns if required. Therefore my code will look like this:
$query = "INSERT INTO table (could be any amount) VALUES (could be any amount)";
Is it possible to populate the 'could be any amount' parts from arrays? These could be as follows:
$array1 = (fieldname, fieldname, fieldname);
$array2 = (value, value, value);
Thanks in advance for any help you can give.
$array2 = array_map('mysql_real_escape_string', $array2);
$query = "INSERT INTO table (`".implode("`,`", $array1)."`)"
." VALUES ('".implode("','", $array2)."')";
But You should not use such bad practices.

Categories