I’m trying to display each single row from my db as a separated unique page, so when I click on the row link (which I don’t even know what it is until now) it directs me to a new page with the content of this row or some of the content as I desire..
So I created a new php file, and inserted this code but it doesn’t work after all.
include "db_connect.php"; $sql = "SELECT Joke_question, Joke_answer FROM jokes_table WHERE JokeID = '". $_GET['JokeID']."'"; $result = $mysqli->query($sql); $row = $result->fetch_assoc() echo $row["Joke_question"]; ?>
Tried to include ?id=
into the url to see if I can actually access a row in a unique page, but still doesn’t work.
I am a beginner, so I hope the answer will be simple enough for me to understand.
I want to know what should I do to generate a page for each row I have?
Edit:
PROBLEM SOLVED BY CHANGING THE CODE INTO THIS (BUT i have another issue):
$id = $_GET['JokeID']; $sql = "SELECT Joke_question FROM jokes_table WHERE JokeID = '". $id."'"; $result = $mysqli->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo $row["Joke_question"]; } } else { echo "0 results"; }
But sadly i have another problem..
I wanna display a URL for each row in my database on my main page, but i dont wanna do this manually one by one, i want it to be generated dynamically through a loop.
What im using on my main page:
<a href="single_joke.php?JokeID=1">click</a> <a href="single_joke.php?JokeID=2">click</a> <a href="single_joke.php?JokeID=3">click</a>
I want to loop the process.
EDIT(SOLVED):
Updated Code:
$sql = "SELECT * FROM jokes_table"; $result = $mysqli->query($sql); $breaking_space = array(); while($row = $result->fetch_assoc()) { $breaking_space[]='<a href="single_joke.php?JokeID='. $row['JokeID'].'">'.$row['Joke_question'].'</a>'; } echo implode('<br/> ', $breaking_space);
Advertisement
Answer
You can fetch all the rows on the page and then display it as links using the fetch_assoc function
$sql = "SELECT JokeId FROM jokes_table"; $result = $mysqli->query($sql); while($row = $result->fetch_assoc()) { echo "<a href='single_joke.php?JokeID=".$row['JokeId']."'>click</a>"; }
you can also use SELECT * FROM jokes_table
if you want other columns from the database table.
this will get all the rows of the table and display it as a link that will go to their respective page.