Dynamic amount of insert in loop [duplicate] - php

This question already has answers here:
What is the best way to insert multiple rows in PHP PDO MYSQL?
(4 answers)
Insert multiple rows with PDO prepared statements
(4 answers)
PDO MySQL: Insert multiple rows in one query
(1 answer)
Multiple inserts with PDO [duplicate]
(1 answer)
PDO multi insert statement
(1 answer)
Closed 5 years ago.
Sorry if this seems like a simple question but I've searched high and low on Google and Stackoverflow and while there are answers to similar questions, but nothing exactly like what my current situation is. In addition, I just recently returned to programming and first time in ever started using PDO and prepared statements so I've not mastered the art yet.
I have the following code, generating the SQL: (I will have the same code to generate the UPDATE versions to later update these insertions)
if(isset($vars['benefits']))
{
foreach($vars['benefits'] as $benefit)
{
$sql['benefits'][] = "INSERT INTO " . BENEFITS_TABLE . " (benefit) VALUES ('{$benefit['benefit']}')";
}
}
if(isset($vars['sliteratures']))
{
foreach($selectedIDs as $litID)
{
$sql['literature'][] = "INSERT INTO " . PRODLIT_TABLE . " (productID, literatureID) VALUES ('{$productID}', '{$litID}')";
}
}
Which obviously creates the dynamic amount of the query... and now I'm trying to convert it so I could prepare/bind the values (The columns is a hard-coded array while the values are retrieved VIA POST from an HTML form).
I don't know what is the best way to come by doing this. Or how to do it properly might be a better way to phrase that.
I could do that in a loop for each query separately. Like so:
if(isset($vars['benefits']))
{
foreach($vars['benefits'] as $benefit)
{
$sql = "INSERT INTO " . BENEFITS_TABLE . " (benefit) VALUES (:benefit)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":benefit", $benefit['benefit'], PDO::PARAM_STR);
$stmt->execute();
}
}
And the other query likewise, but that puts the SQL operations in a loop. Is that a bad approach?
There would never be a drastic amount of INSERTS. The most would be like 10 for benefits and 3 or 4 for literature so I imagine doing it all in a loop wouldn't effect me much in terms of performance, but for future reference, what would be the best way to come by this effectively?
Thanks for any constructive input.

Related

How to performs multiple query on the database Oracle using PHP Language [duplicate]

This question already has answers here:
Best way to do multi-row insert in Oracle?
(9 answers)
Closed 3 years ago.
In order to run a query for database MySQL, we are using mysqli_query. Then, for running a query for database Oracle, we are using oci_execute.
When we wish to running multiple query for database MySQL, we are using mysqli_multi_query. Example as below:-
$mysqliconn = mysqliconn(); //mysqli connection
$sql = '
INSERT INTO TABLE VALUES();
INSERT INTO TABLE VALUES();
INSERT INTO TABLE VALUES();
INSERT INTO TABLE VALUES();
';
if(mysqli_multi_query($mysqliconn, $sql)) {
echo 'Success';
}
My Question is if there anyone of you whom can come out with the most simplest solution to run multiple inserting values into the database table using one command execution.
Oracle has an INSERT ALL statement for that.
Otherwise you could just loop in your code and execute it n times.
$sql = '
INSERT INTO TABLE abc VALUES(123,'xyz'),(456,'def'),(789,'qwe');
';
I suggest that using support library ^^

SQL Query as a string - safe from injection? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 4 years ago.
most of the time I've been doing SQL like this:
$pdo = new PDO($dsn, $usr, $pass);
$qry = 'SELECT * FROM `my_table` WHERE `pk_id` = '. $id .';';
$res = $pdo->query($qry);
but recently I've seen a few posts showing that the only way to be safe is using prepared statements - this isn't an issue really for me, and this probably has an answer, just one I couldn't find from Googling around.
surely, if all of my statements, end in .';' using concat is ok?
Thanks,
No.
In SQL, it does not give an error if you supply two semi colons at the end of your query.
So if a user could pass along this:
1; DROP TABLE users;
it will have the same consequences, with or without the semi colon in your code added at the end.
The huge benefit of prepared statements is that no data is being altered. It just simply sends two queries.
Here is a a nice source which contains a lot of SQL injection examples.

How can i execute multiple queries using prepared statments? [duplicate]

This question already has answers here:
mysqli: can it prepare multiple queries in one statement?
(2 answers)
Closed 8 years ago.
I am trying to execute 2 queries at the same time. I know I can do this using mysqli::multi_query.
But is there any way I can perform a multiple queries using prepared statements?
Below is an example of my query Thanks!
$delete_all_options = "DELETE FROM option_categories WHERE item_id = ?; ";
$delete_all_options .= "DELETE FROM option_names WHERE option_category_id = ?";
$delete_stmt = $db->prepare($delete_all_options);
//Execute statement ......
You may want to use transactions. Here's an explanation for using transactions with PDO: http://php.net/manual/en/pdo.transactions.php . Transactions can be used also with the MySQLi extension, by setting MySQLi::autocommit(false) and then committing with MySQLi::commit() (with PHP 5.5+ you can also use MySQLi::begin_transaction() and other methods).
Transactions execute multiple queries "at once" and if one query fails all the transaction is reverted.

Query works in phpmyadmin but not in PHP [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
Ok so i have this kind of query
SELECT * FROM table WHERE column LIKE 'Blahblahblah Blah - Blah (Blah-Blah)'
(Yep, column values are 20-30 characters long)
And it works in phpmyadmin and returns ~ 100 results.
But whn i try it in PHP framework CI (CodeIgniter)
It is not returning any values.
My code looks like:
$sql = "SELECT * FROM table WHERE column LIKE '$val' ORDER BY column ASC";
$sql = $this->db->query($sql);
return $sql->result();
So how do i get this to work?
Before you try to make it work, you really, really need to change the way you're constructing the query. You should use a prepared statement where you introduce variables, and then bind them to values.
The way you've written it is horribly vulnerable to SQL injection attacks. (Suppose $val contained '; DROP DATABASE blah; .... What would the whole SQL statement now look like?) If you try to solve the problem in its current form, you'll end up with something that works but will be very dangerous. Make it safe first with a prepared statement.
Details in this linked question.

PHP PDO Equivalent of INSERT INTO ... SELECT [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MySQL INSERT from a SELECT with PDO
I've historically used the mysql_* style of connecting to mysql via php and am finally making the trek over to PDO. In the past I've like to use mysql's INSERT INTO... SELECT... to insert data. The benefit being that I could add columns to a table at a later time without completely hosing all other forms that interact with that table. My question is quite simply. . . is there a PDO equivalent to this?
I'm not having much luck using the old syntax in a prepared statement nor do I see any examples using this format. Any thoughts or suggestions would be much appreciated.
The queries don't change. You can use things like:
$postUser = $_POST["user_name"];
$stmt = $dbh->prepare("SELECT * FROM user WHERE userName = :postUser");
$stmt->bindParam(':postUser', $postUser);
$stmt->execute();
To INSERT:
$sql = "INSERT INTO table (whatever) VALUES (:whatever)";
$q = $conn->prepare($sql);
$q->execute(array(':whatever'=>'whatever'));
And to SELECT:
$sql = "SELECT whatever FROM table WHERE whatever = :whatever";
$q = $conn->prepare($sql);
$q->execute(array(':whatever'=>'whatever'));
$row = $q->fetch();
For more information on prepared statements go here.

Categories