I have connection, and I wan't delete one record by choosing ID (option have value of row ID in db)
<form class="form">
<?php
require "connect.php";
$select = $_POST['del_zaint'];
if(isset($_POST['Del'])){
$$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";
mysqli_query($db, $que);
}
mysqli_close($db);
?>
<span class="main-page__info">Usuń rekord zainteresowań.</span>
<select name="del_zaint">
<option disabled selected>Wybierz rekord do usunięcia</option>
<?php
require "connect.php";
$que = "SELECT * from zainteresowania";
$wynik = mysqli_query($db, $que);
while($row = mysqli_fetch_array($wynik)){
echo "<option value=".$row['id'].">"."[".$row['id']."] ".$row['zainteresowanie']."</option>";
}
mysqli_close($db);
?>
</select>
<input name="Del" type="submit" value="Usuń">
</form>
Nothing is done by this :/ I choose option and after clicking submit with name = Del, it won't work, just reset to normal position. (Adding informations to db and showing from it works well)
Try This
You miss the method in the form tag.
Also, I Change the SQL query
$que = "DELETE FROM `zainteresowania` WHERE id = '".$select."'";
Below code is working on my system. You have to use the SQL injection for secure
$db->real_escape_string($_POST['del_zaint'])
instated of delete the record, Make a column like status in the database and change the status 0 or 1.
You can refer the site for deleting the record
https://www.w3schools.com/php/php_mysql_delete.asp
<?php
include('db/connection.php');
if(isset($_POST['Del'])){
echo $select = $db->real_escape_string($_POST['del_zaint']);
$que = "DELETE FROM `zainteresowania` WHERE id = '".$select."'";
if (mysqli_query($db, $que)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($db);
}
mysqli_close($db);
}
?>
<form class="form" method="POST" action="#">
<span class="main-page__info">Usuń rekord zainteresowań.</span>
<select name="del_zaint">
<option disabled selected>Wybierz rekord do usunięcia</option>
<?php
$que = "SELECT * from zainteresowania";
$wynik = mysqli_query($db, $que);
while($row = mysqli_fetch_array($wynik)){
echo "<option value=".$row['id'].">"."[".$row['id']."] ".$row['zainteresowanie']."</option>";
}
mysqli_close($db);
?>
</select>
<input name="Del" type="submit" value="Usuń">
</form>
Please change this to:
require "connect.php";
$select = $_POST['del_zaint'];
if(isset($_POST['Del'])){
$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = $select";
mysqli_query($db, $que);
}
mysqli_close($db);
I have had cases where PHP only notices variables if they are included directly in double quotes and but not single quotes. The other option is to use string concatenation so that PHP knows where the variable is.
require "connect.php";
$select = $_POST['del_zaint'];
if(isset($_POST['Del'])){
$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";
mysqli_query($db, $que);
}
mysqli_close($db);
The main issue is you have not set method="post" with your form tag. So set it there and give it a try.
A suggestion:
Chage your query like this:
$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'"; // Check the changes I made around $select.
Related
So im trying to change the image thats already inside the database but i cant seem to make it work i kept looking at tutorials and other related questions but couldnt find the exact solution.
this is what i have in php
// Als de knop van de formulier is ingedrukt update de data dat van de database afkomt
if (isset($_POST['update'])) {
if (isset($_GET['id'])) {
$chauffeurs_id = $_GET['id'];
}
if (isset($_POST['Chauffeurs_foto'])) {
$Chauffeurs_foto = $_POST['Chauffeurs_foto'];
}
$sql = "SELECT * FROM chauffeurs ORDER BY 'chauffeurs_geboortedatum ASC";
$sql = "UPDATE `chauffeurs`
SET `Chauffeurs_foto`=$Chauffeurs_foto
WHERE `id`='$chauffeurs_id'";
$result = $conn->query($sql);
if ($result == TRUE){
echo "Aanpassingen zijn voltooid.";
}else{
echo "Error:" . $sql . "<br>" . $conn->error;
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];
Here is my html code:
<!-- Formulier waar alles in komt om te veranderen -->
<form action="" method="post" enctype='multipart/form-data' >
<fieldset>
<legend>Gegevens chauffeur:</legend>
<div class="form-group col-md-4">
//I did it like this so i could style the input file
<input type="file" name="file" id="file" class="inputfile" value="data:image/jpeg;base64, <?php.base64_encode($row['chauffeurs_foto']).?>" />
<label class="btn btn primary"for="file">Choose a file</label>
<input type="submit" value="Chauffeur Aanpassen" name="update">
</fieldset>
</form>
</div>
If anyone of you has a solution i would greatly appreciate it cause i need to finish it for my internship if not i'm just going to keep searching.
File uploads can be tricky. May I suggest you start by reading the documentation on file uploading first?
You will see that your upload can best be reached using the $_FILES array. You will need to store the uploaded data in a variable, using the file_get_contents() method. And it's the file data you'll be uploading to your mySQL server.
Your code should look something like this:
$foto = file_get_contents($_FILES['file']['tmp_name']);
$sql = "UPDATE `chauffeurs` SET `Chauffeurs_foto`='{$foto}' WHERE `id`='$chauffeurs_id'";
Finally, it's generally not good practise to store file data in your database, as the database size can get out of hand if the number of files you're storing in it grows. You're better off storing files (and images) separately and only storing a file reference in the database.
You have mistakes in your '. Try this code:
session_start();
include "config.php";
if (isset($_POST['update'])) {
if (isset($_GET['id'])) {
$chauffeurs_id = $_GET['id'];
}
if (isset($_POST['Chauffeurs_foto'])) {
$Chauffeurs_foto = $_POST['Chauffeurs_foto'];
}
$sql = "UPDATE chauffeurs SET Chauffeurs_foto = '$Chauffeurs_foto' WHERE id = '$chauffeurs_id'";
$result = $conn->query($sql);
if ($result == TRUE){
echo "Aanpassingen zijn voltooid.";
}else{
echo "Error:" . $sql . "<br>" . $conn->error;
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];
}
}
Assuming this is for a real application, you should properly escape SQL values for security reasons. Never trust user input! I'm going to assume you're using mysqli, so I'm using mysql::real_escape_string().
Also, you should properly embed your variables in the query, like so:
if (isset($_GET['id'])) {
$chauffeurs_id = $conn->real_escape_string($_GET['id']);
}
if (isset($_POST['Chauffeurs_foto'])) {
$Chauffeurs_foto = $conn->real_escape_string($_POST['Chauffeurs_foto']);
}
$sql = "SELECT * FROM chauffeurs ORDER BY `chauffeurs_geboortedatum` ASC"; // This statement can you remove, it will never be used in this way
$sql = "UPDATE `chauffeurs` SET `Chauffeurs_foto` = '{$Chauffeurs_foto}' WHERE `id`='{$chauffeurs_id}'";
Succes ermee.
I have just written this code and assign the name of the check box dynamically and delete the selected checkbox when delete button is pressed. But it isn't working. Can somebody help me??
main.php
$snooverhtml = "select * from songs_list";
$query7 = mysqli_query($con, $snooverhtml);?>
<form method="post" action="delete.php">
<input id="deletebtn" type="submit" name="deletethis" value="Delete"/></br>
<?php while($row = mysqli_fetch_assoc($query7)):?>
<input type="checkbox" name="<?php echo "cb".$row['sno.'];?>"/><?php echo $row['sno.']?> <?php echo $row['songs_name']?></br>
<?php
endwhile;
?>
delete.php
$noofsongs = "select * from songs_list";
$query8 = mysqli_query($con, $noofsongs);
$noio = mysqli_num_rows($query8);
$flag = 0;
if(isset($_POST['deletethis'])){
for($j=0; $j<=$noio ;$j++){
if (isset($_POST['<?php echo"cb".$j;?>'])){
$deletesongsquery = "DELETE FROM `songs_list` WHERE `sno.` = $j" ;
$query4 = mysqli_query($con, $deletesongsquery);
$flag = $flag + 1;
}
}
echo $flag;
}
You are already in PHP so $_POST['<?php echo"cb".$j;?>'] is incorrect. That is looking for <?php echo"cb".$j;?> literally as an index of $_POST which it never finds so isset is false. Use:
$_POST['cb'.$j']
or in your code usage:
if (isset($_POST['cb'. $j])){
You also should use parameterized queries. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/manual/en/security.database.sql-injection.php
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>";
}
}
I'm trying to update the database after select a few options and submit (using isset). The page display some information after a database query, and then I have to update the database according to the selected option.
If I run exactly the same query that is inside the function "actualizarEstado" but on a third page, then it works. What am I doing wrong? I can't understand. Tried to kill and close the first connection, but I get the same results. Thanks in advice!
<?php
include '00-conexion.php';
$data = extract($_GET);
$sql = "SELECT * FROM inscripciones WHERE nroInscripcion = $sel";
$retval = mysqli_query($conexion, $sql);
$fila = mysqli_fetch_array($retval);
if(isset($_POST['ejecutar'])){
actualizarEstado($sel);
}
function actualizarEstado($sel){
$estado = $_POST['estado'];
$sql2 = "UPDATE inscripciones SET revision1='',
revision2='',
revision3='',
revision4='',
revision5='',
revision6='',
revision7='',
revision8='',
revision9='',
estado='$estado'
WHERE nroInscripcion = $sel";
if (!mysqli_query($conexion, $sql2)) {
die('Error: ' . mysqli_error($conexion));
}
}
?>
<form method="post" action="">
<tr><td><select name="estado" from="estado">
<option value="aceptado">Aceptar</option>
<option value="rechazado">Rechazar</option>
<option value="revision">En revision</option>
</tr/></td>
<tr><td><input type="submit" value="Actualizar" name="ejecutar" onclick="return confirm('¿Estás seguro que deseas?')" /></tr></td>
</form>
I think you have to pass the $connexion variable through the function!
Make it something like this:
function actualizarEstado($myConnection,$sel){
$estado = $_POST['estado'];
$sql2 = "UPDATE inscripciones SET revision1='',
revision2='',
revision3='',
revision4='',
revision5='',
revision6='',
revision7='',
revision8='',
revision9='',
estado='$estado'
WHERE nroInscripcion = $sel";
if (!mysqli_query($myConnection, $sql2)) {
die('Error: ' . mysqli_error($myConnection));
}
}
and call the function like:
actualizarEstado($connexion,$sel);
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?