I am trying to create a few php pages for my website. Basically, I want to query a table for a database thats connected with my website and be able to store/retrieve information from this table.
I have purchased a hosting service and to the best of my knowledge have correctly set up a database on phpMyAdmin. I have also set up a username and password for access (so DATABASE NAME, SERVER, USERNAME, PASSWORD).
However, I am using the following function to query from my table.
function query(/* $sql [, ... ] */)
{
// SQL statement
$sql = func_get_arg(0);
// parameters, if any
$parameters = array_slice(func_get_args(), 1);
// try to connect to database
static $handle;
if (!isset($handle))
{
try
{
// connect to database
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
// ensure that PDO::prepare returns false when passed invalid SQL
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
// trigger (big, orange) error
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
}
// prepare SQL statement
$statement = $handle->prepare($sql);
if ($statement === false)
{
// trigger (big, orange) error
trigger_error($handle->errorInfo()[2], E_USER_ERROR);
exit;
}
// execute SQL statement
$results = $statement->execute($parameters);
// return result set's rows, if any
if ($results !== false)
{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}
When I try something simple like query("Select * From table"), I get the following error message
Fatal error: SQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES) in /home/user/includes/functions.php on line 142
Please, any help would be greatly appreciated. I looked online and it looks like some forums have mentioned that I need to check my config file as per the advice of this post: https://forums.cpanel.net/threads/error-link-to-database-cannot-be-established.394212/
Edit: I do not have mySQL on my computer. I am using a windows. I set up the database inside of phpMyAdmin in cpanel.
Something like this:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $handle->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$handle->close();
Please see the section Granting user permissions part of https://www.digitalocean.com/community/tutorials/how-to-create-a-new-user-and-grant-permissions-in-mysql