Put link and session on array - php

Hello I am doing a query for search using like clause it work and I want to add a link on the result and when I click the link it will display each file. I am using session for the link but when 3 records that display on search which I'm using like example:
I search grace and it display 3 records that start with Grace
1 - Grace Napoles
2 - Grace Urgel
3 - Grace Smith
And I want to add link when i click the click it will redirect another page that display there individual record A am using the code below which have the problem display only the last record
3 - Grace Smith will display even i click the 1 or 2 i need your help if i click the 1 or 2 or 3 it display each records thanks
<?php
session_start();
include'database.php';
$ssmain = $_SESSION['sessionsmain'];
$conn = mysqli_connect($server, $dbusername, $dbpassword, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM employee where E_ID = '$ssmain' || LastName like '%$ssmain' || FirstName like '%$ssmain'";
$no=0;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) { ?>
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Last Name</th>
<th>First Name</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)) {
$no++;
?>
<tr>
<td><?php $_SESSION['ttid'] = $row['E_ID']; echo"{$row['E_ID']}"; ?></td>
<td><?php echo"{$row['FirstName']}"; ?></td>
<td><?php echo"{$row['LastName']}"; ?></td>
</tr>
<?php
}
}
else
{
header('location: error404.php');
}
?>
</tbody>
</table>

You're only ever going to get the last result (ie: 3 - Grace Smith) because you're overwriting the $_SESSION['ttid'] value in each iteration.
You should append a GET query string to your link and adjust your code. For example;
<td><a href="employeerecord.php?id=<?php echo $row['E_ID']; ?>">
<?php echo $row['E_ID']; ?> - <?php echo implode(" ", array($row['FirstName'], $row['LastName'])); ?>
</a>
</td>
Now in your query, look for the query string.
if( isset($_GET['id']) AND ctype_digit($_GET['id']) ) {
//Query for the specific E_ID
$sql = "SELECT `FirstName`,`LastName` FROM employee where E_ID = ?";
$objGet = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($objGet, 'i', $_GET['id']);
mysqli_stmt_execute($objGet);
mysqli_stmt_bind_result($objGet, $strFirstName, $strLastName);
echo 'Viewing: '. $strFirstName .' '. $strLastName;
} else {
//Query all records to show to the user
}

Related

Print calculated Value of variable before its been calculated

This is a tricky question to search, hence my post here. I have a a header that displays the sum of all the values in a column of a table that is printed below it. However the table is generated from a MYSQL table and the sum of the column values is calculated as it is generated. So somehow I have to have a variable printed but only after the table is generated and I am not sure how to pass the variables back up to the print statement so it doesn't always print out a 0
I feel like the solution is that the sum should call a script (Javascipt) that generates and prints the table returning the sum of columns to then be printed. But I am not sure how I would do this
echo "
<h3>EPL</h3>
<h5>Total Score: $total</h5>
<table class='table table-bordered'>
<tr>
<th>#</th>
<th>Name</th>
<th>Score</th>
</tr>
<tbody class='row_position'>"?>
<?php
require('db_config.php');
$tablename = $_SESSION['username'] . "_epl";
$_SESSION['tablename'] = $tablename;
$sql = "SELECT * FROM $tablename ORDER BY position_order";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
$con = mysqli_connect('localhost', 'root', 'root', 'predictions');
$sql1 = "SELECT * FROM `predictions`.`".$tablename."` WHERE (CONVERT(`title` USING utf8) LIKE '%".$user['title']."%')";
$sql2 = "SELECT * FROM `predictions`.`epl` WHERE (CONVERT(`title` USING utf8) LIKE '%".$user['title']."%')";
$result = mysqli_query($con, $sql1);
$row = $result->fetch_assoc();
$position1 = $row['position_order'];
$result->close();
$result = mysqli_query($con, $sql2);
$row = $result->fetch_assoc();
$position2 = $row['position_order'];
$total += abs($position1-$position2);
?>
<tr id="<?php echo $user['id'] ?>">
<td><?php echo $user['position_order'] ?></td>
<td><?php echo $user['title'] ?></td>
<td><?php echo abs($position1-$position2); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
To explain the table further, each user has their own table with the same format username_league, so I use some php code to grab the table. Additionally I have a base case table in this case 'epl' in which I compare the tables and calculate the scores based on the absolute difference in the column 'position_order'.
You should always aim for separation of your code and presentation. And beyond that, your database code is extremely inefficient. You're re-creating an entire database object for every instance of your original query.
Just put your PHP code before the HTML, or better yet in a separate file.
<?php
$total = 0;
require('db_config.php');
$tablename = $_SESSION['username'] . "_epl";
$_SESSION['tablename'] = $tablename;
$sql = "SELECT id, position_order, title FROM `$tablename` ORDER BY position_order";
$users_result = $mysqli->query($sql);
while($user = $users_result->fetch_assoc()) {
$users[] = $user;
}
foreach ($users as $user) {
$sql1 = "
SELECT position_order FROM `$tablename` WHERE CONVERT(`title` USING utf8) LIKE '%$user[title]%' LIMIT 1
UNION
SELECT position_order FROM `epl` WHERE CONVERT(`title` USING utf8) LIKE '%$user[title]%' LIMIT 1
";
$result = $mysqli->query($sql1);
$row = $result->fetch_assoc();
$position1 = $row['position_order'];
$user["position1"] = $position1;
$row = $result->fetch_assoc();
$position2 = $row['position_order'];
$user["position2"] = $position2;
$total += abs($position1 - $position2);
}
?>
There you are; using a single database object, one third fewer queries, all your values in an array. They're ready to use later in the file, or in your separate HTML view:
<h3>EPL</h3>
<h5>Total Score: <?=$total?></h5>
<table class='table table-bordered'>
<tr>
<th>#</th>
<th>Name</th>
<th>Score</th>
</tr>
<tbody class='row_position'>
<?php foreach($users as $user):?>
<tr id="<?=$user['id'] ?>">
<td><?=$user['position_order'] ?></td>
<td><?=$user['title'] ?></td>
<td><?=abs($user["position1"]-$user["position2"]); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
I don't know enough about the structure here, but I'd be very surprised if you couldn't make this a single database query.
Output buffering is your friend! Simply call ob_start before outputting the table i.e.
ob_start();
echo "
<table class='table table-bordered'>
<tr>
<th>#</th>
<th>Name</th>
<th>Score</th>
</tr>
<tbody class='row_position'>"?>
...
then once you have done generating the table, you can collect the output of the table's content using ob_get_clean, output the header and then the table content:
...
$table = ob_get_clean();
echo "<h3>EPL</h3>
<h5>Total Score: $total</h5>";
echo $table;

Show Foriegn key data (names etc) instead of just the forign key in HTML table

I am creating a medical application for a Drs Practice as part of an assignment.
I have a table which is displaying the information with to the visits table which is linked in the image here.
Currently the table is displaying the Id values of the foriegn keys like this
How do i display the text value for example rather than patient name being 9, i would like to display the actual name and so on for the rest of the table.
so it will display as
patient name | doctor | condition | medication prescribed | Date
Andrew Terry | Dr Iqbal | Depression | Fluoxetine | 20th April 2018
I am also when i have worked this out, wanting to add a search where i can search for patients with a certain condition within a certain time period.
The current code is as follows
<?php // Include config file
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/config.php");
?>
<?php // Include header File
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/header.php");
?>
<?php
if (!$db) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = "SELECT * FROM visit JOIN doctor
ON visit.doctor_id = doctor.doctor_id
JOIN patient
ON visit.patient_id = patient.patient_id
WHERE patient.patient_id BETWEEN 1 AND 9
ORDER BY date DESC";
$query = mysqli_query($db, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($db));
}
?>
<body>
<?php // Navigation File
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/nav.php");?>
<div class="container"><br><br>
<?php include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/logo.html"); ?>
<h2>APPOINTMENTS</h2>
<p>Most Recent Appointments:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Patient Name</th>
<th>Doctor</th>
<th>Condition</th>
<th>Medication Prescribed</th>
<th>Date</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td>'.$row['patient_id'].'</td>
<td>'.$row['doctor_id'].'</td>
<td>'.$row['con_id'].'</td>
<td>'.$row['drugs_id'].'</td>
<td>'.$row['date'].'</td>
<td>Delete</td>
</tr>';
$no++;
}?>
</tbody>
</table>
New Appointment
Admin Area
</div>
</body>
</html>
I have amended code following #kamal assistance earlier.. but now i am getting undefined notice errors.
Code is as follows
<?php // Include config file
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/config.php");
?>
<?php // Include header File
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/header.php");
?>
<?php
if (!$db) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = "$sql = "SELECT patient.fName AS pfname, patient.sName AS psname, doctor.sName AS doc, conditions.con_name AS con, drugs.medication AS meds, visit.visitdate FROM visit
JOIN doctor ON visit.doctor_id = doctor.doctor_id
JOIN patient ON visit.patient_id = patient.patient_id
LEFT JOIN conditions ON visit.con_id = conditions.con_id
LEFT JOIN drugs ON visit.drugs_id = drugs.med_id
WHERE patient.patient_id BETWEEN 1 AND 100
ORDER BY date DESC";
$query = mysqli_query($db, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($db));
}
?>
<body>
<?php // Navigation File
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/nav.php");?>
<div class="container"><br><br>
<?php include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/logo.html"); ?>
<h2>APPOINTMENTS</h2>
<p>Most Recent Appointments:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Patient Name</th>
<th>Doctor</th>
<th>Condition</th>
<th>Medication Prescribed</th>
<th>Date</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td>'.$row['pfName'].'</td>
<td>'."Dr ".$row['doc'].'</td>
<td>'.$row['con'].'</td>
<td>'.$row['meds'].'</td>
<td>'.$row['date'].'</td>
<td>Delete</td>
</tr>';
$no++;
}?>
</tbody>
</table>
New Appointment
Admin Area
</div>
</body>
</html>
I am now getting the following. enter image description here
I assume few of the tables in the following answer.
Here how your query should look like as #Barmar mentioned in comment:
SELECT fName,date,visit_id,patient.patient_name, doctor.name AS doctor_name, condition.name AS condition_name, drugs.name AS drugs_name FROM visit JOIN doctor
ON visit.doctor_id = doctor.doctor_id
JOIN patient
ON visit.patient_id = patient.patient_id
LEFT JOIN condition ON visit.con_id = condition.id
LEFT JOIN drugs ON visit.drugs_id = drugs.id
WHERE patient.patient_id BETWEEN 1 AND 9
ORDER BY date DESC
Then within your PHP code, you should change the column names in while loop as below:
echo '<tr>
<td>'.$row['patient_name'].'</td>
<td>'.$row['doctor_name'].'</td>
<td>'.$row['condition_name'].'</td>
<td>'.$row['drugs_name'].'</td>
<td>'.$row['date'].'</td>
<td>Delete</td>
</tr>';
I hope this will help you to move forward.

Addition in php from more than one row in mysql

Hello I am trying to make a little game, where I need to add some point given for how a drink looks and taste.
There will be 7 people giving points, so in php i need to create a table for each date and only show 1 name for each of the players, but I need the points to be added for every row with the same name:
Here is what I have so far.
<?php
$pdo = Logbase::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT DISTINCT start FROM grade';
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);?>
<?php while ($r = $q->fetch()): ?>
<table class="blueTable" align="center">
<thead>
<tr>
<th> <?php echo $r['start'] ?></th>
<th></th>
</tr>
</thead>
<?php endwhile; ?>
<tbody>
<?php
$pdo = Logbase::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * FROM grade group by start, name';
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
?>
<?php while ($r = $q->fetch()): ?>
<tr>
<td> <?php echo $r['name'] ?></td>
<td> <?php echo $r['drinks_fla'] + $r['drinks_view'] + $r['food'] +
$r['sam'] ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
In my result I can see 1 name for each player, but only 1 rows has been added (the first), so I quess I need a loop or something in my mysql?
Dennis --------10 point
Michael--------6 point
I want to see
Dennis 24 point
Michale 12 points
id---start--- name-----drinks_fla---drinks_view
1---31.07-2017---dennis---5---5
1---31.07-2017---dennis---4---3
1---31.07-2017---dennis---5---2
2---31.07-2017---Michale---5---1
2---31.07-2017---Michael---2---4
$sql = 'SELECT * FROM grade group by start, name';
You have grouped your Results from MySQL, so only one Row will be called for the Properties of the Group.
Try "sum()" to get sum of the selected Columns you want:
$sql = 'SELECT name as name,sum(sum(drinks_fla),sum(drinks_view)) as sum FROM grade group by start, name';
MySQL will call all Rows, ordered by the first Property. All Rows with the same first Property are sorted with the second one.
Example:
id---start--- name-----drinks_fla---drinks_view
1---31.07-2017---dennis---5---5
1---31.07-2017---dennis---4---3
1---31.07-2017---dennis---5---2
2---31.07-2017---Michale---5---1
2---31.07-2017---Michael---2---4
Result:
name----sum
dennis----24
Michale----6
Michael----6

How to get data from tables linked to a single user

First of all thank you for help me in advance.
I am looking to make a system were i am using 1 mysql DB and 2 tables or more and connect the tables to a user in a session. So lets suppose that the user logs in in a location, after login he can view from another table the data relative to this user, like a support ticket system (very simple one).
So i created a login system with sessions and then i want to display from another table only the data from that single user but when i do this i get all the data from the table, other users can see other users submissions and i wanna stop that and make it single user, single data display from that user only.
So here is the codes i am using:
<?php
// Validate Client Details
session_start();
if(!isset($_SESSION["user_username"]))
{
header("location:index.php?action=login");
}
?>
Then i got this code to display the records:
<?php
$connect = mysqli_connect("localhost", "root", "root", "helpdesk");
$sql = "SELECT * FROM users INNER JOIN tickets ON users.user_id = tickets.ticket_id";
$result = mysqli_query($connect, $sql);
?>
It works great but displays all and not just the single user details.
The Output i am using:
<table class="table table-striped">
<tr>
<th>Ticket ID</th>
<th>Client Username</th>
<th>Ticket Issue</th>
<th>Message</th>
<th>Priority</th>
</tr>
<?php
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["ticket_id"]; ?></td>
<td><?php echo $row["user_username"];?></td>
<td><?php echo $row["ticket_issue"]; ?></td>
<td><?php echo $row["ticket_message"]; ?></td>
<td><?php echo $row["ticket_priority"]; ?></td>
</tr>
<?php
}
}
?>
</table>
I hope someone can help me on this, my best regards and thanks in advance.
You missed where condition
$name=$_SESSION['user_username']
$sql = "SELECT * FROM users INNER JOIN tickets ON users.user_id = tickets.ticket_id where user_username='$name'";

Using a SELECT Query to retrieve data from a database using a multidimensional array

I want to use a SELECT Query to retrieve data from a database, that displays the list of categories and the number of DVDs in each category using a multidimensional array.
Table Name: dvds_table
dv_id dv_caid dv_name
1 4 Matrix Reloaded
2 2 Johnny English
3 4 The Recruit
4 4 Minority Report
5 3 Two Weeks Notice
6 2 Bend It Like Beckham
Table Name: categories_table
ca_id ca_name
2 Comedy
4 Action
1 Drama
3 Romance
5 TV
This is what I've come up with so far, excuse my basic knowledge:
<?php
$link = mysqli_connect("localhost", "root", "", "dvddb");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$categories=getNumDvdsInCategories();
function getNumDvdsInCategories() {
$this->db->select('*');
$this->db->from('categories_table');
$this->db->order_by('ca_name', 'DESC');
$query = $this->db->get();
return $query->result();
}
$this->load->model("model");
$data['results'] = $this->model->list_categories();
$this->load->view('categories_list_view', $data);
?>
<html>
<body>
<table border=1>
<tr>
<td>Category ID</td>
<td>Category Name</td>
<td>Num. DVDs</td>
</tr>
<?php foreach ($categories as $category) { ?>
<tr>
<td><?php echo $category['ca_id']; ?></td>
<td><?php echo $category['ca_name']; ?></td>
<td><?php echo $category['num']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
I Belief that this code will give the results you are looking for. Please Google for information about mysql COUNT which counts the number of rows in a selection, and LEFT JOIN which joins rows from two tables together in a selection.
I've tried to keep as much from the original code in tact. Only the query part has changed. I can advice you to read-up about the SQL.
You can play around with the AS aliases or removed them. Please note they will affect the $catetory key names. And maybe you want to remove the ID from the selection. But that's up to you.!
<?php
// * These where the create queries that I have used to make a similar table as you.
// create table dvds_table ( dv_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, dv_caid INT NOT NULL, FOREIGN KEY (dv_caid) references categories_table(ca_id), dv_name varchar(20));
// create table categories_table (ca_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, ca_name varchar(20));
$link = mysqli_connect('localhost', 'root', '', 'dvddb');
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// * use $sql example below if you dont want the ID (Then also remove $category['ID'] in your HTML).
// * Also you can remove the AS aliases or rename them as you see fit (then also change the $category key names).
// $sql = 'SELECT categories_table.ca_name AS Category, COUNT(dvds_table.dv_caid) AS Amount FROM categories_table LEFT JOIN dvds_table ON dvds_table.dv_caid = categories_table.ca_id GROUP BY categories_table.ca_name ORDER BY categories_table.ca_name DESC;';
$sql = 'SELECT categories_table.ca_id AS ID,
categories_table.ca_name AS Category,
COUNT(dvds_table.dv_caid) AS Amount
FROM categories_table
LEFT JOIN dvds_table
ON dvds_table.dv_caid = categories_table.ca_id
GROUP BY categories_table.ca_id
ORDER BY categories_table.ca_name DESC;';
$result = mysqli_query($link, $sql);
?>
<html>
<body>
<table border=1>
<tr>
<td>Category ID</td>
<td>Category Name</td>
<td>Num. DVDs</td>
</tr>
<?php foreach ($result as $category) { ?>
<tr>
<td><?php echo $category['ID']; ?></td>
<td><?php echo $category['Category']; ?></td>
<td><?php echo $category['Amount']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
<?php
mysqli_free_result($result);
mysqli_close($link);
?>

Categories