Exploring the Integration of MySQL with PHP

I have a great tool on my website that displays different pages based on user input. Here is the code for it:

 if(isset($HTTP_GET_VARS['mod']))
 {
 $page = $HTTP_GET_VARS['mod'];
 }
 else
 {
 $page = 'home';
 }

 switch($page)
 {

         case 'home':
         require('home.php');
         break;


         default:
         echo('Error: There is no file on this server with that name');
         }


          }

I am currently working on retrieving data from a database called "pages". The table has two fields - Name and Link. My goal is to display all of the results from this table so that users can access various pages.

Answer №1

The information in your query is somewhat ambiguous, but based on my interpretation, you are seeking a method to verify any value of $page against a link value stored in a database table (pages?) without manually listing all potential values in a switch statement.

If I have understood correctly, the following rough function can assist you with this task. In a live high-traffic setting, it would be essential to introduce caching mechanisms to avoid excessive database queries on each page load, along with robust input validation - both aspects that are not encompassed in the provided demonstration. Nevertheless, this should offer some direction for your next steps:

Common library file:

/**
 * Given a page name, this function checks if there is an associated
 * link in the database.
 * If found, return the link value, otherwise return false.
 */
function getTemplate($page)
{
    // Query the database to check for a link corresponding to this page
    // For busy sites, consider implementing caching strategies
    $query = sprintf("SELECT link FROM pages WHERE name = '%s'",
            mysql_real_escape_string($page));
    $result = mysql_query($query, $db_cnx);

    // Any results obtained?
    if (mysql_num_rows($result) > 0)
    {
        // Assumption: 'name' is unique in the db
        $row = mysql_fetch_assoc($result);
        return $row['link'];
    }
    else
    {
        return false;
    }
}

Header.php:

include('common.lib.php');
if(isset($HTTP_GET_VARS['mod']))
{
    $page = $HTTP_GET_VARS['mod'];
}
else
{
    $page = 'home';
}

// Verify if our page is linked in the database
$template = get_template($page);

if($template)
{
    require( $template );
}
else
{
    // No corresponding link was found in the database
    echo('Error: There is no file on this server with that name');
}

Answer №2

$server = "YOUR_SERVER";
$database_user = "DB_USER";
$password = "PASSWORD";
$database_name = "DB_NAME";
$table_name = "TABLE";

$conn = mysql_connect($server, $database_user, $password);
if (!$conn) {
  die('Connection failed: ' . mysql_error());
}
mysql_select_db($database_name);
$query = sprintf("SELECT Name, Link FROM %s", $table_name);
$result = mysql_query($query, $conn);
while ($row = mysql_fetch_assoc($result)) {
    echo "<a href='" . $row['Link'] . "'>" . $row['Name'] . "</a>";
}
mysql_free_result($result);
mysql_close($conn);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the method for measuring the size of a dynamically generated list

I'm currently working on a chat box that displays messages as a list. One issue I'm facing is that when I click on the start chat button, the chat box opens but the length of the list always remains zero. How can I resolve this problem? $(docu ...

The issue of broken images in the Azure Blob module for Drupal

Recently, I began constructing a Drupal website utilizing Azure. I successfully installed the Azure Blob module, and all functions worked flawlessly in my local environment, including image display and upload to storage blob. However, upon migrating the si ...

Using the JQuery Library, you can implement two submit buttons that either open in a new tab or submit

I am facing a situation where I have a FORM containing two submit buttons. My requirement is that when the first button is clicked, the form should submit on the same tab. On the other hand, if the second button is clicked, it should proceed to open a new ...

Efficiently displaying multiple links with varying values in a D3.js force-directed graph

Issue with Displaying Overlapping Lines I attempted to showcase numerous connections between nodes using a multi-array format (Source, Target, Value). However, the lines are not displaying correctly and appear to be overlapping. You can view my example h ...

Tips for using a JavaScript variable in a PHP file on WordPress

As a newcomer to Wordpress, I am trying to navigate the Theme Editor. Within it, I found a javascript file that looks like this: const isMenuOpen = false; function toggleMenu() { alert("toggle"); isMobileMenuOpen = !isMobileMenuOpen; } ...

managing arrays in JavaScript with multiple tables

**I have successfully written code for calculating the sum of inputs in one table** $('#example122').on('input', '.calculate', function () { calculateTotal(); }); function calculateTotal() { var grandTotal = 0; $ ...

CSRF verification for Laravel Commands was unsuccessful

There seems to be an issue I'm encountering while using cron for a Laravel Command. When the function is executed as php /path/to/artisan/ command:cron, it leads to an error stating CSRF verification failed. Has anyone found a solution to disabling C ...

FormBuilder Interface Silex File Input

Having recently subscribed, I have come to seek assistance on a platform where I have previously found many solutions to my issues. I have completed a course on Openclassrooms (Transitioning to a Professional PHP Architecture) which has equipped me with t ...

What is the best way to transfer an XML file from a server to a device using HTTP POST method?

I am in the process of setting up a server that will run on PHP, and I need to create an app for both iPhone and Android devices to parse the XML data that is sent. The app will send requests such as login and sign-in, and I am looking for guidance on ho ...

Issue with PHP array function is that it is only showing the first element in the array while disregarding the rest

Having an issue with displaying multiple client's items in an array. My current code only shows the first item id in the array. Can you help me identify what I'm doing wrong? Check out this example of sItem value: $items = array(); $cli ...

How to retrieve various items from a function call in PHP

Can a function in some languages (like Python) return multiple items and have them assigned to different variables in a single statement? For instance, is it possible to do something similar to this: a, b, c, d = foo(); ...

Monitor a user's activity and restrict the use of multiple windows or tabs using a combination of PHP and

I am looking to create a system that restricts visitors to view only one webpage at a time, allowing only one browser window or tab to be open. To achieve this, I have utilized a session variable named "is_viewing". When set to true, access to additional ...

What is the best way to execute a function that retrieves data from a MySQL query and then sends it back as a result in Express.js?

How can I refactor my code to efficiently call a function that returns the result of a MySQL query and send it back in an Express.js response? I am attempting to streamline my SQL queries by exporting them into individual functions to eliminate duplicatio ...

Trouble arises with single-page website's contact form

Seeking assistance with my one-page portfolio and contact form. I'm not proficient in PHP, so bear with me as I try to explain the issue. I have a contact template from WordPress that I've used previously, but now I want to incorporate it into my ...

Tips on implementing a Javascript function triggered by a user's click within the video player frame

<script> function greet() { alert("hello"); } </script> <iframe width="100%" height="315" src="https://www.youtube.com/embed/AGM0ibP1MRc" onclick="greet()"></iframe> .Kindly assist me, please. ...

PHPStan is throwing an error about the first parameter $length in the random_bytes function, expecting an integer in the range of 1 to the maximum

I encountered a perplexing PHPStan error that I am struggling to resolve: Parameter #1 $length of function random_bytes expects int<1, max>, int given. The function in question is rather straightforward: private function generateEncryptionKey(in ...

Exploring the PHP array slice feature

Hey there, I'm currently facing a challenge with iterating through my array chunks. I am working on creating an image gallery where groups of three images follow a specific pattern and then the next set of three follows the opposite pattern. I believ ...

Mastering web authentication using android studio

https://i.stack.imgur.com/g1jpd.png My server provides JSON data to my android app. How can I bypass the authentication code for username and password in Android Studio when the website requires authentication? I want users of my mobile app to avoid havi ...

You cannot set the column 'tax_id' as NOT NULL in Laravel

Currently, I am involved in a project that features a table containing a foreign key named tax_id. An issue arose when a migration was created to alter the column tax_id to be nullable at one point. Schema::table('products', function (Blueprint ...

My custom Wordpress plugin experiencing issues with the Ajax function not being triggered

I'm currently working on a plugin that includes a button to export a list to an Excel file. At the moment, the plugin index displays the list in a table format with the export button at the top. Below is the code snippet: Even when I try removing th ...