The Problem
I am really struggling to get wordpress to generate a page dynamically based on the content of a database.
The Context
I have a sql database which contains unique slugs and Ids, and I am able to make a page on wp which pulls the data in from the sql database and presents it in a table of the items.
The bit I cannot work out how to do is generate a unique page based on the slug (or even the Id) for each table row.
My Code
This is the code on the index page of the devices, and it works fine; it displays what I need, each href is the slug from the database.
I am using a custom template php file for the specific wordpress pages in question.
page-206.php
- this is for the 'index' page
<tbody style=>
<?php foreach ($devices AS $device):
//$newUrl = "http://example.com$device[slug]";
$newUrl = "page-device-repair-service.php?id=$device[slug]";
?>
<tr style=>
<td style=>
<a style=href="<?=$newUrl?>">
<?php echo "$device[deviceName]" ?>
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
page-214.php
- this is for the 'results' page
if (isset($_GET['id']))
{
$slug = $_GET ['id'];
}
else
{
$slug = "";
}
include 'sql_connect.php'; //db connection
$connection = new PDO ($dsn, $username, $password);
$connection -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "connection successful";
$sql = "SELECT *
FROM newdevices
WHERE slug = $slug";
$url = "http://18.168.90.222$slug";
The results
The result I am getting is the 'page not found', so something is missing, I just don't know enough to know what.
Further
Do I have to insert the php code into the page directly, rather than use a template? If so, how do I go about doing that on wordpress? https://stackoverflow.com/q/57643520/18227124 say they used Advanced Ads plugin, but I have looked and I am not sure thats what I want. I have tried header and footer insert but I don't want the php running on every page on the site, just this 'results' page.
Extra
Just in case its needed, my sql_connect.php
looks like this
<?php
$host = "localhost";
$dbName = "myDatabase";
$username = "root";
$password = "xxxxxx";
$dsn = "mysql:host=$host;dbname=$dbName";
//specify if local or production
//$liveUrl = "http://.....$device[slug]";
//$newUrl = "http://18.168.90.222$device[slug]";
//$localUrl="http://localhost$device[slug]";
$devices = "";
try {
$connection = new PDO($dsn, $username, $password);
$connection -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "connection succesful";
$sql = "SELECT * FROM newdevices";
$devices = $connection -> query ($sql);
} catch (PDOException $error){
echo $error -> getMessage();
}
?>
The comments are for when I'm testing on my local or my production site.
Please excuse me if I am missing something glaringly obvious, I am relatively new to PHP, SQL and PHP on wordpress.
Edit
I know there are similar questions on SO and SE, I have been searching, reading and trying to replicate various answers into my own code but nothing I do is working!