Search code examples
phpurloptimizationusing

Using URL With Variables to Effect Code


I was wondering how you use ? (question marks) in your website to make it do different stuff based on the variable in the url. like: http://example.com/php/learn/kinder.php?level=$level like what's that called, and how do you use it? I assume with a switch statement This is my code at the momment:

<php
$con=mysqli_connect("host","username","pass","db");
  //Check connection
 if (mysqli_connect_errno())
   {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }

$level = mysqli_query($con,"SELECT gradek FROM profiles");
?>
<html>
<head>
<title> Redirecting </title>

<meta http-equiv="refresh" content="1; url=http://teachertechtutor.com/php/learn/kinder.php?level=$level> 
</head>
<body>
</body>
</html>

Then i'd have a switch... I know it's pointless. I just want to know for future reference.

So my question is: how to redirect using php variable in html How to use the ? to change the code.

I used bolli's code and this is what appears in the web page:

`<meta http-equiv="refresh" content="1; url=http://teachertechtutor.com/php/learn/kinder.php?level2=> </head> <body> </body> </html> 

And it still doesn't redirect correctly


Solution

  • In kinder.php place:

    $level = $_REQUEST['level'];
    echo $level;
    

    And read about POST and GET request. http://www.tizag.com/phpT/postget.php

    Or do you mean how to place the variable in the URL?

    Either do

     <meta http-equiv="refresh" content="1; url=http://teachertechtutor.com/php/learn/kinder.php?level=<?php echo $level;?>> 
    

    or

    echo "<meta http-equiv="refresh" content="1; url=http://teachertechtutor.com/php/learn/kinder.php?level=".$level;
    

    EDIT / UPDATE

    Are you trying to get the variable and based on it, switch the page content?

    You could do something like this?

    <?php
    
    //you could load header here
    //include 'header.php';
    
    /*
    *Load content based on $_get parameter
    */
    
        // Get the $variable from the url after the level=
    $page = (isset($_GET['level'])) ? $_GET['level'] : 'index';
    
    //Check to see if the file exist
    if (!file_exists($page . '.php'))
    {
    //echo "File does not exist" . $page;
    }
    
    switch ($page)
    {
    case 'test':
    include('test.php');
    break;
    
    case 'test2':
    include('test2.php');
    break;
    
    case 'test3':
    include('test3.php');
    break;
    
    //Defualt start page
    default:
    include('index.php');
    
    }
    
    // You could load footer here
    //include 'footer.php';
    ?>