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

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.

Related

Dynamic amount of insert in loop [duplicate]

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.

MySQL SELECT WHERE IN array [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I have a situation where I'd like to add a list of names in an array and use it in an SQL query.
How I do it:
$names = implode(',', $names);
$sql = "DELETE FROM product WHERE name NOT IN ($names)";
This works ok if I use id (but I can't do that here). Problem is - name can have a comma in it (i.e. - benchpress rack, blue) and that breaks this query. Is there a way to bypass this issue?
Try this:
$names = implode("','", $names);
$sql = "DELETE FROM product WHERE name NOT IN ('$names')";
If this is your actual code I would suggest switching to PDO, use a library, or escape your values with mysqli_real_escape_string.
Here is a link: http://php.net/manual/en/mysqli.real-escape-string.php
Here is a w3schools link for prepared statements, a decent high level view of how they work: http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Here is how your statement query will run if your using PDO:
$query= $conn->prepare("DELETE FROM product WHERE name NOT IN (:names)");
$query->bindParam(':names', $names);
$query->execute();
And for mysqli it will be similar, refer to the w3schools link above for the differences.
I highly recommend you move away from the old mysql driver and at the very least switch to mysqli.

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.

How to Perform SQL Injection making a SELECT statement UPDATE or INSERT rows? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MySQL Injection - Use SELECT query to UPDATE/DELETE
So I have found in my site bug that allows to perform sql injection
http://mysite.com/script.php?id=1 union select 1,2,3 will output all fields that has Id property equal to one plus one additional row with 1,2,3. I know that I have to validate user input to close my bug.
However my question is quite another. Is it possible to perform update query or insert query? I am able to comment query using --, however I cannot use multiple statements that are delimited by ;. So is it possible to perform update query in my case. I can show PHP code and SQL query if needed.
$sql = "SELECT id, title, text from table where cId=$val";
$result = mysql_query($sql);
$array = mysql_fetch_array($result);
//echo rows in table
Judging from MySQL Injection - Use SELECT query to UPDATE/DELETE
all that is protecting you is a limitation of mysql_query. I would not rely on this, and in particular not that it remains this way over time. You should never rely on a feature to be disabled by default. Maybe the next version already allows statements such as.
SELECT id, title, text from table where cId=1; DROP table table
Nope it is not possible. Most probably you ar running mysql_query, that would not allow multiple queries to be run in one pass. And hence if your query starts with SELECT (as it does), it would not allow any UPDATE injection
Edit: Use mysql_real_escape_string on your input even then
By default this should not be possible. Although there are options for mysql_query to run multiple statements in one string since MySQL 5.0 which you have to set with mysql_set_server_option.
Please consider changing your statement command like this to use mysql_real_escape_string:
$q = mysql_fetch_array(mysql_query("SELECT id, title, text from table where cId = " . mysql_real_escape_string($val)));
At the very best you change your code to use PDO since all mysql_* functions are officially deprecated.

Is there a way to see a prepared query as it will be executed on the database? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PDO Prepared Statements
I'm using the mysqli extension in PHP and I'm wondering, is there possibly any way to see a prepared query as it will be executed on the server, e.g. The query is something like this
select * from table1 where id = ? and name = ?
but I want to see the query after the values are filled in, like this:
select * from table1 where id = 20 and name = "John"
Turn on mysql query logging and it will log all queries to a text file for you to review.
Duplicate of PDO Prepared Statements
Short answer: no. A prepared query will never be converted to the query you expect. It's executed directly by the database server. You can use mysql's query log or PDO's undocumented function debugDumpParams, but both are just approximations.
See it where?
If it's your code you have the query and you have the prepared parameters, log them separately or replace in the original query string.
If the binding will fail you will get an error, otherwise you should expect the same values to be "filled" in as you specified them.
Its the way most of the times I am debugging mysql quires:
$q = "select * from table1 where id = ".$id." and name = ".$name;
echo $q;
The output generates all variables assigned to the query.
Hope I understood you exactly, what you wanted.

Categories