Using PHP to INSERT multiple rows into mysql DB - php

I am trying to insert data into a table, and the data is drawn from another table. At the moment my code looks like this:
$result3 = mysql_query('SELECT order_no
FROM orders
WHERE ord_date = "' . ($_POST["ord_date"]) . '"');
while($row=mysql_fetch_array($result3)){ $order=$row['order_no'];}
$result4 = mysql_query('SELECT door_product_no
FROM estimateDescribesDoorProduct
WHERE estimate_no = "' . ($_GET["estimate_no"]) . '"');
while($row=mysql_fetch_array($result4)){ $door=$row['door_product_no'];}
$result5 = mysql_query('SELECT quantity
FROM estimateDescribesDoorProduct
WHERE estimate_no = "' . ($_GET["estimate_no"]) . '"');
while($row=mysql_fetch_array($result5)){ $dquantity=$row['quantity'];}
$sql2="INSERT INTO orderConsistsOfDoor (order_no, door_product_no, product_quantity)
VALUES ('$order','$door','$dquantity')";
I used this method yesterday thanks to some advice on this site. My problem today is that I need to insert multiple rows. The tables 'orderConsistsOfDoor' and 'estimateDescribesDoorProduct' are identical except that for the first column (order_no/estimate_no). Basically if an estimate (or order) consists of e.g. 3 products, then there will be 3 rows in the table with that estimate_no (but different product_no and quantity).
I think that the code I have will only insert one row into orderConsistsOfDoor, but I need it to insert every row where the estimate_no is ($_GET["estimate_no"]). I think this can be done with foreach or something but I've never used this and don't know how it works.
Can somebody help me?

To insert multiple records with one query, you can do:
INSERT INTO `table_name` (`foo`, `bar`) VALUES (1, 2), (3, 4), (5, 6);
See INSERT Syntax
You should use a library, though, it's 2012!

Related

how to work with array updates

I am looking for some inspiration from someone wiser than me with PHP/MySQL.
In have a database application, and in this instance there are two primary tables and one child table.
Primary Table 1 - Documents
Primary Table 2 - JobDesriptions
Child Table - LnkDocuments_JobDescriptions, which as the title suggests is a one to many relational table between the Document and Job Description Table. In my Documents Table I have a field which is a lookup of JobDescriptions and presents options as a checkbox, this field is called 'AppliesTo', because of the way the application works, the field stores the results as a string, eg "1,2,3,4,5) I have used the explode function to turn this into an array and then insert each record into the child table, as I prefer 1-2-many relationships. This is the code that I have, and it works.
$jdarray = explode(',',$values['AppliesTo']);
foreach($jdarray as $item)
{
$sql2 = "INSERT INTO LnkDocuments_JobDescriptions (DocumentFk, JobDescriptionFk)
values ('".$keys["DocumentPk"]."', '$item')"; CustomQuery($sql2);
}
The problem I now have is that if that table gets updated, I need to also update the child table, i have tried this code (but quickly realised that it is wrong):
$jdarray = explode(',',$values['AppliesTo']);
foreach($jdarray as $item)
{
$sql = "SELECT * FROM LnkDocuments_JobDescriptions WHERE DocumentFk='".$keys["DocumentPk"]."' AND JobDescriptionFk='$item'"; ;
$num_rows = mysql_num_rows(CustomQuery($sql));
if ($num_rows > 0) //Delete Record
{
$sql2 = "DELETE FROM LnkDocuments_JobDescriptions WHERE DocumentFk='".$keys["DocumentPk"]."' AND JobDescriptionFk='$item'"; CustomQuery($sql2);
echo "JD FK : ".$item." deleted";
}
else //Insert Record
{
$sql3 = "INSERT INTO LnkDocuments_JobDescriptions (DocumentFk, JobDescriptionFk)
values ('".$keys["DocumentPk"]."', '$item')"; CustomQuery($sql3);
echo "JD FK : ".$item." added";
}
}
It occured to me that I need to compare differences in the arrays, but havent got a clue how to do this, but this is what I need:
If I can get $oldarray and $new array to compare, for example
if in old array there were values 1,2,3,4 and in $newarray there were values 1,2,3,5, I want the code to loop through each value to determine if there is a change, e.g. if value exists in old and new array then do nothing, if value exists in old array but not new then delete, if value exists in new array but not old then insert.
I have also thought about just deleting all associated records and adding again, but think this is bad practice and will result in high number primary key, also it is worth noting that in my example there are only 5 options, this is just for testing, in reality there could be dozens.
Thanks in advance
If you are trying to optimize things I'm not sure that reading the values already present in the table and then deleting only those are not in the new version while inserting the missing records is the best way to go. In my opinion it would be much faster to just delete everything in one query, then insert all records in one query. Try something like this:
$item_list = implode( ',' , $jdarray );
$delete_query = "DELETE FROM LnkDocuments_JobDescriptions WHERE DocumentFk='".$keys["DocumentPk"]."' AND JobDescriptionFk IN ( $item_list )";
CustomQuery($delete_query);
$document_key = "'" . $keys["DocumentPk"] . "'";
$item_list_to_insert = "($document_key, " . implode( "), ($document_key, ", $jdarray ) . ")";
$insert_query = "INSERT INTO LnkDocuments_JobDescriptions (DocumentFk, JobDescriptionFk) VALUES " . $item_list_to_insert;
CustomQuery($insert_query);
Note: I didn't test this, there might some debugging needed.

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?

Trigger to delete table and then insert value with Mysql

How could i do a query with php and mysqli, to remove an entire table and then add new I have a form where data is received, but before adding the new data, I want to remove all data from table.
$oConni is my connection string
$cSQLt = "TRUNCATE TABLE approved";
$cSQLi = "INSERT INTO approved (ID_STUDENT, YEAR, APPROVED)
VALUES (
'" . $_POST['NSTUDENT'] . "',
'" . $_POST['YEAR'] . "',
'YES'
)";
$oConni->query($cSQLt);
$oConni->query($cSQLi);
You can remove everything from a table with MySQL by issuing a TRUNCATE statement:
TRUNCATE TABLE approved;
.. which usually is the same as
DELETE FROM approved;
.. but there are a few small differences, which you can read about in the documentation.
In the code you've pasted, please use prepared statements to avoid a sql injection attack. Never use unfiltered POST-data directly in a query!
If you want to do this as a trigger, we'll need to know a bit more about your data handling. Issuing a TRUNCATE before a INSERT will usually lead to only one row being available in the table, which seems like a weird use case for actually using a table.
You could use TRUNCATE TABLE and then your next query:
$cSQLt = "TRUNCATE TABLE CALIFICA_APTO";
$cSQLi = "INSERT INTO approved (ID_STUDENT, YEAR, APPROVED)
VALUES (
'" . $_POST['NSTUDENT'] . "',
'" . $_POST['YEAR'] . "',
'YES'
)";
$Connect->query($cSQLt);
$Connect->query($cSQLi);
If your looking to remove all of the data from a table you should use TRUNCATE:
TRUNCATE TABLE approved
Then you can do your SQL statement.
NOTE: This will delete all data from the table, so be careful! Also, your database user must have the ability to truncate tables.

mysql UPDATE multiple rows but single column different value fetch from array

ok so i have a php array it looks like
array('somehash' => 'someotherhash', 'somehash2' => 'someotherhash2');
here somehash = producthash and someotherhash = tohash
$db->query('UPDATE sometable SET status = '.self::STATUS_NOT_AVAILABLE.', towhere = '.self::TO_WHERE.', '.
.'tohash = WHEN or IF or ??? and how ?, '.
.'WHERE status = '.self::STATUS_AVAILABLE.' AND '.
.'producthash IN (' . implode(',' , $prodarray) . ')') or $db->err(__FILE__,__LINE__);
so in the above query i want tohash value to be fetched from the php array via producthash mysql field
something like tohash = IF(producthash IN '.$prodarray.', $prodarray['producthash'] , whatever)
ofcourse the above IF wont work cause i dont have the producthash value in $prodarray['producthash']
anyone knows a way around this because i have more than 1000 values in the array and dont want to run thousand updates
the INSERT INTO ON DUPLICATE KEY is not possible in this cause because this table unique key is based on 3 fields and i dont have all the three field values while doing this update.
A subquery?
UPDATE ...
WHERE ... producthash in (SELECT * FROM products)
This will work as long as you're not selecting from the same table you're updating - mysql doesn't allow that without workarounds.

php mysql save mysql with for loop

TABLE:
09:00 -- id_timeslot = 1
09.15 -- id_timeslot = 2
09.30 -- id_timeslot = 3
09.45 -- id_timeslot = 4
10.00 -- id_timeslot = 5
PHP MYSQL:
for($i=0; $i<=2; $i++) {
$mysqli->query("INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES ('" . ++$id_timeslot . "', '" . $id_member . "', '" . $b_ref . "', '" . $id_doctor . "', 1)" )
}
I want the data to be saved twice and increment the id_timeslot.
The above code working fine, but when save cliked. it didnt pick up the right id_timeslot?
for example: if user click on id_timeslot:1, soon it save to database the id_timeslot starts from 2 instead of id_timeslot 1?
if user click on id_timeslot:1, soon it save to database the id_timeslot starts from 2 instead of id_timeslot 1?
This is because you're using a pre-increment rather than a post-increment. If $id_timeslot is 1 before entering the loop, the value of ++$id_timeslot is 2, so the first generated query is:
"INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES ('2', '$id_member', '$b_ref', '$id_doctor', 1)"
If the id_timeslot column is supposed to be an ID for the bookslot record, the best approach is to declare it with the AUTO_INCREMENT attribute and don't insert values for that column:
-- run just once in some MySQL client
ALTER TABLE bookslot MODIFY id_timeslot INT UNSIGNED PRIMARY KEY AUTO_INCREMENT;
// in PHP
$stmt = "INSERT INTO bookslot(id_member, b_ref, id_doctor, status)
VALUES ('$id_member', '$b_ref', '$id_doctor', 1)";
When using double quoted strings, you don't need to concatenate variables. Compare the above statement with your own.
If id_timeslot isn't a unique ID, then you can simply switch to post-increment.
$stmt = "INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES (" . $id_timeslot++ . ", '$id_member', '$b_ref', '$id_doctor', 1)";
This may or may not be a correct approach for various other reasons. Without knowing more about the schema, it's impossible to say.
Off Topic
Depending on where the values for $id_member, $b_ref $id_doctor originate, your script could be open to SQL injection. Rather than inserting values directly into the string, use a prepared statement. MySQLi supports them, as does PDO, which is simpler to use. New code should use PDO, and old code should get updated over time.
You have to fetch last id_timeslot from database and then increase it PHP during inserting.

Categories