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.
Related
This question already has answers here:
How to add a delete button to a PHP form that will delete a row from a MySQL table
(5 answers)
Closed 1 year ago.
I am new to php coding.
I am adding each row delete button, but it should not working.
This is my html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
$sql = "SELECT * FROM venu ";
$result = mysql_query($sql) or die(mysql_error());
?>
<table border="2" style= " margin: 0 auto;" id="myTable">
<thead>
<tr>
<th>name</th>
<th>id</th>
<th>rollnumber</th>
<th>address</th>
<th>phonenumber</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rollnumber'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phonenumber'] . "</td>";
echo "<td><form action='delete.php' method='POST'><input type='hidden' value='".$row["address"]."'/><input type='submit' name='submit-btn' value='delete' /></form></td></tr>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>
This is my delete code:
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
error_reporting(0);
session_start();
$name = $_POST['name'];
$id = $_POST['id'];
$rollnumber = $_POST['rollnumber'];
$address = $_POST['address'];
$phonenumber = $_POST['phonenumber'];
if($name!='' and $id!='')
{
$sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
echo "<br/><br/><span>deleted successfully...!!</span>";
}
else{
echo "<p>ERROR</p>";
}
mysql_close($connection);
?>
I am trying to delete each row using a button, but it is not working.
In your html view page some change echo "<td><a href='delete.php?did=".$row['id']."'>Delete</a></td>"; like bellow:
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rollnumber'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phonenumber'] . "</td>";
echo "<td><a href='delete.php?did=".$row['id']."'>Delete</a></td>";
echo "</tr>";
}
?>
PHP delete code :
<?php
if(isset($_GET['did'])) {
$delete_id = mysql_real_escape_string($_GET['did']);
$sql = mysql_query("DELETE FROM venu WHERE id = '".$delete_id."'");
if($sql) {
echo "<br/><br/><span>deleted successfully...!!</span>";
} else {
echo "ERROR";
}
}
?>
Note : Please avoid mysql_* because mysql_* has beed removed from
PHP 7. Please use mysqli or PDO.
More details about of PDO connection http://php.net/manual/en/pdo.connections.php
And more details about of mysqli http://php.net/manual/en/mysqli.query.php
First you need to change your button like
echo "<td>Delete</td>";
this will send the ID of the row which you want to delete to the delete.php
Secondly you need to change a bit your delete.php currently is wide open for SQL injections. Try using MySQLi or PDO instead
if(isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("DELETE FROM venu WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
}
Of course if you need to add more parameters in delete query you should pass them also with the button..
EDIT: Simple example for update record
You can put second button on the table like
echo "<td>Update</td>";
Then when you click on it you will have the ID of the record which you want to update. Then in update.php
if(isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? WHERE id = ?");
$stmt->bind_param('sisi', $name, $rollnumber, $address, $id);
$stmt->execute();
$stmt->close();
}
Here ( in update.php ) you can have form which you can fill with new data and pass to variables $name, $rollnumber, $address then post it to update part.
Something to start with: PHP MySqli Basic usage (select, insert & update)
change up your query to use the dynamic value entered by the user, right now it is hard coded in there.
session_start();
require_once 'conn.php';
class myClass extends dbconn {
public function myClassFunction(){
try {
$id = $_GET['id'];
if(isset($_GET['id'])) {
$sql = "DELETE FROM tablename WHERE id = ?";
$stmt = $this->connect()->query($sql);
$stmt->bind_param('i', $id);
header("location: ../filepath/index.php");
}
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
}
This line is wrong, you need to set the WHERE clause to the data you get from the hidden input value
$sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
Should be:
$sql = mysql_query("DELETE FROM 'venu' WHERE address='"._POST['address']."'");
And in the little form you are using, change:
<input type='hidden' value='".$row["address"]."'/>
to:
<input type='hidden' name='address' value='".$row["address"]."'/>
i retrieve from the database a list with the ids and titles of some data and have for each an edit and delete link/button
after i click the delete for any of the data it works but i can t make it redirect me to the edit/delete page. here is the code for the table:
<table>
<tr>
<td>ID</td>
<td>Nume poveste</td>
<td>edit</td>
<td>delete</td>
</tr>
<?php
foreach($results_stories as $data) {
echo "<tr>";
echo "<td>" . $data->id_story . "</td>";
echo "<td>" . $data->title . "</td>";
echo "<td><a href='edit_data.php?id=" . $data->id_story . "'>edit</a></td>";
echo "<td><a href='delete_row.php?id=" . $data->id_story . "'>del</a></td>";
echo "</tr>";
}
?>
and here is the code for the delete.php:
try {
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$query = $conn->query("DELETE FROM stories WHERE id_story = '$_GET[id]'");
$stmt = $pdo->prepare($sql);
// use exec() because no results are returned
$stmt->bindParam(':id_story', $data->id_story, PDO::PARAM_INT);
if($stmt->execute()) {
echo "Record deleted successfully";
header("Location: http://localhost/auth2/edit.php");
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
any ideas?
To properly use prepared statements you should have:
$stmt = $conn->prepare("DELETE FROM stories WHERE id_story = ?");
if($stmt->execute(array($_GET['id']))) {
The ? is a placeholder for the value. The PDO driver adds it to the query and quotes it as needed.
To resolve the header issue I'd do:
header("Location: http://localhost/auth2/edit.php?response=Record+deleted+successfully");
Then on edit.php:
if(!empty($_GET['response'])) {
echo htmlspecialchars($_GET['response'], ENT_QUOTES);
}
I have a MySQL Database with 3 columns (id, question, answer). I used a code to insert with a get method into the database and it worke (sanitized), but im searching for a method in mysqli. And when i want to get from the Database the answer where the questions are matching, i get blank page.
This is my code used for inserting (it works, but i need mysqli):
require 'db.php';
function array_sanitize(&$item)
{
$item = htmlentities(strip_tags(mysql_real_escape_string($item)));
}
function InsertData($register_data)
{
array_walk($register_data, 'array_sanitize');
$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';
mysql_query("INSERT INTO `db_question` ($fields) VALUES ($data)");
}
if ($_GET['code'] == "somecode")
{
$data = array(
'question' => $_GET['q']),
'answer' => $_GET['a']
);
InsertData($data);
exit();
}
And my bigger problem is when im reading the answer by matching the question:
require 'db.php';
function sanitize($data)
{
return htmlentities(strip_tags(mysql_real_escape_string($data)));
}
if ($_GET['code'] == "somecode")
{
$question = sanitize($_GET['q']);
$result = mysql_query("SELECT `answer` FROM `db_question` WHERE `question` = '$question'");
echo "
<table id=\"box-table-b\">
<thead>
<tr>
<th scope=\"col\">Answer</th>
</tr>
</thead>";
if($row = mysql_fetch_array($result))
{
echo "<tbody>";
echo "<tr>";
echo "<td>" . $row['answer'] . "</td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
}
I think the question isn't the same with get method, because the questions and the answers too in database contains letters like: ă, î, ș, ț, â
And with get method the spaces will be replaced with %20, and when i tried getting an answer by id, i get "?" instead of those letters.
If there's someone who can help me.
Even when i've updated my code:
$question = sanitize($_GET['q']);
$result = mysql_query("SELECT `answer` FROM `tip_question` WHERE `question` = '$question'");
echo "
<table id=\"box-table-b\">
<thead>
<tr>
<th scope=\"col\">Answer</th>
</tr>
</thead>";
if($row = mysql_fetch_array($result))
{
echo "<tbody>";
echo "<tr>";
echo "<td>" . utf8_encode($row['answer']) . "</td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
i still ddint get any answer from database. Can someone tell me why?
If you get a question mark back then there is a charset problem. You could try this
And for changing your code to mysqli check this
ă, î, ș, ț are special charters.
so, you are use the utf-8 encode.
also check link: How to create an XML file with special charaters
use below code:
if($row = mysql_fetch_array($result))
{
echo "<tbody>";
echo "<tr>";
echo "<td>" . utf8_encode($row['answer']). "</td>";
echo "</tr>";
echo "</tbody>";
}
Ok so I have a script that pulls information from a database and puts it into a table. (the full script is at the bottom of this question)
Each TR is echoed with a standard ID: echo "<tr class='task' id='task1'>"; the only problem with this is each new tr or each row that is pulled from the database gets assigned the same ID task1 This is not good coding technique as well as not working with my javascript for changing the tables class name's based on the information from the database.
So my question is, is there a way to sort of "auto generate" the id name for each tr of the table? I would like to see task1, task2, task3 and so on.
Full code starts here
<?php
$con=mysqli_connect("");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM affiliate_tasks WHERE username = '$_SESSION[username]'";
if( isset($_POST['sort-selection']) && $_POST['sort-selection'] != 'all' )
{
$query .= " AND status = '". $_POST['sort-selection']."';" ;
}
$result = mysqli_query($con, $query);
echo "<table class='table table-message'>
<tr class='heading'>
<td class='cell-title'>Tasks</td>
<td class='cell-status hidden-phone hidden-tablet'>Status</td>
<td class='cell-time align-right'>Due Date</td>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr class='task' id='task1'>";
echo "<td class='cell-ttle'>" . $row['task_name'] . "</td>";
echo "<td class='cell-status hidden-phone hidden-tablet'>" . $row['status'] . "</td>";
echo "<td class='cell-time align=right'>" . $row['due_date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
If your table row has an unique id column, that will be the best fit here. You can use:
echo "<tr class='task' id='task-" . $row['id'] . "'>";
If not, and you just want a sequential number, you just use a variable like this:
$i = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr class='task' id='task-" . ++$i . "'>";
// Rest of your lines ...
}
EDIT: This is what I am trying to achieve: http://i.imgur.com/KE9xx.png
I am trying to display the results from my database in two columns. I'm a bit new to PHP so I haven't the slightest clue on how to do this. Can anybody help me with this? Thanks in advance.
Here is my current code:
include('connect.db.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM todo ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table width='415' cellpadding='0' cellspacing='0'>";
// set table headers
echo "<tr><td><img src='media/title_projectname.png' alt='Project Name' /></td>
<td><img src='media/title_status.png' alt='Status'/></td>
</tr>";
echo "<tr>
<td><div class='tpush'></div></td>
<td> </td>
</tr>"
while ($row = $result->fetch_object())
{
echo "<tr>";
echo "<td><a href='records.php?id=" . $row->id . "'>" . $row->item . "</a></td>";
echo "<td>" . $row->priority . "</td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
A good idea would be storing your data into a simple array and then display them in a 2-columned table like this:
$con = mysql_connect('$myhost', '$myusername', '$mypassword') or die('Error: ' . mysql_error());
mysql_select_db("mydatabase", $con);
mysql_query("SET NAMES 'utf8'", $con);
$q = "Your MySQL query goes here...";
$query = mysql_query($q) or die("Error: " . mysql_error());
$rows = array();
$i=0;
// Put results in an array
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
$i++;
}
//display results in a table of 2 columns
echo "<table>";
for ($j=0; $j<$i; $j=$j+2)
{
echo "<tr>";
echo "<td>".$row[$j]."</td><td>".$row[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
<table>
<tr>
<td>ProjectName</td>
<td>Status</td>
<td>ProjectName</td>
<td>Status</td>
</tr>
<?php
while($row = $result->fetch_object()) {
echo "<tr>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "</tr>";
}
?>
</table>
This is the thing on picture. With a bit CSS you can manipulate the tds.
Your function should look similar to this:
$query = "SELECT *
FROM todo
ORDER BY id";
$result = $mysqli->query($query);
while($row = $result -> fetch_array()) {
$feedback .= "<tr>\n<td>" . $row['item'] . "</td><td>" . $row['priority'] . "</td>\n</tr>";
}
return $feedback;
Then, in your HTML have the <table> already setup and where you would normally insert your <td> and <tr> put <?php echo $feedback?> (where $feedback is the assumed variable on the HTML page that retrieves the $feedback from the function). This isn't a complete fix, your code is hard to read, but by starting here, you should be able to continue on the path filling in all the extra information you need for the table, including your CSS.