So I have a PDO and MySQL script that is used to retrieve a result based on the user's username, or screen name, in this case being e
.
First, I have a function at the beginning of the file that is used to connect to the database. (it is present in a functions.php
file and required
at the beginning of each page, thus the globalization). This function doesn't have anything wrong with it (as far as I know).
function SQLConnect () {
// Database connection variables
$host = "localhost";
$dbname = "dropbox";
$user = "root";
$password = "ethan17458";
// Connect to the database
try {
//put $connect in global scale of document
global $connect;
// attempt to connect to database
$connect = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
// Sets error mode
$connect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e) {
// Retrieves error message if connection fails
echo $e->getMessage();
}
}
This function uses PDO to connect to the database containing the user's information.
Next is the script to retrieve the user's data
// Test user in database
$test = "e";
try {
//confirms running of "try" block
echo "tried";
//database information
$host = "localhost";
$dbname = "dropbox";
$user = "root";
$password = "ethan17458";
//Prepare statement from connection function
// username_raw is "e"
//username should be e1671797c52e15f763380b45e841ec32 (md5)
$statement = $connect->prepare("SELECT `username` FROM `users` WHERE `username_raw` = ':name'");
//create placeholder for prepared statement
$statement->bindParam(":name", $test);
//make the statement fetch in an associative array
$statement->setFetchMode(PDO::FETCH_ASSOC);
//execute the prepared statement
$statement->execute();
//set $get_result to the fetched statement
$get_result = $statement->fetch();
//attempt to display the data fetched in $get_result
echo "<br />";
echo "<pre>";
//Outputs 1 for some reason
// **not working**
echo print_r($get_result);
echo "</pre>";
echo "<br />";
} catch (PDOException $e) {
//confirm running of "catch" block
echo "caught";
// echo error message
echo $e->getMessage();
}
When I run this script I get this output:
tried
1
In this output, tried
is the confirmation that the "try" statement was processed, and the 1
is where I start to run into problems.
If the script was working as I would like, the script would retrieve the data e1671797c52e15f763380b45e841ec32
from the database because it is the column username
where the username_raw
is e
, as is stated in the PDO prepared statement.
The ideal output should be
tried
e1671797c52e15f763380b45e841ec32
What am I doing wrong?
fetch() is returning false, which prints nothing to the screen. This is false because you're getting no results because you're putting single quotes around your parameter in the query, which PDO takes care of for you. Just remove the quotes around :name.