I am trying to individually print out each line from my SQL database in PHP. I am trying to do this so each line that is retrieved, it can act like a link which will direct the user to another page. For example, the current SQL query will output the Category names from the database Category, i would like it to output all the values from that table but have it so each one has a different redirect link to another page which clicked on.
$query = "SELECT CATEGORY_NAME
FROM CATEGORIES ORDER BY CATEGORY_ID ASC";
$results = #mysqli_query ($conn, $query);
$numrows = mysqli_num_rows($results);
if ($results) {
if ($numrows >0) {
echo '
<table>
<tr>
<td><strong>Categories</stong></td>
</tr>';
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo '<tr>
<td>' . $row['CATEGORY_NAME'] . '</td>
</tr>
';
}
mysqli_free_result ($results);
Such as,
Category
__________
PS4
XBOX
i can click on PS4 and it would take me to another page, i know how to do this with a href and then print out the row in sql however, i'm not sure how do print out each row individually without printing them out using $row['CATEGORY_NAME'].
Thank you for any help
You could just store the link to which it needs to be redirected in a new column CATEGORY_URL along with the CATEGORY_NAME and then print it out like so:
$query = "SELECT CATEGORY_NAME, CATEGORY_URL FROM CATEGORIES ORDER BY CATEGORY_ID ASC";
$results = mysqli_query($conn, $query);
$numrows = mysqli_num_rows($results);
if ($numrows > 0) {
echo '
<table>
<tr>
<td><strong>Categories</stong></td>
</tr>';
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo '
<tr>
<td>
'.$row['CATEGORY_NAME'].'
</td>
</tr>';
}
mysqli_free_result ($results);
} else {
// no results found
}
OR if you just want to pass it as a url parameter, you just need to modify if like so:
'.$row['CATEGORY_NAME'].'
OR
'.$row['CATEGORY_NAME'].'
Something like? (I'm not 100% sure if I understand your question)
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo '<tr>
<td><a href="somelink.php?cat=' . $row['CATEGORY_NAME'] . '">' .
$row['CATEGORY_NAME'] . '</a></td>
</tr> ';
}
UPDATE
If a category is named playstation, playstation.php would be linked to...
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo '<tr>
<td><a href="' . $row['CATEGORY_NAME'] . '.php">' .
$row['CATEGORY_NAME'] . '</a></td>
</tr> ';
}
Though above would work a wild guess is that you're looking for something completely different. The thing you are looking for is essentially a way to present information for playstation, a way to present information about PS4 etc depending on what user clicks on!? In that case you should do something like this instead:
//Include ID of category in your sql-statement
$query = "SELECT ID, CATEGORY_NAME
FROM CATEGORIES ORDER BY CATEGORY_ID ASC";
....
....
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo '<tr>
<td><a href="presentinfo.php?id=' . $row['ID'] . '">' .
$row['CATEGORY_NAME'] . '</a></td>
</tr> ';
}
and create presentinfo.php file where you fetch information about the category, based on the id given in the url. (e.g.select from categories id={id given in url})
Related
Repairtable.php
<?php
// Connect to the database
$db = new mysqli('localhost', 'username', 'password', 'repair_shop');
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
// Get the search input from the form
$search = isset($_GET['search']) ? $_GET['search'] : '';
// Get the sorting parameters from the query string
$sort = isset($_GET['sort']) && !empty($_GET['sort']) ? $_GET['sort'] : 'work_orders.id';
$order = isset($_GET['order']) && in_array($_GET['order'], array('asc', 'desc')) ? $_GET['order'] : 'asc';
$status = isset($_GET['status']) && !empty($_GET['status']) ? $_GET['status'] : '';
$where = "WHERE customers.name LIKE '%$search%' OR devices.type LIKE '%$search%' OR devices.issues LIKE '%$search%'";
if ($status) {
$where .= " AND work_orders.status='$status'";
} else {
$where .= " AND work_orders.status IN ('Awaiting Repair', 'Repair In Progress', 'Ready For Pickup', 'Repair Complete', 'Sale Complete')";
}
$query = "SELECT work_orders.id, devices.type AS device_name, customers.name, work_orders.status, devices.service_request_id, devices.issues
FROM work_orders
INNER JOIN devices ON work_orders.device_id = devices.id
INNER JOIN customers ON devices.customer_id = customers.id
$where
ORDER BY work_orders.status $order
LIMIT 10 OFFSET 0";
echo("status: " . $status);
$result = $db->query($query);
// Check for errors
if ($db->error) {
die("Query failed: " . $conn->error);
}
// Check if there are any results
if ($result->num_rows > 0) {?>
<table class='table table-striped'>
<tr class='thead-dark'>
<th>
ID
</th>
<th>
Device Name
</th>
<th>
Customer Name
</th>
<th>
<form method="get" id="form" action="#">
<select id="status" name="status" onchange="loadRepairs('<?php echo $sort; ?>', '<?php echo $order; ?>');">
<option value="">Status</option>
<option value='Awaiting Repair'>Awaiting Repair</option>
<option value='Repair In Progress'>Repair In Progress</option>
<option value='Ready For Pickup'>Ready For Pickup</option>
<option value='Repair Complete'>Repair Complete</option>
<option value='Sale Complete'>Sale Complete</option>
</select>
</form>
</th>
<th>
Service Request ID
</th>
<th>issues</th>
<th>View/Edit</th>
</tr>
<?php
// Print the table rows
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td class='align-middle'>" . htmlspecialchars($row['id']) . "</td>";
echo "<td class='align-middle'>" . htmlspecialchars($row['device_name']) . "</td>";
echo "<td class='align-middle'>" . htmlspecialchars($row['name']) . "</td>";
echo "<td class='align-middle'>" . htmlspecialchars($row['status']) . "</td>";
echo "<td class='align-middle'>" . htmlspecialchars($row['service_request_id']) . "</td>";
echo "<td class='align-middle'>" . htmlspecialchars($row['issues']) . "</td>";
echo "<td class='align-middle'><button class='btn btn-primary' data-toggle='modal' data-target='#repairModal' data-id='" . $row['id'] . "' data-device-name='" . $row['device_name'] . "' data-customer-name='" . $row['name'] . "' data-service-request-id='" . $row['service_request_id'] . "' data-status='" . $row['status'] . "' data-issues='" . $row['issues'] . "'>View/Edit</button></td>";
echo "</tr>";
}
// Close the table
?>
</table>
<?php
// Close the database connection
$db->close();
}
?>
LoadRepairs function:
function loadRepairs(sort = 'id', order = 'asc') {
// Get the selected status value
var status = $('#status').val();
console.log(status);
// Load the repairtable.php file into the repairsTable element,
// and include the selected status value, as well as the sort and order values,
// in the query string
$.get(`includes/repairtable.php?status=${status}&sort=${sort}&order=${order}`, function(response) {
$('#repairsTable').html(response);
});
}
Query with a status selected:
SELECT work_orders.id, devices.type AS device_name, customers.name, work_orders.status, devices.service_request_id, devices.issues FROM work_orders INNER JOIN devices ON work_orders.device_id = devices.id INNER JOIN customers ON devices.customer_id = customers.id WHERE customers.name LIKE '%%' OR devices.type LIKE '%%' OR devices.issues LIKE '%%' AND work_orders.status='Awaiting Repair' ORDER BY work_orders.status asc LIMIT 10 OFFSET 0
So, this produces a table with headers which are links to sort the table, except for status, it's a dropdown for filtering the table to only display the selected status.
The trouble is that none of the sorting and filtering seems to work as expected. when i click a table header, it will sort by ascending or descending, but it sometimes has random mixed in results which are not in the desired order, like 21 appearing before 20, additionally when i filter the results with the status dropdown, it just doesn't filter at all.
My guess is that my sql query is poorly constructed, because that's my weakest area, but i'm really just not sure anymore. i've debugged seemingly each link in the chain, but i can't seem to find the bug. I'm really hoping someone else can.
If any more detail is required, please let me know. Any help is appreciated.
Thanks to everyone warning me about SQL injection, You guys are 100% right, but i'm also designing this to be used by a grand total of 3 people, all of which are employees of the store for which i work, so i'm not super worried about attack vectors, but thank you for looking out for me. The sentiment is appreciated.
I feel the issue is in this part of your query,
...AND work_orders.status='Awaiting Repair' ORDER BY work_orders.status asc...
You are trying to show data's based on a particular value in the status column, then what is the need for ordering it based on the same status field?
Replace the above section with the below and try,
...AND work_orders.status='Awaiting Repair' ORDER BY work_orders.id asc...
The above will order the data's based on the id.
I have this query to list name categories and avg of each one, but the result is not what I want, how to sove this? if you look to image you see that the table resulta don't show correct
$query = $connMysqli->query("SELECT qc.name as cat_name
FROM fhrw_question_categories qc
...
group by Quiz, cat
ORDER BY u.id");
?>
<table>
<tr>
<?php
while($row = $query->fetch_assoc()){
echo '<th>' . $row['cat_name'] . '</th>';
}?>
</tr>
<!-- table continiuous avg-->
<?
$query = $connMysqli->query("SELECT avg(IFNULL(fraction, 0)) * 10 as Media, u.ud as student, qc.name as cat_name
FROM fhrw_question_attempt_steps qc
...
group by Quiz, u.id, cat
ORDER BY u.id ASC");
?>
<?php
while($row = $query->fetch_assoc()){
echo '<tr><td>' . $row['cat_name'] . ' - ' . round($row['Media'],2) . '</td></tr>';
}?>
I'm very new to HTML, PHP & MySql, so apologies for the noob question but, I need to retrieve categories from a database, that are in 2 tables, but am having difficulty calling the subcategories after clicking the initial link.
//Category code as...
<?php
require 'dbcon.php';
$sql = "SELECT * FROM `category`";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
echo "<table>
< tr >
<th>Category < /th>
< /tr>";
while ($row = $result ->fetch_assoc()) {
$id = $row['category_ID'];
echo "<td>" .$row['description']. "</td>";
echo "</tr>";
}
echo "</table>";
?>
//Subcategory code as...
<?php
require 'database_conn.php';
$sql = "SELECT category.ID, subcategory.title, subcategory.ID FROM category, subcategory WHERE subcategory.ID=category.ID";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
echo "<table>
< tr >
<th>Title < /th>
< /tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" .$row['title']. "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
Ideally, I would like it so that selecting one category will bring up the whole list of subcategories, either in the same page or a separate page. I've struggled over this for a few days now and I'm really struggling to understand what it is I am doing wrong.
simply take the id from the URL and put into your query
$category_id = $_GET['id'];
SELECT * FROM subcategory WHERE category_id = $id;
im having problems with this code
<?php
include '01.php';
include 'header.php';
$sql = "SELECT cat_id, cat_name, cat_description FROM categories WHERE cat_id = " . mysql_real_escape_string($_GET['id']) . "";
$result = mysql_query($sql);
if(!$result)
{
echo 'The category could not be displayed, please try again later.' . mysql_error();
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'This category does not exist.';
}
else
{
//display category data
while($row = mysql_fetch_assoc($result))
{
echo '<h2>Topics in ′' . $row['cat_name'] . '′ category</h2>';
}
//do a query for the topics
$sql = "SELECT
topic_id,
topic_subject,
topic_date,
topic_cat
FROM
topics
WHERE
topic_cat = " . mysql_real_escape_string($_GET['id']);
$result = mysql_query($sql);
if(!$result)
{
echo 'The topics could not be displayed, please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'There are no topics in this category yet.';
}
else
{
//prepare the table
echo '<table border="1">
<tr>
<th>Topic</th>
<th>Created at</th>
</tr>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $row['topic_subject'] . '<h3>';
echo '</td>';
echo '<td class="rightpart">';
echo date('d-m-Y', strtotime($row['topic_date']));
echo '</td>';
echo '</tr>';
}
}
}
}
}
include 'footer.php';
?>
the error it gives me is this The category could not be displayed, please try again later.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 strong text **
$sql = "SELECT cat_id, cat_name, cat_description FROM categories WHERE keeps not working for some reasonstrong text**
would really appreciate the help i dont know what to do anymore googled everywhere and tried different combinations but cant get the id from cat_id please help
seems you don't have proper quote. you should enclose the result of your mysql_real_escape_string($_GET['id']) inside '
like the sample below
"SELECT cat_id, cat_name, cat_description
FROM categories WHERE cat_id = '" . mysql_real_escape_string($_GET['id']) . "'";
if you want try to use a simplified query remember the quotes this way:
$sql= mysql_query("SELECT cat_id, cat_name, cat_description
FROM categories WHERE cat_id = '" .$id . "';");
but for debugging try
var_dump($id);
var_dump($sql);
and check if $id contain a proper value and $sql is correctly formed (try copy the resulting query and execute it in your console)
then if the query give you the right result in console this mean the resulting query is right..
PS the url should be
xxxxx.com/category.php?id=1
remember to assign a value to your id
i'm trying to find a solution, i'm trying to get a data from different tables using same id. Here is my code
"SELECT * FROM menucat LEFT JOIN vmenutab ON menucat.cat_id = vmenutab.menu_id";
I need to create sections, and fill them later with some content, table menucat is parent table with sections, vmenutab is child table with content.
But i have a problem, it doesn't show up correctly. It should be like this:
Section1
Link1
Link2
But it shows up like this:
Section1
Link1
Section1
Link2
I've been using search, GROUP BY and DISTINCT didn't worked.
tables:
menucat:
cat_id menu_cat_est menu_cat_ru menu_cat_en
vmenutab:
id (unique link id) menu_id (id to related section) menu_name_est menu_name_ru menu_name_en
menu_cat_xxx and menu_name_xxx are different languages data
PHP Code
<?php
$target = "SELECT * FROM menucat LEFT JOIN vmenutab ON menucat.cat_id = vmenutab.menu_id";
$mq = mysql_query($target);
while ($row = mysql_fetch_array($mq)) {
$menu_cat_est = $row['menu_cat_est'];
$menu_cat_ru = $row['menu_cat_ru'];
$menu_cat_en = $row['menu_cat_en'];
$menu_name_est = $row['menu_name_est'];
$menu_name_ru = $row['menu_name_ru'];
$menu_name_en = $row['menu_name_en'];
$cat_id = $row['cat_id'];
$id = $row['id'];
echo '<tr>
<td>' . $menu_cat_est . ''.$menu_name_est.'</td>
<td>' . $menu_cat_ru . ''.$menu_name_ru.'</td>
<td>' . $menu_cat_en . ''.$menu_name_en.'</td>
<td scope="col"><center><img src="style/stylesheet/images/edit.png"></center></td>
<td scope="col"><center><img src="style/stylesheet/images/delete.png"></center></td>
<td scope="col"><center>Добавить</center></td>
</tr>';
}
?>
Sorry for my english. Best Regards.
EDIT: Added entire PHP Code.
EDIT #2: Added table rows.
an example as i don't know your db data. also sort db by cat id
' . $menu_cat_xxx . ''.$menu_name_xxx.' its a bit confusing
$target = "SELECT * FROM menucat LEFT JOIN vmenutab ON menucat.cat_id = vmenutab.menu_id" order by menucat.cat_id;
$mq = mysql_query($target);
while ($row = mysql_fetch_array($mq)) {
$menu_cat_est = $row['menu_cat_est'];
$menu_cat_ru = $row['menu_cat_ru'];
$menu_cat_en = $row['menu_cat_en'];
$menu_name_est = $row['menu_name_est'];
$menu_name_ru = $row['menu_name_ru'];
$menu_name_en = $row['menu_name_en'];
$cat_id = $row['cat_id'];
$id = $row['id'];
if(!$nocat[$cat_id]){ $nocat[$cat_id] = $cat_id; $section='<tr><td colspan="6"> section' . $cat_id . '</td></tr>
';}else{$section='';} // customise as i need sleep
echo $section.
'<tr>
<td>' . $menu_cat_est . ''.$menu_name_est.'</td>
<td>' . $menu_cat_ru . ''.$menu_name_ru.'</td>
<td>' . $menu_cat_en . ''.$menu_name_en.'</td>
<td scope="col"><center><img src="style/stylesheet/images/edit.png"></center></td>
<td scope="col"><center><img src="style/stylesheet/images/delete.png"></center></td>
<td scope="col"><center>Добавить</center></td>
';
}