Calling another function within a function - positioning the output - php

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;
}

Related

How to show add one row of a mysql Table?

Hi i want to show all the data of one row in a table.But i can only show 1 column of the table.
function getAllRecipes(): array {
global $connection;
$query = "SELECT * FROM recipe";
$stmt = $connection->prepare($query);
$stmt->execute();
return $stmt->fetchAll();
}
$recipe = getAllRecipes();
<?php foreach ($recipe as $recip) : ?>
<table>
<tr>
<td><?= **$recip["id"];** ?></td> <----here
</tr>
</table>
This is the result
and i want all of the line:
Do you know how to do it ?
Thanks for your help
Based on "i just want by one line show all the contain of th row" in your "answer".
$arr_values = array_values($recipe);
$html = '<table><tr><th>' . implode('</th><th>', $arr_values) . '</tr></table>';
echo $html;
If you simply only want the name of the keys(columns):
$arr_keys = array_keys($recipe);
$html = '<table><tr><th>' . implode('</th><th>', $arr_keys) . '</tr></table>';
echo $html;

Website interface on 2 screens

I'm making this website, and it's only gonna be opened on 2 screens at the same time. I'm going to generate a table with php with output from a database.
My goal is that if the table doesn't fit on the main screen it goes to the second screen.
Is this even possible?
I've tried to come up with something but couldn't figure anything out. I have tried for loops but it has to do with the style and html or maybe javascript or jquery?
If this isn't possible should I generate a second window with jquery?
Thanks in advance!
if (!empty($_POST['check_list']))
{
$idArr = $_POST['check_list'];
$id = $idArr[0];
$parameters = array(':medId'=>$id);
$sth = $pdo->prepare("SELECT naam FROM medewerkers WHERE medewerkerid = :medId");
$sth->execute($parameters);
while ($row = $sth->fetch())
{
echo "<h2>" . $row['naam'] . "</h2>";
}
?>
<table class="table">
<tr>
<th>Donderdag <br> 31-05</th>
<?php
$datum = "2017-05-31";
$parameters = array(':date'=>$datum,
':aid'=>$id);
$sth = $pdo->prepare("SELECT DISTINCT opdrachten.KRITISCHE_DATUM, opdrachten.PLANNINGS_DATUM, opdrachten.OPDRACHTID, onderzoekactiviteiten.A_UITVOERDER
FROM opdrachten
INNER JOIN onderzoekactiviteiten
ON opdrachten.OPDRACHTID=onderzoekactiviteiten.OPDRACHTID
WHERE PLANNINGS_DATUM = :date
AND A_UITVOERDER = :aid");
$sth->execute($parameters);
while ($row = $sth->fetch())
{
$cutKritDate = substr($row['KRITISCHE_DATUM'], 0, 10);
$cutPlanDate = substr($row['PLANNINGS_DATUM'], 0, 10);
echo "<td>Krit= " . $cutKritDate . "<br>";
echo "Plan= " . $cutPlanDate . "<br>";
echo "Opdracht= " . $row['OPDRACHTID'] . "</td>";
}
?>
</tr>
<tr>
<th>Vrijdag <br> 02-06</th>
</tr>
<tr>
<th>Maandag <br> 03-06</th>
</tr>
<tr>
<th>Dinsdag <br> 04-06</th>
</tr>
<tr>
<th>Woensdag <br> 05-06</th>
</tr>
</table>
<?php
}
else
{
$check_list = NULL;
$id = NULL;
echo "U bent vergeten een medewerker aan te vinken.";
}
I have a form with names, if one is selected it generates a table. this is how I generate the table. The goal is that the tables are below each other. But when it doesn't fit anymore (when you can scroll) the table needs to go to the second screen.

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.

Foreach loop and variables in php

Happy new yar. I am still new to php so I need your great help. I am designing a post page where visitors can post anything. I am almost through but when I post something to the page, the new post over ride the old one, I am certain I need to use foreach loop but my problem I can't define the $posting variable.
My bad, but I really need you guys to help me. here is my coding:
<?php
include 'connect.php';
?>
<?php
if (isset($_POST['submit'])) {
$title = $_POST['title'];
$post = $_POST['post'];
$name = $_POST['name'];
if (empty($title) or empty($post) or empty($name)) {
$message = "Please fill in all fields";
} else {
mysql_query("INSERT INTO prayer VALUES('', '" . $title . "', '" . $post . "', '" . $name . "')");
$message = "PRAYER REQUEST SUBMITTED!!!";
}
echo"$message";
}
?>
<form method="post" action="prayerpage.php">
<table width="80%">
<tr>
<td><b>Name:</b><input type="text" name="name" />
<b>Title:</b><input type="text" name="title" /></td>
</tr>
<tr>
<td><b>Prayer<br>Request:</b></td>
<td><textarea name='post' rows='10' cols='40'></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="SUMIT"/></td>
</tr>
</table>
</form>
<hr width="70%">
<?php
function postid($id) {
$array = array();
$q = mysql_query("SLECT * FROM prayer WHERE id='.$id.'");
while ($r = mysql_fetch_assoc($q)) {
$array['id'] = $r['id'];
$array['title'] = $r['title'];
$array['name'] = $r['name'];
$array['post'] = $r['post'];
}
return $array;
}
foreach ($posting as $posting) {
?>
<table width="60%">
<tr>
<td><font color="blue"><?php echo $title; ?></font></td>
</tr>
<tr>
<td><?php echo $post; ?> - <font color="blue"><?php echo $name; ?></font> </td>
</tr>
</table>
<hr noshade width="50%">
<?php
}
?>
And please i also need the code to make the post a link to its page
check your id is auto increment or not if not then make it autoincrement
then try to change this code in your page :
mysql_query("INSERT INTO prayer VALUES('', '".$title."', '".$post."', '".$name."')");
to
mysql_query("INSERT INTO prayer VALUES('".$title."', '".$post."', '".$name."')");
There are a couple problems with your code. The first is that you mysql_query when you should be using mysqli_query, same mysql_fetch_assoc, should be mysqli_fetch_assoc -- please replace all references of mysql_* with mysqli_*. The second is you are running a query inside of a function. The third problem is your query is wrong. And... you do not need a foreach in the way you are using it.
function postid($id) {
global $db;
$array = array();
$id = (int)$id; // cast as int to prevent SQL injection
$q = mysqli_query($db, "SELECT * FROM prayer WHERE id=$id");
while ($r = mysqli_fetch_assoc($q)) {
$array['id'] = $r['id'];
$array['title'] = $r['title'];
$array['name'] = $r['name'];
$array['post'] = $r['post'];
}
return $array;
}
You had a typo, it should be SELECT not SLECT. You do need to concatenate variables when you are inside of a double quoted string. I would link to the PHP documentation about it but is not super clear. Basically the following lines all result in the same output:
$amazing = "neato!";
$example1 = "This is my variable: $amazing"; // Output: This is my variable: neato!
$example2 = 'This is my variable: ' . $amazing; // Output: This is my variable: neato!
$example3 = "This is my variable: " . $amazing; // Output: This is my variable: neato!
Notice how you can put a variable inside of a string with double quotes. But you cannot do this:
$doesNotWork = 'This is my variable: $amazing'; // Output: This is my variable: $amazing
$doesNotWork = "This is my variable: '.$amazing.'"; // Output: This is my variable: '.$amazing.'
The reason you should use mysqli_query is because mysql_query is no longer supported. Inside of your function you will need to use the special keyword global to get the variable of your database connection (I set it to $db in the example but you might have it called something else).
Basically, global is a PHP keyword that will allow you to access variables that have been defined in the global scope. Read about in the documentation by clicking here
[..] within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.
Lastly.. you do not have the variable $posting defined correctly.
You can fix this by getting rid of your call to foreach, replace this line:
foreach ($posting as $posting) {
With these 2 lines:
$q = mysqli_query($db, "SELECT * FROM prayer");
while ($posting = mysqli_fetch_assoc($q)) {
Your $posting variable is undefined, when it looks like you actually just want to query the database and get all the rows from the prayer table.
This query will give you warnings in MYSQL but execute due to PK auto increment:
mysql_query("INSERT INTO prayer
VALUES('', '" . $title . "', '" . $post . "', '" . $name . "')");
Solution is that define column names in this query and if your id is PK than not use because its auto increment:
mysql_query("INSERT INTO prayer (title,post,name)
VALUES('".$title."','".$post."','".$name."')");

PHP/MySQL Table with Hyperlinks

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>

Categories