Harvey Mackie
Harvey Mackie

Reputation: 21

How to use $_GET in mysqli/php to extract an integer from the URL?

How to use $_GET in MySQLI/PHP to extract an integer from the URL to be bind into a SQL statement?

Making a blog esque page where the content is stored in a database, meaning that there can be multiple pages without the need for numerous files.

On the index page, there are links to these pages, once clicked, the URL is changed to the blog page with the ID posted:

pages/article.php?id=1

Here's how -

for($x=0;$x<$articlesFetched;++$x){
    $row=mysqli_fetch_array($data);
    //create div
    echo '<div class="col-lg-4 col-md-6 col-sm-6 col-xs-12" id="articleDiv">';
    echo "<img class='img-responsive' id='articleImage' src=".$row['articleThumbnail'].">";  
    echo '<h5><a href="article.php?id='.$row['articleId'].'">'.$row['articleHeadline'].'</a></h5>';
    echo '<p>',$row['articleSummary']," ",'</p>';
    echo '<div class="row">';
    echo '<p>' , $row['articleTopic']," | ",'</p>';
    echo '<p>', $row['articleSubTopic']," | ",'</p>';
    echo '<p>',$row['articleDate']," | ",'</p>';
    echo '</div>';            
    echo '</div>';
}

PS - excuse the indentation, copy and paste seems to mess the formatting up.

To tell the difference between page content, I have used an ID, which can be binded to the SQL statement e.g. 'SELECT * FROM table WHERE id=?'

Heres how:

$id=$_GET['articleId'];
$stmt = $conn->prepare("SELECT * FROM Article WHERE articleId=?");
$stmt->bind_param("i",$id);
$stmt->execute();

However, when the web page is opened there is no content, as there is a Undefined index error, pointing $id=$_GET['articleId'];

When checking if $id=$_GET['articleId']; variable is set, the output is FALSE.

Upvotes: 1

Views: 289

Answers (3)

proghasan
proghasan

Reputation: 425

Your url pages/article.php?id=1 But You use $id=$_GET['articleId'];

You Simple Use it $id=$_GET['id'];

Code:

$id=$_GET['id'];
$stmt = $conn->prepare("SELECT * FROM Article WHERE articleId=?");
$stmt->bind_param("i",$id);
$stmt->execute();

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Actually your URL become something like this:-

article.php?id=1 //for example

So yo need to do:-

$id = $_GET['id']; // not $_GET['articleId']

Upvotes: 2

Krishnadas PC
Krishnadas PC

Reputation: 6529

In the $_GET you have used articleId but what You have pasted on url is id. Both names must be the same then only it will fetch data.

As an example

www.yoursite.com/category?q=myname

<?php
   echo $_GET['q'];  //Output: myname
?>

Upvotes: 0

Related Questions