PHP/MySQL Table with Hyperlinks - php

I have 2 PHP forms. One displays a list of events and the other displays the results of each specific event. On the page with the list of events I would like it so that a hyperlink can be created to access each individual event's results.
For example, on the Events page I click on row 2's hyperlink which will then take me to the Results page that has the results for that specific event.
Any help would be appreciated as I am very, very new to PHP. If any extra details are needed, please feel free to ask.
Thanks.
Edit: Sorry I'll show you what the Events form looks like so far:
<?php
mysql_connect('localhost','root','');
mysql_select_db('clubresults') or die( "Unable to select database");
$sql = "SELECT *, DATE_FORMAT(EventDate, '%d/%m/%y') as newdate FROM Events";
$result = mysql_query ($sql);
?>
<table border = 1>
<tr>
<th>Event ID</th>
th>Event Name</th>
<th>Event Date</th>
<th>Location</th>
</tr>
<?php
while ($row = mysql_fetch_array($result))
{
echo "</td><td>" . $row['EventID'] . "</td><td>" . $row['EventName'] . "</td><td>" . $row['newdate'] . "</td><td>" . $row['Location'] . "</td><tr>";
}
echo "</table>";
mysql_close();
?>

You don't need two scripts, but just one:
events.php?list
events.php?event=1234
in there you only need to check for things:
$db = new Database(); # simplified
/* show event details if requested */
if (isset($_GET['event']) {
if ($event = $db->getEventByID($_GET['event'])) {
printf('<h2>Event: %s</h2>', htmlspecialchars($event->title));
# ...
}
}
/* show the list if requested (or show it always, whatever pleases you) */
if (isset($_GET['list']) {
echo '<table>';
foreach($db->getEventList() as $event) {
printf('<tr><td>%s</td></tr>'
, $event->ID, htmlspecialchars($event->title));
}
echo '</table>';
}
Edit: As I saw in your updated question, you should switch from those oldskool mysql_* functions to the class style I outlined in my example, because it is much simpler to use. Here is a code-example that is close to yours:
<?php
/**
* My First PDO Databaseclass
*/
class Database extends PDO
{
public function __construct()
{
$host = 'localhost';
$name = 'clubresults';
$user = 'root';
$pass = NULL;
parent::__construct("mysql:host=$host;dbname=$name", $user, $pass);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function getEvents()
{
$sql = "SELECT *, DATE_FORMAT(EventDate, '%d/%m/%y') as newdate FROM Events";
return $this->query($sql, PDO::FETCH_OBJ );
}
public function getEventByID($id)
{
$sql = sprintf("SELECT * FROM Events WHERE EventID = %d;", $id);
return $this->query($sql)->fetchObject();
}
}
$db = new Database();
?>
<table border=1>
<tr>
<th>Event ID</th>
th>Event Name</th>
<th>Event Date</th>
<th>Location</th>
</tr>
<?php
foreach($db->getEvents() as $event)
{
echo "</td><td>" . $event->EventID . "</td><td>" . $event->EventName . "</td><td>" . $event->newdate . "</td><td>" . $event->Location . "</td><tr>";
}
?>
</table>

Related

How to display a php variable in another php file?

I am working with this php code which makes a query and then displays the information in a table. There is a column returned from this query called 'queue' which I want to store in a variable called '$queue_tittle' and then display this variable in index.php but when I try to do so, the variable is empty, it does not display any information.
query.php
<?php
session_start();
$queue_tittle = "";
function fill(){
if (isset($_GET['vid'])){
$vid = $_GET['vid'];
if (!$conn = new mysqli("localhost", "root", "", "zendesk_data")){
$output="Connection failed: " . $conn->connect_error;
}
else {
$sql = "SELECT status, id, subject, requester, requested, requested_updated, service, next_sla_breach, queue FROM $vid";
if ( $result = $conn->query($sql) ){
if ($result->num_rows > 0) {
$output="<table class='queue_table'>
<tr align='left'>
<th>Status</th>
<th>ID</th>
<th>Subject</th>
<th>Requester</th>
<th>Requested</th>
<th>Requested Updated</th>
<th>Service</th>
<th>Next SLA Breach</th></tr>";
while($row = $result->fetch_assoc()) {
$queue_tittle = $row["queue"];
$output.= "<tr><td>". $row["status"]. "</td><td><a href='../tickets/new.php?tid=" . $row["id"] . "'>" . $row["id"]. "</a></td><td>" . $row["subject"]. "</td><td>" . $row["requester"]. "</td><td>" . $row["requested"]. "</td><td>". $row["requested_updated"]. "</td><td>".
$row["service"]. "</td><td>". $row["next_sla_breach"]. "</td></tr>";
}
$output.="</table>";
} else {
$output= "0 results";
}
} else {
$output="Error en la consulta: ".$conn->error;
}
$conn->close();
}
echo $output;
}
}
?>
index.php
<div id="inner_cont">
<div id="queue">
<?php
include '../utilities/query.php';
fill();
echo $queue_tittle;
?>
</div>
I know this is may be an easy question but I have tried to follow online tutorials to solve this but nothing seems to work for my case. All help will be highly appreciated, thanks beforehand.
You could just return the title from the function.
function fill() {
$queue_tittle = "";
// ...
echo $output;
}
return $queue_tittle;
}
and
<?php
include '../utilities/fill.php';
$queue_tittle = fill();
echo $queue_tittle;
?>
If you need to return more bits of data, you can wrap them in an associative array.
You need to add global into fill to access $queue_tittle - like so:
function fill(){
global $queue_tittle;

Calling another function within a function - positioning the output

I have the following function:
public function createRatingButtons(){
for($count=1;$count<=5;$count++){
echo "<button onclick=''><b>$count</b></button> ";
}
}
The above function simply creates 5 separate buttons, labelled 1, 2, 3, 4, and 5!
I am calling the above function below:
public function displayGrades($student,$unit){
$studentID = $this->getStudentID($student);
$unitID = $this->getUnitID($unit);
$obj = new dbConfig();
$obj->dbConnect();
$sql="SELECT * FROM grading where studentID = '$studentID' && unitID = '$unitID'";
$result = mysqli_query($obj->conn,$sql) or die(mysqli_error($sql));
$row = mysqli_fetch_assoc($result);
echo "
<table>
<tr>
<td>Independence</td>
</tr>
<tr>
<td>Current Rating: " . $row['independence'] . "</td>
</tr>
<tr>
<td>" . $this->createRatingButtons() . "</td>
</tr>
<tr>
<td>Participation</td>
</tr>
.
.
.
PROBLEM: It displays the buttons, but they do not appear in that column where I have called the function. The buttons appear above the table. I want them to appear in the same column where I am calling the function.
How do I fix this problem? Please can anyone help. Thank you in advance
Your are echoing inside an echo, and this is not possible.
Maybe you should try to build a string of buttons, by doing this :
public function createRatingButtons(){
$result = "";
for($count=1;$count<=5;$count++){
$result.="<button onclick=''><b>$count</b></button> ";
}
return $result;
}

Trying to delete a row from a table

At the moment I am displaying in a table all the patients that are registered to a health centre. I have added a delete button or delete link that will remove the patient from the table. When I click on the delete button I am getting an error message and all of the patients that were previously displayed are gone and the 'all patient view' page now echoes out '0 results'.
If someone could help me resolve the issue so that I can remove a patient from the table that would be much appreciated.
Error Message
Warning: main(): Couldn't fetch mysqli_result in E:\WebProgrammingAssignment\views\AllPatientsView.php on line 48
UPDATED Register Patient Model
<?php
require_once('DAO.php');
class RegisterPatientModel extends DAO
{
protected $target = "patient";
public function __construct()
{
parent::__construct();
}
public function insertPatient($firstname, $lastname, $patstreet, $patcity, $patpostcode, $patphone, $doctorid, $dob)
{
$firstname = parent::escape($firstname);
$empnin = parent::escape($lastname);
$patstreet = parent::escape($patstreet);
$patcity = parent::escape($patcity);
$patpostcode = parent::escape($patpostcode);
$sql = "INSERT INTO {$this->target} (`firstname`, `lastname`, `patstreet`, `patcity`, `patpostcode`, `patphone`, `doctorid`, `dob`) VALUES ('{$firstname}', '{$lastname}', '{$patstreet}', '{$patcity}', '{$patpostcode}', '{$patphone}', '{$doctorid}', '{$dob}');";
return parent::query($sql);
}
public function deletePatient($patientid)
{
$sql = "DELETE
FROM {$this->target}
WHERE patientid='{$patientid}'";
return parent::query($sql);
}
function getAllPatients()
{
$sql = "SELECT a.patientid,
concat(d.firstname, ' ', d.lastname) as fullname_doctor,
a.firstname, a.lastname, a.patstreet, a.patcity, a.patpostcode, a.patphone, a.dob
FROM patient as a
INNER JOIN doctor as d
on a.doctorid = d.doctorid;";
return parent::query($sql);
}
}
?>
UPDATE All Patient View
<html>
<tr>
<td colspan="5" align="center">
<div id="boxalign2" class="boxalign2">
<div class="inputwrap">
<br>
<table id="customers" width="900" border="1" cellspacing="0" cellpadding="1">
<tr align="center">
<td bgcolor="#008000">Patient ID</td>
<td bgcolor="#008000">Doctor Name</td>
<td bgcolor="#008000">First Name</td>
<td bgcolor="#008000">Last Name</td>
<td bgcolor="#008000">Street</td>
<td bgcolor="#008000">City</td>
<td bgcolor="#008000">Post Code</td>
<td bgcolor="#008000">Telephone</td>
<td bgcolor="#008000">DOB</td>
</tr>
<?php
$allpatients = $_SESSION['patients'];
if ($allpatients->num_rows > 0) {
while ($row = $allpatients->fetch_assoc()) {
echo "<td>" . $row["patientid"] . "</td>";
echo "<td>" . $row["fullname_doctor"] . "</td>";
echo "<td>" . $row["firstname"] . "</td>";
echo "<td>" . $row["lastname"] . "</td>";
echo "<td>" . $row["patstreet"] . "</td>";
echo "<td>" . $row["patcity"] . "</td>";
echo "<td>" . $row["patpostcode"] . "</td>";
echo "<td>" . $row["patphone"] . "</td>";
echo "<td>" . $row["dob"] . "</td>";
echo "<td><a href='../controllers/ViewAllPatientsController.php?patientid=" . $row['patientid'] . "'>Delete</a></td>";
echo "</tr>";
}
} else {
echo "0 results.";
}
?>
UPDATED View Patient Controller
<?php
session_start();
require_once("../models/RegisterPatientModel.php");
$vapc = new RegisterPatientModel;
if (isset($_GET['patientid'])) {
$vapc->deletePatient($_GET['patientid']);
}
$allpatients = $vapc->getAllPatients();
require_once("../views/AllPatientsView.php");
try this:
public function deletePatient($patientid)
{
$sql = "DELETE
FROM {$this->target}
WHERE patientid='{$patientid}'";
echo $sql;
die();
return parent::query($sql);
}
You will be able to figure out if the SQL query is getting created correctly.
Obligatory warning: this is not a good way to make queries.
See How can I prevent SQL injection in PHP?
Update the 1st
Since deletePatient() is not firing, the issue must be earlier in the source.
Try removing
require_once("../views/AllPatientsView.php");
from DeletePatientController.php
Update the 2nd
You are not using $_POST, so remove
if (isset($_POST["Delete"])) {
And use $_GET instead to access the patientid
Update the 3rd
if (isset($_GET['patientid'])) {
$patientid->{$_GET['patientid']}();
}
$rpms->deletePatient($patientid);
Should be
if (isset($_GET['patientid'])) {
$rpms->deletePatient($_GET['patientid']);
}
Update the 4th
Since the query is not the source of the issue, remove the debug statements:
public function deletePatient($patientid)
{
$sql = "DELETE
FROM {$this->target}
WHERE patientid='{$patientid}'";
return parent::query($sql);
}
Update the 5th
Since the delete itself is not part of the issue, your next step is to debug the other parts of the code.
$allpatients = $vapc->getAllPatients();
$_SESSION['patients'] = $allpatients;
...
$allpatients = $_SESSION['patients'];
The $_SESSION shenanigans are not needed. Remove $_SESSION['patients'] = $allpatients; and $allpatients = $_SESSION['patients'];.
Then, change
if ($allpatients->num_rows > 0) {
to
var_dump($allpatients);
die();
if ($allpatients->num_rows > 0) {
and see if that leads anywhere. You should see some kind of DAO object or mysql_result (whatever parent::query() returns).
Quick Tip
You can remove the last ?> from .php files. This will save you from some weird Header bugs down the line with trailing line breaks in your outputs.

A href in PHP Foreach $result

I have a question about PHP/MYSQL.
Here you see my php page in the browser:
And here you see my phpmyadmin database:
What I want is when I click on:"Laders" I only want to see on the next page everything in the "groep":"Laders". The problem is I don't know how to do that in a loop. Here is the code:
<?php
$link = mysqli_connect('localhost', 'root', 'root', 'producten');
$query = "SELECT *
FROM producten
WHERE Merk = '" . 'Apple' . "'
ORDER BY Artikelnummer, Artikelnaam";
/*echo $query;*/
$result = mysqli_query($link, $query);
?>
<table>
<?php
echo '<table style="width:100%">
<tr style="color:yellow; background-color:black;">
<th>Apple</th>
</tr>';
foreach ($result AS $rij)
{
echo '<tr style="background:blue"><td>' . $rij['Groep'] . ' </td></tr>';
}
?> </table>
foreach ($result AS $rij)
{
echo '<tr style="background:blue"><td>'.$rij['Groep'].'</td></tr>';
}
After this, create a php file "view.php" and fetch data using $_GET['variable']

fetch PDO::FETCH_ASSOC multiple checkboxes

usually i help people with whatever they need, this time i'm asking for your help.
i'm trying to get a specific row from my database after preforming multiple checkbox select i spend 50 hours on that and i couldn't manage to do that.
each time i'm changing something in my code i get a different ERROR.
i was looking for an answer in every HTML page that exist on the INTERNET !
please show me the light..
here is a part of my form.... value means "size" of the toy
<div class=""><input type="checkbox" name="toys[]" value="6X2" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="4X3" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="8X2.5" /><label></label></div></strike>
here is the PHP code...
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
echo "<table>";
echo "<tr>
<th>ratio</th>
<th>size</th>
<th>built</th>
<th>description</th>
</tr>";
while ($row = $query->fetch(PDO::FETCH_ASSOC))
echo "<tr><td>" . $row['ratio'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['built'] .
"</td><td>" . $row['description'] .
"</td></tr>";
echo "</table>";
This is so very far from being valid:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
More like:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
$query = $db->query("SELECT * FROM `toys` WHERE SIZE = '".$each_check."'");
}
}
But should be more like:
if (isset($_POST['toys'])) {
$query = 'SELECT * FROM `toys` WHERE SIZE = ?';
$sth = $db->prepare($query);
foreach($_POST['toys'] as $each_check) {
if( ! $sth->execute(array($each_check)) ) {
die('MySQL Error: ' . var_export($sth->error_info(), TRUE);
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
// code here
}
}
}
You're assigning $db->query instead of using it as a function. Change your query line to this:
$query = $db->prepare('SELECT * FROM `toys` WHERE SIZE = :size');
$query->bindValue(':size',$each_check);
$query->execute();
Also, you're going through $_POST['toys'], but not assigning it to any value. I'm guessing you want to add all of your query and table code within the foreach.
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
// put everything else here
}
}
I want to suggest that you use MySQL's IN (...) clause in your WHERE condition to retrieve all the rows with matching 'size' in just 1 query:
SELECT * FROM toys WHERE size IN ( $chosenSizes )
To get the list of sizes, use PHP's implode function:
$chosenSizes = implode(', ', $_POST['toys']);
You can then use PDO's fetchAll to fetch all rows into a result array.
$resultRows = $sth->fetchAll();
Note: Only use this method when you are quite certain that the result arrays is not too big!
Hagay, the following should work for you:
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'my_name', 'my_pass');
if (isset($_POST['toys'])) {
$sizes = implode(', ', array_map(array($pdo, 'quote'), $_POST['toys']));
$sql = "SELECT * FROM toys WHERE size IN (" . $sizes . ")";
echo '<table>', PHP_EOL;
echo '<tr><th>ratio</th><th>size</th></tr>', PHP_EOL;
foreach( $pdo->query($sql) as $row ) {
echo '<tr><td>', $row['ratio'], '</td><td?', $row['size'], '</td></tr>', PHP_EOL;
}
echo '</table>', PHP_EOL;
}

Categories