简体   繁体   中英

PHP passing variable through href

I'm having a little problem with passing a parameter for a query to another page.

I want to make the name of the restaurant a link that would pass the name of the product to process a query on the next page.

echo "<p class='p2'><a class='link' href='restaurant.php?name=". $row['name'] ."'><strong>". $row['name'] ."</strong></a>

on the restaurant page

<?php
require ("db.php");
$name = $_GET['name'];

$query = "SELECT * FROM restaurant WHERE name =\"$name\"";
$result = mysql_query($query);
$row = mysql_fetch_array($result);   
?>

but nothing is displayed.

Any idea what I'm doing wrong?

First, a note: you should pass an ID rather than the name, since certain characters aren't great in URLs.

Second, try using urlencode() on the name.

echo "<p class='p2'><a class='link' href='restaurant.php?name=". urlencode($row['name']) ."'><strong>". $row['name'] ."</strong></a>

Of course it won't display anything, because you don't have any print functions (echo, print, var_dump, ...) in your file.


Anyways, you probably thought that your query doesn't work. If so, try to echo your $row['name'] . If everything's OK, check if your variable is set, but it probably isn't because you get null .

To fix that issue, use isset() or empty() .

Example:

if(!empty($_GET['name'])) $name = $_GET['name'];
else die('Variable name is empty');

Try also to add ini_set('display_errors', true) to the top of your pages to see if there's any errors.


Note that your code is very insecure and vulnerable. Use mysql_real_escape_string() before executing queries.

Example:

$name = mysql_real_escape_string($_GET['name']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM