input file Update images inside database - php

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.

Related

PHP query when a user submit a form select

I want to delete a row from a form select when i click on submit input with an sql query,(i think i am wrong on something, but i don't understand what) as you can see below for my example :
My list and the blue case i want to delete on submit
My actual code, and the $supp i want to do when the user click on submit
`
<form method="POST">
<select>
<?php
// Drop Down
$res = null;
$sql2 = "SELECT `sinistre_type` FROM `form_sinistre`";
$query2 = $db->prepare($sql2);
$query2->execute();
// INIT > PREP > EXEC > SUPP
$supp = "DELETE FROM `form_sinistre` WHERE `sinistre_type` = '$res'";
$query3 = $db->prepare($supp);
$sendbddsupp = $query3->execute();
echo "<option disabled selected>..Choix Possible..</option>\n";
while ($res = $query2->fetch(PDO::FETCH_NUM)) {
echo "<option name='res'>" . $res[0] . "</option>\n";
}
?>
</select>
<input type="submit" value="Supprimer">
</form>
`
Some $_POST config
`
<?php
session_start(); //debut de SESSION
include("config.php"); //Appel de la bdd
// ... INIT VARIABLES ...
$sinistre_type = "";
$sinistre_desc_dmg = "";
$list = "";
if (empty($_POST)) { // SANS COOKIES / POST
} else { // AVEC COOKIES / POST
$sinistre_type = $_POST['nom'];
$sinistre_desc_dmg = $_POST['vent'];
$res = $_POST['res'];
$sql = "INSERT INTO `form_sinistre` (sinistre_type, sinistre_desc_dmg) VALUES (:sinistre_type, :sinistre_desc_dmg)";
$query = $db->prepare($sql);
$query->execute(array(':sinistre_type' => $sinistre_type, ':sinistre_desc_dmg' => $sinistre_desc_dmg));
}
var_dump(isset($_POST['res']));
?>
`
(EDIT : my list is linked with my db and working that why i want to send sql query)
Thanks by advance for your help, if you need more information let me know :)

Submitting table row data to another table using an input field in php

How can I submit a table row data to another table using an input field in PHP and MYSQL?
HTML
<form method="post" action="post.php">
<input type="number" name="code" placeholder="Code..."/>
<input type="submit" name="submit" value="Submit"/>
</form>
Post.php
if (isset($_POST['submit'])) {
$code = $_POST['code'];
$getCode = "SELECT * FROM products WHERE code=$code";
mysqli_query($connection, $getCode);
if ($_POST['code'] == $code) {
$migrating = "INSERT INTO managment(price) VALUES ($price) SELECT
price FROM products";
mysqli_query($connection, $migrating);
header("location: index.php");
}
}
What is wrong with my code?
The syntax is :
INSERT INTO managment(price) SELECT price FROM products
Maybe you want add a WHERE clause :
INSERT INTO managment(price) SELECT price FROM products WHERE code=$code
Note: in your code, $_POST['code'] == $code doesn't make sense, because of $code = $_POST['code'] earlier.
I also suggest you to have a look to How can I prevent SQL injection in PHP? to secure your queries.
Your code updated (untested) :
if (isset($_POST['submit'])) {
$code = $_POST['code'];
$getCode = "SELECT * FROM products WHERE code=$code";
$result = mysqli_query($connection, $getCode);
if (!$result) die("Error: " . mysqli_error($connection));
$row = mysqli_fetch_assoc($result);
if ($row['code'] == $code) {
$migrating = "INSERT INTO managment(price)
SELECT price FROM products WHERE code=$code";
$result2 = mysqli_query($connection, $migrating);
if (!$result2) die("Error: " . mysqli_error($connection));
header("Location: index.php");
exit;
}
}

PHP Query won't work with DELETE

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.

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

Mysqli not updating

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

Categories