This question already has an answer here:
I am having difficult understanding the $conn
within the tutorial I just did. It is from Tutsplus PHP Fundamentals course.
I have arrived at the following code:
<?php
require 'config.php';
$letter = 'J%';
try {
$conn = new PDO('mysql:host=localhost; dbname=practice', $config['DB_USERNAME'], $config['DB_PASSWORD']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Switch to turn on error modes with errors displayed
$stmt = $conn->prepare('SELECT * FROM users WHERE username LIKE :placeholder');
$stmt->bindParam('placeholder', $letter, PDO::PARAM_INT);
$stmt->setFetchMode(PDO::FETCH_OBJ);
$stmt->execute();
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
I understand the :placeholder
part. The part that I'm not quite grasping is particularly the $conn
in this line:
$stmt = $conn->prepare('SELECT * FROM users WHERE username LIKE :placeholder');
If I'm understanding the ->
now it means we're passing the variable $conn
into the function prepare()
and storing the result in $stmt
. What I don't get is what $conn
is currently holding from the PDO connection. I tried doing print $conn;
but got returned an error.
</div>
$conn contains PDO class's object.
PDO (php database object) is a standart library to provide access to different database drivers using object-oriented interface.
"$conn" object is an instance of PDO class.
Objects in "object-oriented programming" are essentially data structures together with their associated processing routines.
You should learn at least OOP basics to fully understand how it works.
http://en.wikipedia.org/wiki/Object-oriented_programming
If I'm understanding the -> now it means we're passing the variable $conn into the function prepare()
No. "->" operator you calling a function "prepare" of the object "$conn"