I have a scenario in where I would like to create button links to allow users to view there own adverts, but the amount of ads will depend from user to user.
For example, John would have 3 ads stored in ads table(username, advertid, adverttitle, advertdescription), and he would have one account in accounts table(username, name, email, password).
When John logs in he would see 3 buttons (not physical buttons but hyperlink buttons), these button names will correspond to adverttitle in mysql database. Once John clicks on any given ad, he can view the advert description, make changes ect (not relevant to my issue though).
I'm not looking for ways to link advert to different forms, I would just like to know how I could create hyperlink buttons (text buttons) which generate depending on how many ads a user has in the advert table (user can have infinite ads, therefore infinite hyperlink buttons, as username is not pk, but advertid is). thanks in advance.
Note: I have already created a html form, with PHP connecting to MySQL. I just don't know how to create hyperlinks based on the amount of ads a user has.
advert table example
username advertid adverttitle advertdes
john345 123 ad1 ad1des
john345 125 ad2 ad2des
john345 126 ad3 ad3des
user table example
username name email password
john345 john whocares why
You will first need to query a database and then iterate results over in while loop in order to generate HTML links:
PDO:
$userId = 'john345';
$sql = 'SELECT * FROM advert WHERE username = :userId';
$query = $db->prepare($sql);
$result = $query->execute(array('userId' => $userId));
$output = '';
while ($row = $result->fetch(\PDO::FETCH_ASSOC)) {
$output .= '<a href="advert.php?id='.$row['id'].'">'.$row['name'].'</a>';
}
echo $output;
Also you can move PDO::FETCH_ASSOC into a connection setup, if you don't want to keep passing this option.
MySQLi:
$userId = mysqli_real_escape_string('john345');
$sql = 'SELECT * FROM advert WHERE username = '.$userId;
$result = $mysqli->query($sql);
$output = '';
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$output .= '<a href="advert.php?id='.$row['id'].'">'.$row['name'].'</a>';
}
echo $output;