0

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.

Community
  • 1
  • 1
user1459766
  • 118
  • 2
  • 3
  • 16
  • Are you asking if there is a PDO equivalent to INSERT and SELECT? – Paul Dessert Aug 28 '12 at 00:25
  • You can send the same SQL commands to MySQL through PDO as you used to using `mysql_query()`, including [`INSERT ... SELECT`](http://dev.mysql.com/doc/en/insert-select.html). – eggyal Aug 28 '12 at 00:27
  • My question was referencing the use of http://dev.mysql.com/doc/refman/5.0/en/insert-select.html via PDO. This is quite a bit different than the post Jocelyn referenced. Please see response to Paul's answer below. Thank you all. – user1459766 Aug 28 '12 at 17:11

2 Answers2

1

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();
Paul Dessert
  • 6,363
  • 8
  • 47
  • 74
  • While this didn't directly answer the question I was asking your prompt response and confirmation that the queries don't change was helpful. I should have done a better job asking the question but the way I've historically inserted data is via http://dev.mysql.com/doc/refman/5.0/en/insert-select.html which does not use the VALUES piece but instead uses SELECT. This allows for an insert only into the fields identified even if other fields are included in a table. The key to getting this to work was only using bindParam for the fields being included in my prepared statement, no more no less. – user1459766 Aug 28 '12 at 17:09
1

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.

snuffn
  • 2,102
  • 13
  • 15