PHP can't delete MS Access table row - php

I have a simple MS Access database to insert a single-column row. Here is the page:
<!DOCTYPE html>
<html>
<head>
<title>Bell Sistemas - Site de Atividades Teste em PHP</title>
</head>
<?php
include "session.php";
include "header.php";
include "connectSQL.php";
echo "<br><form action='' method='POST'><table align='center'>
<tr><th align='left'>Atividade: <br><input type='text' name='activity'></th></tr>
<tr><th align='left'><input type='submit' name='Cadastrar2' value='Cadastrar'></th></tr></table></form>";
$activity = $_POST['activity'];
if(isset($_POST['Cadastrar2'])) {
if($activity==''){
echo "O campo está vazio.";
}
else{
$sql = "Insert Into Atividades(Atividade) VALUES('$activity')";
$result = $db->query($sql);
echo "Atividade inserida.";
//header("Location: ./menu.php"); /* Redirect browser */
//exit();
}}
?>
<?php
$sql = "SELECT CdAtividade, Atividade FROM Atividades ORDER BY Atividade";
$result = $db->query($sql);
echo "\n<hr>";
echo "<table align='center'><tr><th align='left'>Atividade</th></tr>";
while ($row = $result->fetch()) {
echo "<tr><td align='left' width='250'>".$row['Atividade']."</td><td width='75'>Editar</td><td><a href='delete_atividade.php?CdAtividade=".$row['CdAtividade']."'>Excluir</a></td></tr>";
}
echo "</table>";
?>
<?php
include "footer.php";
include "tableConfig.php";
?>
</body>
</html>
And I configured the delete_atividade.php like this:
<?php
// connect to the database
include "session.php";
include "connectSQL.php";
// get id value
$cdatividade = $row['CdAtividade'];
// delete the entry
$sql = "DELETE FROM Atividades WHERE CdAtividade='$cdatividade'";
$result = $db->query($sql);
// redirect back to the view page
if($result){
header("Location: atividades.php");
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
header("Location: atividades.php");
}
?>
However, when I click to delete a row, it does not delete it. Have I forgot something?
I appreciate anyone who can help me.

I'm not sure that this will be the final solution, but for starters:
$cdatividade = $row['CdAtividade'];
The $row variable doesn't exist in this file. You're passing on the query string, so it should be:
$cdatividade = $_GET['CdAtividade'];
Also, generally speaking for numeric values it's not necessary to surround in quotes, so your current delete statement:
$sql = "DELETE FROM Atividades WHERE CdAtividade='$cdatividade'";
...could be rewritten as:
$sql = "DELETE FROM Atividades WHERE CdAtividade=$cdatividade";
Finally, it's worth noting as Marc B did that your current query is susceptible to SQL Injection attacks like the following:
http://yourdomain.com/delete_atividade.php?CdAtividade=0;DROP TABLE Atividade;
Will result in your SQL looking like this:
DELETE FROM Atividades WHERE CdAtividade=0;DROP TABLE Atividades;
When executed, your table will be dropped, and that's no fun.

Related

PHP Not deleting MYSQL Database row

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.

If there is no $_POST present after a URL, how can I prevent (nothing) from getting passed into a MySQL query, and causing an error?

I have a Delete.php page that deletes records based on their ID.
When there is an ID, i.e., Delete.php?id=3610, all is well, and it functions as expected.
If I just go to "Delete.php" and that's it - no ID, it generates:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"
From the little I understand, it is doing this because I am trying to pass a nonexistent variable into my query.
I have been trying to put if (empty($_POST['id'])) { } in different places, which removes the error, but breaks something else.
Here is my code:
<?php
require_once 'functions.php';
$conn = mysqli_connect("localhost", "user", "pass",'db');
writeHead("Delete Track");
if (isset($_POST['delete'])) {
$trkid = $_POST['trkid'];
$query = "DELETE FROM track WHERE TrackID=$trkid";
mysqli_query($conn, $query) or die(mysqli_error($conn));
if (mysqli_affected_rows($conn)>0) {
header("Location: Display.php?action=deleted&id=$trkid&status=deleted");
exit();
}
echo "<p class='error'>Unable to update record</p>";
} else {
if (!isset($_GET['id'])) {
echo "<p class='error'>No Track ID provided.<br><a href='Display.php'>Return to display page.</a><p>";
}
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}
?>
<p>Track Information:</p>
<p><?php echo "<b>ID: $trkid <br>Title: $Name</b>"; ?></p>
<form method="post" action="Comp3Delete.php">
<p>
<input type="hidden" name="trkid" value="<?php echo $trkid; ?>">
<input type="submit" name="delete" class="btn" value="Confirm Delete">
</p>
</form>
<p>Return to Track Table Display</p>
<?php writeFoot(); ?>
Your post code is fine. it's the GET code that's wrong:
if (!isset($_GET['id'])) {
^^^^^^^^--check if the parameter exists
}
$trkid=$_GET['id'];
^---try to use the parameter ANYWAYS, even if it doesn't exist.
$trkid=$_GET['id']; has no condition so it runs even when no id is passed which generates the error. Your code should go like this:
if(isset($_GET['id'])){
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}

Inserting values from multiple checkboxes into multiple rows in a mysql database using php

I have stayed up two nights and I haven't been able to fix this. I am new to the site as well as in PHP please forgive my inexperience. The idea is that when a user selects several courses it should be sent to the database and stored in separate rows. what happens now is that it stores only the first value twice in the database. thanks.
code:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
$user_id=$_SESSION['user_id'];
?>
<h2>Register</h2>
<?php
if(isset($_GET['success']) && empty($_GET['success'])){
echo 'You have successfully registered!';
}
else{
if(empty($_POST)===false){
$course[]=$_POST['course_code'];
$user_id= $user_data['user_id'];
$username=$user_data['username'];
foreach($course as $c){
$data= '\''.implode('\',\'',$c).'\'';
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) VALUE ('$user_id','$username', $data)");
header('location:courses.php?success');
exit();
}
}
?>
<form action="" method="post">
<?php
$sql = "SELECT * FROM course";
$result = mysql_query($sql)or die(mysql_error());
echo "<table>";
echo "<tr><th>COURSE CODE</th><th>COURSE TITLE</th><th>UNIT</th><th>SEMESTER</th><th>LEVEL</th></tr>";
while($row = mysql_fetch_array($result)){
$course_code = $row['course_code'];
$course_title = $row['course_title'];
$course_unit = $row['course_unit'];
$semester = $row['semester'];
$level = $row['level'];
echo "<tr><td style='width: 100px;'>".$course_code."</td><td style='width: 600px;'>".$course_title."</td><td>".$course_unit."</td><td>".$semester."</td><td>".$level."</td><td><input type=\"checkbox\" name=\"course_code[]\" value=".$course_code."></td></tr>";
} // End our while loop
echo "</table>";
?>
<input type="submit" value="Register">
</form>
<?php
}
include 'includes/overall/footer.php';
?>
Your code is dangerous. It is not resistant for sql injection. You should stop using mysql_ functions and switch to mysqli or PDO.
But just to fix the bug now you can change your code in this part:
foreach($course as $c){
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`)
VALUES ('$user_id','$username', $c)");
}
header('location:courses.php?success');
exit();
redirection inside loop stopped the process so it did only once. for good practice do not put sql query inside loop it makes slow process.
$values = '';
foreach($course as $c){
$values .= "('$user_id','$username', '$c'), ";
}
$values = rtrim($values, ',');
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) VALUES {$values}");
header('location:courses.php?success');
exit();
if you don't agree, why you don't write some comment?

Using PHP to submit a Vector onto MySQL to make a connection with 2 tables

i have a list of emails on a database, which are brought onto the screen, this is coming from a previous page where you choose the category to add emails into.
The idea is for the user to check in the emails he wants to add to a connecting table that will join those two.
But i seem to be having problems. I have tried editing the page where i think the problem is, which is the , but no clue as to how i should edit it.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$idcategoria = $_GET["id"];
$query = "SELECT nome,email,id FROM email";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo"<form id='formulario' name='formulario' method='post' onsubmit='return validar(this);' action='../inserir/inserirmailcat.php'>";
echo "<br>";
echo "<button type='submit'>Submeter</button>";
echo "<tr align='center'><td>Nome</td><td>Email</td><td>Adicionar a Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if($campo=="nome")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="email")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="id")
{
echo "<td><input name='nome[".$valor."]' type='checkbox' value='Adicionar'></td></tr>";
}
}
echo "<input type='hidden' name='categoria' value='".$idcategoria."'>";
echo "</form>\n";
}
echo "</table>\n";
echo"</center>";
?>
This first page receives the ID from the previous one, and it lists a series of emails, where i check out the ones i want to add to a new table. And i try to pass them through a vector.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$queryq = "SELECT id FROM email";
$resultsq = mysql_query($queryq) or die(mysql_error());
while ($rowq = mysql_fetch_assoc($resultsq)) {
foreach ($rowq as $campoq=>$valorq) {
$cat = $_POST["categoria"];
$username = $_POST['nome['.$valorq.']'];
if ($username != '')
{
$query = "INSERT INTO emailcategoria (email,categoria) VALUES ('".$username.",".$cat."')";
mysql_query($query) or die(mysql_error());
}
}
}
mysql_query($queryq) or die(mysql_error());
header("Location:../listar/listarcategoria.php");
?>
On this second page i try to add only the emails which have been selected onto a new table which will receive the email's ID and the category's ID, but it is giving me the following error "after a few different error's when i tried a diferent approach":
Notice: Undefined index: nome[8445] in C:\xampp\phpMyAdmin\trabalho\inserir\inserirmailcat.php on line 10
The error is given for all the email ID's.
UPDATED
Error is on this like
$username = $_POST['nome['".$valorq."']'];
Firstly, is it supposed to be 'nome' ?
Secondly change the syntax like this
$username = $_POST['nome['.$valorq.']'];
$username = $_POST['nome['".$valorq."']'];
Well that's wrong, as the syntax highlighting shows.
$username = $_POST['nome['.$valorq.']'];
Also, sanitise your input or (better) use prepared statements!
> xkcd

double click required to insert into database

this might be a really simple solution but I really can't figure it out. if i insert into my database I have to press the insert button twice for it to work.. My guess is that it has to do with my using of 2 forms in one file or just because I did it all in one file. please help me.
thanks
code:
<?php
/*require "link.php";*/
?>
<html>
<head>
<!--<link rel="stylesheet" type="text/css" href="css.css">--> <!-- verwijzing naar je css -->
<!--<script type="text/javascript" src="js.js"></script>-->
</head>
<header>
</header>
<article>
<div id="cards">
<?php
$host = "localhost";
$user = "root";
$pwd = "";
$db_name = "flashcards";
$link = mysqli_connect($host, $user, $pwd, $db_name)or die("cannot connect");
$array = array();
$IDarray = array();
ini_set('display_errors', 1);
error_reporting(E_ALL);
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{
echo "<tr id='".$rows['ID']."'><td>".$rows['Question']."</td><td><input type='text' name='Answer[]' id='V".$rows['ID']."'></input></td></tr>";
$array[] = $rows["Answer"];
$IDarray[] = $rows["ID"];
}
echo "</table><input type='submit' name='submit'></input></form>";
$i = 0;
$count = sizeof($IDarray);
if(!empty($_POST['Answer']))
{
foreach($_POST['Answer'] as $answer)
{
if (isset($_POST['Answer'])) {
if ($answer == $array[$i])
{
echo "<script>document.getElementById('".$IDarray[$i]."').style.background='green'; document.getElementById('V".$IDarray[$i]."').value='".$array[$i]."'</script>";
}
elseif ($answer !== $array[$i])
{
echo "<script>document.getElementById('".$IDarray[$i]."').style.background='red'; document.getElementById('V".$IDarray[$i]."').value='".$answer."'</script>";
$count = $count-1;
}
$i ++;
}
}echo $count." van de ".sizeof($IDarray)." goed";
if ($count == sizeof($IDarray))
{
header('Location: http://localhost:1336/php3/');
}
}
echo "</br></br>insert";
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
echo "<tr><td>vraag</td><td><input type='text' name='vraag'></input></td><td>antwoord</td><td><input type='text' name='antwoord'></input></td></tr>";
echo "</table><input type='submit' name='submitinsert' value='insert'></input></form>";
if ($_POST['vraag'] != "") {
$vraag = $_POST['vraag'];
$antwoord = $_POST['antwoord'];
mysqli_query($link, "INSERT INTO questions (Question, Answer) VALUES (".$vraag.",".$antwoord.");") or die(mysqli_error($link));
}
?>
</div>
</article>
<footer>
</footer>
</html>
The problem is you're processing the form submission in the same script as the one that generates the form. Couple that to the fact that you firsT query the DB, generate a form with what you've already stored, and then add whatever data the user may have posted, you'll never see the data you've added show up the first time 'round you submit the form.
Either move the insert queries to the top (before generating the form), or separate concerns
Let me show you what I mean:
//don't OR DIE
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{//build form here
}
/*
CODE HERE
*/
if ($_POST['vraag'] != "") {
//insert here, after form is generated
}
So the data you query cannot, yet, contain the submitted form data.
There are some other issues with the code, though, like or die: don't do that. Be consistent with your coding style (allman brackets + K&R in the same script is messy). Properly indent your code and this:
if ($_POST['vraag'] != "") {
}
should be:
if (isset($_POST['vraag'])) {
}
You're comparing a key of an array that may not exist to an empty string, whereas you should check if that array key exists. Use isset.
I could go on a bit, but I'll leave it at that for now. Just one more thing: again -> separrate concerns! The presentation layer (the output: HTML and such) should not contain DB connection stuff. That should be done elsewhere.
Process your form either asynchronously (as whatever is submitted gets added to the table that is already there) using AJAX, or at least, use a separate script. Having 1 script doing all the work will soon leave you crying over a mess of spaghetti code
Its not submitting twice, actually its not loading the data after insertion,
Try adding
if ($_POST['vraag'] != "") {
$vraag = $_POST['vraag'];
$antwoord = $_POST['antwoord'];
echo "are you sure?";
mysqli_query($link, "INSERT INTO questions (Question, Answer) VALUES (".$vraag.",".$antwoord.");") or die(mysqli_error($link));
}
before
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or
die(mysqli_error($link));
this will select your records after the current record is saved.

Categories