How to Insert multiple rows of data into a table - php

I am currently new to programming over all and I have all sorts of questions when it comes to PHP, but my first question is how to add multiple data to a table only using one variable. For example:
<?php
$mysqli = mysqli_connect('localhost', 'root', 'testpass', 'testdatabase')
or die (mysqli_error());
$test = "INSERT INTO test (test1, test2) VALUES ('test1', 'test2')";
$test .= "INSERT INTO test (test1, test2) VALUES ('test3', 'test4')";
if (!$test){
echo "Sorry but you information could not be added...";
}
else {
$test_result = mysqli_query($mysqli, $test);
echo "Your data has been entered!";
}
When I use this code when trying to add multiple data into my table it doesn't work. I can only add in 1 row at a time. I can never add in 2, 3, or more rows in at a time. Is there an error in my code? When I look at other example, people user mysql and not mysqli. The people using mysql use that same code as I have above. I prefer using mysqli and not having to switch because of something that is so small. Back to my question, how do I add multiple rows of data into a table? Thanks!

To insert multiple rows use this:
INSERT INTO test (test1, test2) VALUES ('test1', 'test2'), ('test3', 'test4'), ('test5', 'test6')
which would insert 3 rows.

Related

INSERT INTO SELECT with VALUES in one query

Bit new to MYSQL and PHP - I have the following code that will create a new record in multiple tables that I have setup however I need to merge the following code together somehow as it creates separate rows instead of one record
$sql .=("INSERT INTO orders (customer_id) SELECT customer_id FROM
customer_details;");
foreach($result as $item){
$mysql_desc = $item['product_description'];
$mysql_mode = $item['delivery_mode'];
$mysql_cost = $item['course_cost'];
$sql .=("INSERT INTO orders(product_description, delivery_mode, course_cost) VALUES('$mysql_desc', '$mysql_mode', '$mysql_cost');");
}
The result I'm getting:
Based on your data I assume that you want to insert the customer id and the values from php into the same record. In this case you need to combine them into the same insert ... select ... statement:
$sql .=("INSERT INTO orders(customer_id, product_description, delivery_mode, course_cost) select customer_id, '$mysql_desc', '$mysql_mode', '$mysql_cost' from customer_details;");
Couple of things to note:
This insert ... select ... statement will insert the same records for all customers in the customer details table. I'm not sure if this is your ultimate goal.
Pls consider the advices made in the comments regarding the old mysql API and the use of prepared statements.
To put this more into what I would expect to happen, something along the lines of - prepare statement, then loop through each item and add in new row...
$insert = $connection->prepare("INSERT INTO orders (customer_id,product_description, delivery_mode, course_cost)
VALUES (?,?,?,?)");
foreach($result as $item){
$customerID = 1; // Have to ensure this is what your after
$mysql_desc = $item['product_description'];
$mysql_mode = $item['delivery_mode'];
$mysql_cost = $item['course_cost'];
$insert->execute([customerID,mysql_desc,mysql_mode,mysql_cost]);
}

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.

Multiple insert with PHP to MySQL not working for me but working for other people

I can see that this question gets asked a lot and I've tried following some answers that people said that worked for them but still it is not working for me.
I want to insert into my DB a variable number of elements. Here is my code:
$actual_id = $db->insert_id;
$sql = array();
foreach( $relacionado as $row ) {
$sql[] = '('.$actual_id.', '.$row.')';
}
$query2 = 'INSERT INTO relaciones (id, relacionadocon) VALUES '.implode(', ', $sql);
echo $query2;
$result2 = $db->query($query2);
if($result2){
echo "<p>".$db->affected_rows."fields inserted</p>";
}else{
echo "<p>Error</p>";
}
The thing is it works when I give it only one element but returns an error when there are more elements. I tried adding ", " instead of "," between the elements but nothing happens...
May it be because of the configuration of MySQL? Because I can't think on anything else as it seems to work for other people...
THanks!
EDIT: This is the result for echo $query2: INSERT INTO relaciones (id, relacionadocon) VALUES (65, 12), (65, 26)
EDIT2: I created the table using phpmyadmin. There are 2 tables. The first one registers information and uses an autoincreasing ID. So, the colums are ID, Title and Comment. But every comment is related to 1 or more comments. That is why there is another table that has 2 colums: ID and RelatedTo. When, for example, comment number 5 is created, you can relate it with comments 1, 2 and 3. That is why the INSERT should pass: (5,1), (5,2), (5,3). Once again, if I only had (5,1), it would work. I didn't give a primary key to the ID of the second table, only to the first.
I'm thinking the ID field is the primary key and shouldn't be written to. Can you try and run INSERT INTO relaciones (id, relacionadocon) VALUES (65, 12), (65, 26) within phpmyadmin to see what the result is?

Possible to make this code valid/speed up?

I have an enrollment form which takes consumer information, stores it in session, passes from page to page then stores in a database when finished. Originally the table simply listed fields for up to 16 persons but after reading into relational databases, found this was foolish.
I have since created a table named "members" and "managers". Each enrollment will take the information input, store the manager ID in the respective table and place a reference field in each member row containing the manager ID.
While I allow up to 16 members to be enrolled at once, this can range from 1-16.
My best guess is to use a FOR-loop to run though multiple INSERT statements in the event more than 1 member is enrolled.
In the example below, I am using the variable $num to represent the individual member's information and $total to represent the number of all members being enrolled. The code here does not function but am looking for:
a) ways to correct
b) understand if there are more 'efficient' ways of doing this type of INSERT
sample code:
<?php
$conn = mysql_connect("localhost", "username", "pw");
mysql_select_db("db",$conn);
for ($num=1; $num<=$total; $num++) {
$sql = "INSERT INTO table VALUES ('', '$clean_f'.$num.'fname', '$clean_f.$num.mi', '$clean_f.$num.lname', '$clean_f.$num.fednum', '$clean_f.$num.dob', '$clean_f.$num.ssn', '$clean_f.$num.address', '$clean_f.$num.city', '$clean_f.$num.state', '$clean_f.$num.zip', '$clean_f.$num.phone', '$clean_f.$num.email')";
$result = mysql_query($sql, $conn) or die(mysql_error());
}
mysql_close($conn);
header("Location: completed.php");
?>
If all of your statements are structurally the same, but with different parameter values, consider using the PDO extension, which supports prepared statements. The benefits of prepared statements can be read here (http://www.php.net/manual/en/pdo.prepared-statements.php), but in general, the same statement will only need to be compiled once, but can be executed as many times as you want with different parameters, which can make your script more "efficient".
Using PDO, your code could look something like:
$db = new PDO('mysql:host=localhost;dbname=db', 'username', 'pw');
$statement = $db->prepare('INSERT INTO tablename (field1, field2, field3, ...) VALUES (?,?,?,?');
for ($num=1; $num<=$total; $num++) {
$statement->execute(array('val1', 'val2', 'val3', '...'));
}
Generally, putting a query in a loop is bad thing. There is usually a better way. In this case, you should use the multi-insert syntax. Your INSERT isn't working because you didn't specify the fields. I'm assuming the lack of a space between the table name and VALUES is a typo, along with the bad quoting.
INSERT INTO table_name (field1, fname, lname, fednum, ...)
VALUES ('val1', 'Pete', 'Moss', 1234),
('val2', 'T.', 'Cupp', 54321),
('val3', 'Youdid', 'Watt', 787123);
The solution, if I read you right, is to start with the fixed query string:
$queryString = "INSERT INTO table (field1, field2, ...) VALUES ";
then run a loop to build the malleable part. Putting your values into arrays makes things easier:
$queryInsert = '';
$total = count($value1Array);
while ($i < $total) {
$queryInsert .= "('$value1Array[$i]','$value2Array[$i]','$value3Array[$i],...), ";
++$i;
}
then append to the first query piece:
$queryString = $queryString.$queryInsert;
and trim off the trailing , and you're good to go.

Multiple mysql INSERT statements in one query php [duplicate]

This question already has answers here:
Insert multiple rows with one query MySQL
(5 answers)
Closed 2 years ago.
Is this legal?
$string1= "INSERT INTO....;";
$string1 .= "INSERT INTO....;";
$string1 .= "INSERT INTO....;";
mysql_query($string1) or die(mysql_error());
For what it's worth, and depending on if you're inserting the same data into
the same tables, it's much better to insert multiple values with the one insert
e.g.
INSERT INTO a VALUES (1,23),(2,34),(4,33);
INSERT INTO a VALUES (8,26),(6,29);
No, mysql_query() only allows one query at a time.
You can insert multiple rows like this:
INSERT INTO table (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)
From MySQL dev support MySQL dev forum
INSERT INTO table (artist, album, track, length)
VALUES
("$artist", "$album", "$track1", "$length1"),
("$artist", "$album", "$track2", "$length2"),
("$artist", "$album", "$track3", "$length3"),
("$artist", "$album", "$track4", "$length4"),
("$artist", "$album", "$track5", "$length5");
So insert goes as normal as always:
naming first the table name where we want to insert new row,
followed by naming column names in round brackets (Note: Not needed if you want to insert ALL columns),
followed by VALUES key name and then in round brackets comes the values that you want to insert for new ROW in the above table,
followed by COMMA and then another pair of round brackets with new values for new row in the mentioned table above
and this repeats N-times as long you have the data to insert.
Happy inserting multiple values with ONE insert statement. :)
Copy/paste example within a function and a loop (suppose $ids is an array)
public function duplicateItem($ids)
{
if (isset($ids[0])){ //at least one item
$sqlQuery = "INSERT INTO items (item_id, content) VALUES ";
for($i=0; $i<count($ids); $i++) {
if ($i == count($ids)-1){
$sqlQuery .= "(".$ids[$i][0].", '".$ids[$i][1]."');";
}else{
$sqlQuery .= "(".$ids[$i][0].", '".$ids[$i][1]."'),";
}
}
mysql_query($sqlQuery) or die('Error, insert query failed: '.mysql_error());
}
}
In general, that's valid SQL since each statement ends with a semicolon, but PHP doesn't allow you to send more than one query at a time, in order to protect against SQL injection attacks that might exploit a poorly written script.
You can still use a syntax like:
INSERT INTO foo VALUES ('a1', 'b1'), ('a2', 'b2');
INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);
No. They are separate queries, and must be called as such.
// if $data is an array
$sqlQuery ="INSERT INTO tableName(col1, col2) VALUES ";
for($i=0; $i<count($data); $i++) {
$sqlQuery .="(".$data[$i][0].", '".$data[$i][1]."'),";
}
$sqlQuery = rtrim($sqlQuery, ','); // Remove last comma
mysql_query($sqlQuery) or die('Error, insert query failed: '.mysql_error());

Categories