Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 94
  • Last Modified:

Transitioning to PDO/MySQL. Need help with SELECT statement.

How do I transition this select statement to PDO with PHP?

$result1 = mysql_query("SELECT * FROM `product_description`");
while($row1 = mysql_fetch_assoc($result1))
{


mysql_query("INSERT INTO `product_description` (`product_id`, `name`, `description`, short_description) VALUES ('".mysql_real_escape_string($row1['product_id'])."','".mysql_real_escape_string($row1['name'])."','".mysql_real_escape_string($row1['description'])."','".mysql_real_escape_string($row1['short_desc'])."')");


}

Open in new window

0
lawrence_dev
Asked:
lawrence_dev
1 Solution
 
GaryCommented:
<?php
$database_name = "";
$username = "";
$password = "";

$conn = new PDO('mysql:host=localhost;dbname='.$database_name, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Get rows
$result = $conn->query("SELECT * FROM `product_description`");

// Prepare the update sql
$do_update = $conn->prepare("INSERT INTO `product_description` (`product_id`, `name`, `description`, `short_description`)
VALUES (:product_id, :name, :description, :short_desc)");

while ($row = $result->fetch(PDO::FETCH_ASSOC)){
{

	// Execute the update for each row
	$do_update->execute(array(
		':product_id'	=>	$row['product_id'],
		':name'		=>	$row['name'],
		':description'	=>	$row['description'],
		':short_desc'	=>	$row['short_desc']
	));
}

Open in new window

0
 
Ray PaseurCommented:
Here's an article covering most of the aspects of the conversion.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

In the case of the SELECT statement, there are no changes needed at all.  Things only change when you use external variables as part of the query.  The article explains why and shows a few ways of making the transition from direct variable injection (into the query string) and indirect injection via parameterized queries or placeholders.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now