I'm trying to build a my profile page with dynamic url's but for some reason, my code isn't working. This is the outcome I want to have, this is what I get when I replace $username with a username from the database.
And here is the error I keep getting:
There URL in image 2 is the same as in the first image.
The code I'm using:
$host = 'localhost';
$db = 'bitr';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
try {
$connect = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "DB Connection failed" . $e->getMessage();
}
session_start();
if (empty($_SESSION["userID"])) {
header('Location: login.php');
}
$username = $_GET['user'];
$datapdo2 = "SELECT * FROM users WHERE gebruikersnaam = $username";
$stmtpdo2 = $connect->prepare($datapdo2);
$stmtpdo2->execute();
$rowpdo2 = $stmtpdo2->fetchAll(PDO::FETCH_ASSOC);
foreach ($rowpdo2 as $users) {
echo "<tr>";
echo "<th>" . $users['omschrijving'] . "</th>";
echo "</tr>";
}
export.sql:
DROP DATABASE IF EXISTS bitr2;
CREATE DATABASE bitr2;
USE bitr2;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`gebruikersnaam` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`wachtwoord` varchar(255) DEFAULT NULL,
`omschrijving` text NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO `users` (`gebruikersnaam`, `email`, `wachtwoord`, `omschrijving`) VALUES
('Mauro', '[email protected]', '12345678', 'Ik ben Mauro en ik ben 17 jaar oud!');
CodePudding user response:
You're interpolating $username
into the query string, resulting in an unquoted-value. MySQL interprets this bare string as a column name, and then errors out since you don't have such a column. Instead, you should use a placeholder and bind the value dynamically:
$datapdo2 = "SELECT * FROM users WHERE gebruikersnaam = ?";
$stmtpdo2 = $connect->prepare($datapdo2);
$stmtpdo2->execute(array($username));