/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] How can I pass an object into PDO?

I’m new to php and am trying to learn oop. I have a simple input that passes the text to a class to sanitize it. I want to be able to insert the text into the database using pdo. I’m not sure if I’m going the correct way with this.

[code]
$sanitize = new SanitizeText($category);
//I want the sanitize text in the database.
$newdb = new Database();
[/code]

[code]
class Database {
private $db_user = ‘root’;
private $db_password = ‘password’;
private $db_name = ‘test’;
private $db_host = ‘localhost’;

public $prepare_sql;
public $execute_sql;

// Connect to database
public function __construct() {
try {
new PDO(‘mysql:host=’ .$this->db_host. ‘; dbname=’ .$this->db_name, $this->db_user, $this->db_password);
echo “Connected to database”;
}
catch (PDOException $e) {
echo “Could not connect to database”;
}
}

// Insert data.. not sure if this is proper
public function create() {

$stmt = $this->prepare($prepare_sql);
$stmt->execute($execute_sql);

}
}
[/code]

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJan 11.2014 — Well, my first thought is that if you are going to use prepared statements and bound parameters with PDO (which is a very good thing), then you should have no issues with sanitizing values for SQL use. Therefore, the only thing you would need your SanitizeText class is for issues not related to SQL/database stuff. If that's the case, then I would not inject that dependency into your Database class, as you want classes to stay narrowly focused on their specific purposes.

If your SanitizeText class is designed for other things (e.g. screening out link or JavaScript injection), that would probably better fit wherever you would do things like form validation and so forth, not in your database class.

If we set all that aside and assume for now that you do have a reason for using that class within your Database class, probably the best way to make that dependency obvious is to inject it directly via the constructor. That way any client code "knows" it has to provide it.

Oh, and a database class can be a good opportunity to make use of inheritance.
[code=php]
<?php

class Database extends PDO
{
private $sanitize;
private $db_user = 'root';
private $db_password = 'password';
private $db_name = 'test';
private $db_host = 'localhost';

public function __construct(SanitizeText $sanitize)
{
$this->sanitize = $sanitize;
parent::__construct(
'mysql:host=' .$this->db_host.'; dbname='.$this->db_name,
$this->db_user,
$this->db_password
);
}

public function doSomethingWith($text)
{
$text = $this->sanitize->someMethod($text);
echo "And the sanitized text is:".PHP_EOL.$text;
}
}
[/code]

Possible instantiation:
[code=php]
$db = new Database(new SanitizeText());
[/code]
Copy linkTweet thisAlerts:
@phpNoobauthorJan 14.2014 — Thanks for replying. Maybe I explained it wrong. I'm not sure how to prepare and execute the sanitized text with PDO.

Form text input goes to add-category.php. This includes the sanitize class to sanitize the text and the database class to update the database.
<i>
</i>require 'class-database.php';
require 'class-sanitize-text.php';

// Category input text value
$category = $_POST['category'];

// Create new object to sanitize text
$sanitize = new SanitizeText($category);

$newdb = new Database();

//Not sure how to actually prepare and execute the new sanitized object so I can add it to the database


<i>
</i>//class-sanitize-text.php
/* Sanitize string text */
class SanitizeText {
public $SanitizeText;

<i> </i>public function __construct($SanitizeText) {
<i> </i> $this-&gt;SanitizeText = filter_var($SanitizeText, FILTER_SANITIZE_STRING);
<i> </i>}
}


Same as previous initial post. I'm trying to get this class to only connect, read, update, delete data from the database.
<i>
</i>//class-database.php
class Database {
private $db_user = 'root';
private $db_password = 'password';
private $db_name = 'test';
private $db_host = 'localhost';

<i> </i>public $prepare_sql;
<i> </i>public $execute_sql;

<i> </i>// Connect to database
<i> </i>public function __construct() {
<i> </i> try {
<i> </i> new PDO('mysql:host=' .$this-&gt;db_host. '; dbname=' .$this-&gt;db_name, $this-&gt;db_user, $this-&gt;db_password);
<i> </i> echo "Connected to database";
<i> </i> }
<i> </i> catch (PDOException $e) {
<i> </i> echo "Could not connect to database";
<i> </i> }
<i> </i>}

<i> </i>// Insert data.. not sure if this is proper
<i> </i>public function create() {

<i> </i> $stmt = $this-&gt;prepare($prepare_sql);
<i> </i> $stmt-&gt;execute($execute_sql);

<i> </i>}
}
Copy linkTweet thisAlerts:
@NogDogJan 15.2014 — What I suggest doing is to make use of PDO's ability to use bound parameters in prepared statement. When you do that, PDO takes care of any needed sanitizing all by itself -- you don't need any SQL-related sanitizing functions (untested):
[code=php]
<?php
class Database extends PDO
{
private $db_user = 'root';
private $db_password = 'password';
private $db_name = 'test';
private $db_host = 'localhost';

public function __construct()
{
parent::__construct(
'mysql:host=' .$this->db_host.'; dbname='.$this->db_name,
$this->db_user,
$this->db_password
);
}

/**
* Run a query that uses bound parameters
* @return PDOStatement
* @param string $sql
* @param array $data
*/
public function runQuery($sql, Array $data=null)
{
$stmt = $this->prepare($sql);
if($stmt == false) {
throw new Exception(array_merge($this->errorInfo(), array('sql' => $sql)));
}
if($stmt->execute($data) == false) {
throw new Exception(array_merge($stmt->errorInfo(), array('sql' => $sql)));
}
return $stmt;
}
}

// SAMPLE USAGE:

$db = new Database();
// note leading ":" character in parameter names in following 2 commands:
$sql = "SELECT * FROM some_table WHERE foo=:value_1 AND bar=:another_value";
$data = array(
':value_1' => $_GET['some_field'],
':another_value' => $_GET['another_field']
);
// you don't have to worry about sanitizing SQL, as PDO takes care of it for you
$stmt = $db->runQuery($sql, $data);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// do stuff with values in $row
}
[/code]
Copy linkTweet thisAlerts:
@phpNoobauthorJan 15.2014 — Thanks for the help. That helped clear it up.
×

Success!

Help @phpNoob spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...