If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

[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();

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.

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):

$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}

"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation