Jesse Elser
Jesse Elser

Reputation: 976

PHP Retrieving Data From MySQL After Modifying URL Parameter

I'm building a webpage that retrives data depending on a URL parameter.

There are two possible parameters.

1: id which is retrieved using $_GET['id']

2: name which is retrieved using $_GET['name']

When I am retrieving data using the id parameter it works like a charm since id is always a numerical value and never alphabetical text.

But when attempting to retrieve data using the name parameter I get no results.

The name parameter is checking the database for an article with the articles title being the parameter.

For example the name parameter in a URL would look like so:

http://example.com/safetyarticles/view.php?name=9-clues-to-solving-this-parameter-issue

And in the database the articles name would be: 9 Clues To Solving This Parameter Issue

I've already written some lines to remove the dashes in my url parameter to spaces and then capitalize each word to match the article name, but I'm not getting any results.

This is the code I have written:

$conn = getConnected("safetyArticles");
if(isset($_GET['id'])) { 
    $articleID = $_GET['id'];
    $articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_id = $articleID");
    $article  = mysqli_fetch_array($articleQuery);
}
else if(isset($_GET['name'])) {
    $articleName = $_GET['name'];
    $articleName = preg_replace("/[\-]/", " ", $articleName); // Replace dashes in URL parameter with spaces
    $articleName = ucwords($articleName); // Uppercase first letter of each word of URL parameter 
    $articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = $articleName");
    $article  = mysqli_fetch_array($articleQuery);
}

To my knowledge replacing the dashes with spaces and capitalizing each word should make the article_name in the database and $articleName match.

I did add a line of echo $articleName just to see what the output was and the result was 9 Clues To Solving The Mystery Of The Pilot Car which matches the title in the database but the results are not being pulled.

I copied this directly out of the database just to show that the titles are indeed the same: 9 Clues To Solving The Mystery Of The Pilot Car.

I'm at a loss since everything is matching up as it should.

Upvotes: 1

Views: 45

Answers (2)

Frederick Eze
Frederick Eze

Reputation: 131

$articleName in your query needs to be quoted like this : '$articleName'. eg $articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = '$articleName'");

Upvotes: 1

gavgrif
gavgrif

Reputation: 15499

you need '' around the variables in the query:eg '$articleName':

$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = '$articleName'");

Upvotes: 2

Related Questions