I want to create a table which generates data from the database and I need to have update and delete function for each row of data in the table. But i failed to do both update and delete because i put both function in one controller
This is my view file which include the controller to show the data.
<table class="table table-hover">
<tr class="table-active">
<td>Booth ID</td>
<td>Booth Location</td>
<td>Participant ID </td>
<td></td>
<td></td>
</tr>
<tr>
<?php include 'BoothViewController.php'; ?>
</tr>
</table>
This is my controller to display the data in rows. Each row will have update and delete function. The update function will bring the user to another page while delete function is merely remove that row of data.
<?php
require 'boothmodel.php';
$result = viewbooth();
if($result){
while($array = mysqli_fetch_array($result)){
echo "<td>".$array["BoothID"]."</td>";
echo "<td>".$array["Boothlocation"]."</td>";
echo "<td>".$array["ParticipantID"]."</td>";
echo "<td><a href='BoothFormUpdate.php?bid=".$array['BoothID'].
"&blocation=".$array['Boothlocation']."&pid=".$array['ParticipantID']."'>Update</a></td>";
echo "<td><a href='BoothViewController.php?bid=".$array['BoothID'].
"&blocation=".$array['Boothlocation']."&pid=".$array['ParticipantID']."'>Delete</a></td>";
}
return;
}
if(isset($_GET['bid'])){
$selectedbid = $_GET['bid'];
$result = deletebooth($selectedbid);
if($result){
echo "<script language = 'javascript'>";
echo "alert('Booth deleted!');";
echo "window.location.href = 'BoothView.php';";
echo "</script>";
}
}?>
this is my model.
<?php
require 'connection.php';
mysqli_select_db($conn, "ims");
function viewbooth(){
global $conn;
$query = "SELECT * FROM booth";
$result = mysqli_query($conn, $query);
return $result;
}
function updatebooth($bid, $newbloc){
global $conn;
$update = "UPDATE booth
SET Boothlocation='".$newbloc.
"'WHERE BoothID='".$bid."'";
$result = mysqli_query($conn, $update);
return $result;
}
function deletebooth($selectedbid){
global $conn;
$delete = "DELETE FROM booth WHERE BoothID=".$selectedbid;
$result = mysqli_query($conn, $delete);
return $result;
}?>
I know i can simply do the delete function in another controller but im trying to put all in one controller.
You need to create a basic routing mechanism, e.g.
if(isset($_GET['bid'], $_GET['action']))
{
$selectedbid = $_GET['bid'];
$action = $_GET['action'];
switch ($action)
{
case 'delete':
$result = deletebooth($selectedbid);
if($result){
echo "<script language = 'javascript'>";
echo "alert('Booth deleted!');";
echo "window.location.href = 'BoothView.php';";
echo "</script>";
}
break;
case 'update':
// do the updating
break;
}
}
then you can add update and delete links to your items:
Update item
Delete item
Your code hardly resembles the MVC pattern and has many issues. However, the routing idea should work.
Related
I've spent a lot of time messing around with PHP and MYSQL and I've finally managed to create a "to do list" sort of thing that allows the user to submit a "to do" task and for it to add it to a database and then show it. I've followed many tutorials as I've tried to teach myself PHP blah blah. But for some reason i cannot get the delete script working.
echo "<td><a href='delete.php?=Delete" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
Above is the code for the delete button
Here is the delete script apologies for the many commented out lines I've tried many 'solutions'.
$ID = $_GET['task_id'];
//$delete_query = "DELETE FROM Tasks WHERE ID = $ID" ;
$sql = "DELETE FROM Tasks WHERE task_id = $ID;";
echo $row['task_id'];
// $delete_query = "DELETE FROM Tasks WHERE task_id = ['task_id'] ";
/* if(isset($GET['task_id'])){
$delete = $_GET['task_id'];
mysqli_query($connect, "DELETE FROM Tasks WHERE task_id = '$delete'");
} */
echo("Succesfully deleted");
mysqli_close($link);
The script runs and it says "successfully deleted" but the entry still shows. In the F12 Menu/Network tab I get this
error
And when I click "view source" it shows the ID of the row. I can't seem to figure out what is wrong.
I am try to delete data using php pdo. and data can deleted successfully so you can try this code.
I have created 2 file. first req.php and second delete.php.
Here req.php file can fetch data and delete.php file can delete this data from send req.php file id.
req.php
<?php
require "connection.php";
//This is a fetch data from database
$sql = "SELECT * FROM test";
$select = $conn->prepare($sql);
$select->execute();
?>
<html>
<head>
<title>Data</title>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
while($data = $select->fetch())
{
?>
<tr>
<td><?php echo $data['id']; ?></td>
<td><?php echo $data['student_name']; ?></td>
<td><?php echo $data['email_address']; ?></td>
<td><button onclick="return conformation();">Delete</button></td> <!-- This is a delete data button --->
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
<script>
//This is a conformation function if it will return true then data can delete otherwise data cannot deleted.
function conformation() {
let conform = confirm("Can you delete this data ?");
if (conform == true) {
return true;
} else {
return false;
}
}
</script>
delete.php
<?php
require "connection.php";
if(isset($_GET['id']))
{
$sql = "DELETE FROM test WHERE id = ?";
$deleteData = $conn->prepare($sql);
if ($deleteData->execute([$_GET['id']]))
{
header('location: http://local.test/req.php');
}
}
?>
The first issue is trying to get task_id from REQUEST params while you sending "Delete" key.
The second is you passed the task_id to db as a string, while I think it's an Integer type in the database.
So you have to do that:
echo "<td><a href='delete.php?task_id=" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
$task_id = mysqli_real_escape_string($connect, $_GET['task_id']);
if (!empty($task_id)) {
$delete_query = mysqli_query($connect, 'DELETE FROM Tasks WHERE task_id = '.$task_id);
if ($delete_query) {
echo 'deleted successfully';
} else {
echo("Error: " . mysqli_error($connect));
}
} else {
echo 'task_id is empty !';
}
You can solve this or debug it by doing the following.
parse the right URL parameter
echo "<td><a href='delete.php?task_id=" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
this will send a task_id value to the delete page.
checking and logging the response of my SQL in delete.php
if(isset($_REQUEST['task_id'])){
//escape to avoid SQL injection
$delete = mysqli_real_escape_string($connect, $_REQUEST['task_id']);
$process = mysqli_query($connect, "DELETE FROM Tasks WHERE task_id = '".$delete."'");
if($process){
echo("Succesfully deleted");
}else{
echo("Error description: " . mysqli_error($connect));
}
}else{
echo("no id supplied");
}
in your question, you also had this: $GET['task_id'], which I believe was null.
I was trying to delete a record on my Database. So basically I created a table that contains all of my records. Now what I need to do is when I click on the "DELETE" link it would delete the record selected row.
Here's what it looks like:
So basically I have 3 pages here.
1. page.php
2. add.php
3. delete.php
Here's my page.php file:
<table border="1">
<thead>
<th>email</th>
<th>date</th>
<th>delete</th>
</thead>
<tbody>
<tr>
<?php
foreach($emails as $mail){ ?>
<td><?php echo $mail['email']; ?></td>
<td><?php echo $mail['date']; ?></td>
<td><?php echo "<a href='delete.php?id=". $mail['id']. "'>DELETE</a>"; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Here's my add.php file:
<?php
require("new-connection.php");
session_start();
$email = $_POST['email'];
if(empty($_POST['email']) AND (filter_var($email, FILTER_VALIDATE_EMAIL) === false))
{
$_SESSION['message'] = "email cannot be blank";
}else{
$query = "INSERT INTO email_tbl (email, date)
VALUES('$email', NOW())";
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "New RECORD has been added correctly!";
}
else
{
$_SESSION['message'] .= "Failed to add new Interest";
}
}
header('Location: email.php');
?>
Here's my delete.php file so far:
<?php
require("new-connection.php");
session_start();
$query = "DELETE FROM email_tbl
WHERE id={id} LIMIT 1";
$deleteEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "RECORD has been DELETED correctly!";
}
else
{
$_SESSION['message'] .= "Failed to DELETE RECORD";
}
header('Location: email.php');
?>
So now when I click the delete link it must delete the button real time. Any idea?
Modify your delete.php to retrieve the url parameter:
<?php
require("new-connection.php");
session_start();
$id = $_GET['id'];
$query = "DELETE FROM email_tbl
WHERE id='$id' LIMIT 1";
$deleteEmail = run_mysql_query($query);
if($deleteEmail)
{
$_SESSION['message'] .= "RECORD has been DELETED correctly!";
}
else
{
$_SESSION['message'] .= "Failed to DELETE RECORD";
}
header('Location: email.php');
?>
As for your add.php, you are using this:
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
You should change it to this:
$insertEmail = run_mysql_query($query);
if($insertEmail)
What you are doing right now is you are executing the query twice by calling run_mysql_query twice. This should fix it
Sense when what run_mysql_query a function in php?
http://php.net/manual-lookup.php?pattern=run_mysql_query&scope=quickref
Update the delete.php file:
$id = $_GET['id'];
$query = "DELETE FROM email_tbl WHERE id='$id' LIMIT 1";
and also check the section below:
You are running the query twice. so it is obvious it will add the same record twice.
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "New RECORD has been added correctly!";
}
Modify you code to use the run_mysql_query once only.
$query = "DELETE FROM email_tbl WHERE id=".$_GET['id']." LIMIT 1";
system/article.php
<?php
$sql = "SELECT articleTitle, articleSummary, articleContent FROM articles";
$result = $dbconnect->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["articleTitle"];
echo $row["articleSummary"];
echo $row["articleContent"];
}
} else {
echo "0 results";
}
include 'template/homepage.php';
retrieves articles from the article table.
I have included the homepage.php which is supposed to act as a template.
template/homepage.php
<?php include 'template/common/header.php'; ?>
<h1>Article Title here</h1>
<p>articleSummary</p>
<?php include 'template/common/footer.php'; ?>
How do I now pass the retrieved data to the homepage.php to display it on the browser ?
Edit
smarber pointed me to
In the first file:
global $variable;
$variable = "apple";
include('second.php');
In the second file:
echo $variable;
which works. But how do I implement the same with my problem up top?
You may do that via GET, Session or Post; But why don't you simply and efficiently define a function and pass those variables to it, just for example:
function displayArticle($title, $summary, $content) {
displayHeader(); // maybe some concepts you've used in template/common/header.php
echo "<h1>$title</h1><p>$summary</p><div>$content</div>";
displayFooter(); // again, what you've provided in footer.php
}
Well then, you may do the following:
change the template/homepage.php file to:
<?php
include 'template/common/header.php';
echo "<h1>$articleName</h1>";
echo "<p>$articleSummary</p>";
include 'template/common/footer.php';
?>
and change the system/article.php to:
<?php
global $articleName;
global $articleSummary;
global $articleContents;
$sql = "SELECT articleTitle, articleSummary, articleContent FROM articles";
$result = $dbconnect->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$articleName = $row["articleTitle"];
$articleSummary = $row["articleSummary"];
$articleContents = $row["articleContent"];
include 'template/homepage.php';
}
} else {
echo "0 results";
}
However, It's so better to create a cleaner and more reusable code using some facilities you have in the programming language, like using functions and classes :)
I am creating a search function that will allow a user to search for a house in my database by postcode initially. The function can be seen below, when the function is executed and finds a true statement I get no errors however when I execute the search and I get a no fields been returned I am left with this error:
No Records Found
Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/undergradpad/search.php on line 26
I want it to display No Records Found however I don't know how I should correct the above error.
search.php:
<table width="500" border="1" cellpadding="5">
<tr>
<th width="16" scope="row">id</th>
<td width="95">bedrooms</td>
<td width="140">description</td>
<td width="104">roadname</td>
<td width="71">postcode</td>
</tr>
<?php
require("classes/class.House.inc");
$obj = new House();
$obj->search($_POST['term']);
foreach($obj->data as $val){
extract($val);
?>
<tr>
<td scope="row"><?php echo $id; ?></td>
<td><?php echo $bedrooms; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $roadname; ?></td>
<td><?php echo $postcode; ?></td>
</tr>
<?php
}
?>
</table>
classes/class.House.inc:
<?php
include("connect/class.Database.inc");
class House extends Database {
public function read(){
$query = "SELECT * FROM houses";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
}
}
public function search ($term){
$query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
} else{
echo 'No Records Found';
}
}
}
?>
in this variable ($obj->data) you just get null data.
First check if not empty and than use foreach and don't have error if yout method don't return null data
just check if (!empty($obj->data)
{
foreach code
}
$obj is a House object. It has no $data property, even if you use it. The search method sets this property, but only if records are found. If no records are found, the method echoes a value.
I would change it like this: Instead of echoing an error, make the method return false:
public function search ($term){
$query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$data = false;
$num_result = $result->num_rows;
while($row =$result->fetch_assoc()){
$data[]=$row;
}
return $data;
}
Now, the function return an array of false if there is no data. You can now use it like this:
$obj = new House();
if ($data = $obj->search($_POST['term']))
{
foreach($obj->data as $val){
extract($val);
}
}
The changes I made:
- No longer set data as a property, since you also return it. You can still do that, if you like, but I think it's confusing to do both.
- Return false if there's no data.
- Change the variable rows to row, since it only contains one row.
if(is_array($obj->data)){
foreach code
}
else{
no record
}
Hello and Good Morning,
I am still learning PHP and for some reason my script will not post any data in my foreach loop. Any Idea why? The emailRow Echos out fine but I am going to remove My code is below:
<?php
include 'includes/header.php';
$accountUser = array();
$upgradeEmail = $_GET['currEmail'];
$emailQuery = "SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0";
<?php echo $emailRow['fbID']; ?>
<?php echo $emailRow['firstName']; ?>
<?php echo $emailRow['lastName']; ?>
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
?>
<table>
<?php foreach($accountUser as $emailData) { ?>
<tr><td> <?php emailData['fbID']; ?> </td><td><?php emailData['firstName']; ?></td><td><?php emailData['lastName']; ?></td></tr>
<?php } ?>
</table>
You have constructed your SQL query in $emailQuery, but never executed it. Call mysql_query(), and pass its result resource to mysql_fetch_assoc().
$emailQuery = "SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0";
$result = mysql_query($emailQuery);
if ($result)
{
while($emailRow = mysql_fetch_assoc($result, $conn))
{
$accountUser[]=$emailRow;
}
}
else // your query failed
{
// handle the failure
}
Please also be sure to protect your database from SQL injection by calling mysql_real_escape_string() on $upgradeEmail since you're receiving it from $_GET.
$upgradeEmail = mysql_real_escape_string($_GET['currEmail']);
You don't actually echo anything.
as well as not running the query.
and there are some other methods to do things, much cleaner than usual uglyPHP.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
$email = mysql_real_escape_string($_GET['currEmail']);
$data = sqlArr("SELECT * FROM users WHERE emailOne='$email' AND authLevel=0");
include 'template.php';
a template
<? include 'includes/header.php' ?>
<table>
<? foreach($data as $row) { ?>
<tr>
<td><?=$row['fbID']?></td>
<td><?=$row['firstName']?></td>
<td><?=$row['lastName']?></td>
</tr>
<? } ?>
</table>
YOU HAVE A SYNTAX ERROR. You can't open a new php tag within an existing php tag. You have to close the already open tag first.
As far as getting the query to work,
First you have to fetch data before printing it or echoing it...
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
then you may write statements..
echo $emailRow['fbID']; etc. code.
Secondly you have not fired a query, just written the query statement. Use mysql_query to fire it.
Your code would be something like this..
<?php include 'includes/header.php';
$accountUser = array();
$upgradeEmail = $_GET['currEmail'];
$emailQuery = mysql_query("SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0") or die (mysql_error());
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
echo $emailRow['fbID'];
echo $emailRow['firstName'];
echo $emailRow['lastName'];
print '<table>';
foreach($accountUser as $emailData) {
print '<tr><td>'$.emailData['fbID'].'</td><td>'.$emailData['firstName'].'</td><td>'.$emailData['lastName'].'</td></tr>';
}
print '</table';
?>
Feel free to use this code, modifying it to fit your needs.