Can't get the image link - php

So I can't insert images. I keep getting the following error.
"Notice: Undefined index: uploaded"
I can't get the image link!
Uploaded is the name of the button type=file (Upload images)
<?php
$host="localhost"; // Nome do host onde esta o banco de dados. Padrão ‘localhost’
$usuario="root"; // Usuário do Mysql. Padrão ‘root’
$senha=""; // Senha do Mysql
$db ="centro"; // Nome da Database
$tabela="usuarios"; // Nome da tabela
//connecta ao servidor
$mysqli = mysqli_connect("$host", "$usuario", "$senha")or die("cannot connect");
mysqli_select_db($mysqli,$db)or die("cannot select DB");
if(isset($_POST["upload"]))
{
//HERE!!!!!!!
$d="imagens/" . $_FILES["uploaded"]["name"];
if($_FILES["uploaded"]["type"]=="image/jpeg")
{
if(move_uploaded_file($_FILES["uploaded"]["tmp_name"],$d))
{
echo '<img style="width:50px;height:50px;" src="'. $d . '" >';
}
}
$titulo=$_POST['titulo'];
$mensagem=$_POST['mensagem'];
$ano=$_POST['ano'];
$mes=$_POST['mes'];
$dia=$_POST['dia'];
$link=$d;
}
else
{
echo "So imagens JPG.";
$titulo=" ";
$mensagem=" ";
$ano=0;
$mes=0;
$dia=0;
$link=" ";
}
$query = "INSERT INTO imagens(titulo,mensagem,dia,mes,ano,link) VALUES(?,?,?,?,?,?)";
$stat = $mysqli->prepare($query);
$stat->bind_param('ssiiis',$titulo,$mensagem,$dia,$mes,$ano,$link);
if ($stat->execute() && $stat->affected_rows>0)
{
echo "<div>Foi inserida uma imagem!</div>";
}
$stat->close();
$mysqli->close();
?>

You are getting:
Notice: Undefined index: uploaded
For this notice check your HTML Form and
enctype="multipart/form-data"
Example:
<form action="youraction" method="yourMethod" enctype="multipart/form-data">
HTML enctype Attribute

Related

How to save a file name in the MySQL database?

I have developed this code below to the user upload a file and save the name of this file in the database, to be able to access it later, the upload is done normally, it goes to the designated folder, but the name is not saved in the database, does anyone know what's wrong with the code? Especially below the move_uploaded_file, because so far it works, then it goes wrong.
<?php
if (isset($_POST['enviar'])) {
$arq = $_FILES['arquivo']['name'];
$arq = str_replace(" ", "_", $arq);
$arq = str_replace("ç", "c", $arq);
if (file_exists("uploads/$arq")) {
$a = 1;
while (file_exists("uploads/[$a]$arq")) {
$a++;
}
$arq = "[".$a."]".$arq;
}
if (move_uploaded_file($_FILES['arquivo']['tmp_name'], 'uploads/'.$arq)) {
$objDb = new db();
$link = $objDb->conecta_mysql();
$sql = "insert into arquivos (email_vol, nomearq) values ('$email', '$arq')";
if (mysqli_query($link, $sql)){
echo 'Plano de aula 1 enviado com sucesso!';
} else {
echo (mysqli_error($link));
echo 'Erro ao enviar o plano de aula!';
}
} else {
echo "Nenhum arquivo selecionado!";
}
}
?>
That is the code used to connect with the database:
class db {
//host
private $host = 'localhost';
//usuario
private $usuario = '111111';
//senha
private $senha = '11111111';
//banco de dados
private $database = 'dsfadsfasd';
public function conecta_mysql(){
//criar a conexão
$con = mysqli_connect($this->host, $this->usuario, $this->senha, $this->database);
//ajustar a charser de cominicação entre a aplicação e o bd
mysqli_set_charset($con, 'utf8');
//verificar se houve erro de conexão
if (mysqli_connect_errno()) {
echo 'Erro ao tentar se conectar com o banco de dados'.mysqli_connect_error();
}
return $con;
}
}
?>
Don't have the privilege to comment right now but shouldn't this be like this plus you don't have a semicolon at the end of your sql script
$sql = "insert into arquivos (email_vol, nomearq) values ('" . $email . "', '"
.$arq . "');";
and also this
if (file_exists("uploads/" . $arq)) {
$a = 1;
while (file_exists("uploads/". $a . ".". $arq)) {
$a++;
}
$arq = $a.".".$arq;
}
with a full stop between your file number and name

can't create automatic sql tables after first use

I'm new with PHP and SQL...
I'm trying to create new tables based on the url, but it's only working the first time I use it. After that, it's not possible.
Here is my PHP code:
if(isset($_GET['id'])){
$tabela = $_GET['tabela'];
$_GET['id'];
$criar = $tabela . $nivel . $page_id;
// Se clicar no botão 'confirmar', então ele faz o seguinte:
if(isset($_POST['submit'])){
$titulo = $_POST['titulo'];
$_FILES['imagem']['tmp_name'];
$texto = $_POST['texto'];
// Se um destes campos estiver vazio:
if($titulo=='' or $imagem=='' or $texto==''){
echo "Preencha todos os campos para o menu!";
exit(); }
// Se não houver campos vazios, ele faz: else {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "site";
// Ligação à base de dados:
$conn = new mysqli($servername, $username, $password, $dbname);
// Verifica a ligação:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Cria a nova tabela:
$sql = "CREATE TABLE IF NOT EXISTS $criar (
id INT(9) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
titulo VARCHAR(255),
imagem LONGBLOB,
texto TEXT,
grupo INT(9),
FOREIGN KEY (grupo) REFERENCES $tabela(id)
)";
// Se conseguir ligar-se à base de dados e criar uma nova tabela, ele insere os dados na nova tabela:
if ($conn->query($sql) === TRUE) {
include("includes/connect.php");
mysql_query("SET NAMES 'utf8'");
move_uploaded_file($image_tmp,"../imagens/$imagem");
$insert_query = "INSERT INTO $criar (titulo, imagem, texto, grupo) VALUES ('$titulo','$imagem','$texto','$page_id')";
// Se inserir os dados na nova tabela, ele dá uma mensagem de sucesso:
if(mysql_query($insert_query)){
echo "<script>alert('Menu inserido com sucesso!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "Erro: " . $insert_query . "<br>" . $conn->error;
}
}
// Caso ele não consiga criar uma nova tabela (porque já existe), ele insere os dados na tabela já existente:
else {
include("includes/connect.php");
mysql_query("SET NAMES 'utf8'");
// Cria a nova tabela:
$sql = "CREATE TABLE IF NOT EXISTS $criar (
id INT(9) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
titulo VARCHAR(255),
imagem LONGBLOB,
texto TEXT,
grupo INT(9),
FOREIGN KEY (grupo) REFERENCES $tabela(id)
)";
if(mysql_query($sql)){
echo "sim!";
}
else {
echo "não!";
}
move_uploaded_file($image_tmp,"../imagens/$imagem");
$insert_query = "INSERT INTO $criar (titulo, imagem, texto, grupo) VALUES ('$titulo','$imagem','$texto','$page_id')";
// Caso consiga inserir os dados na tabela já existente, dá uma mensagem de sucesso:
if(mysql_query($insert_query&&$sql)){
echo "<script>alert('Menu inserido com sucesso!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "isto não está a correr bem!";
}
// Fecha a ligação à base de dados:
$conn->close();
} } }$nivel = $_GET['grupo']; $page_id =$imagem = $_FILES['imagem']['name']; $image_tmp =
What do you mean 1st time, 2nd time? Do you try to create another table with the same name you just have created? You'll get a table already exists error.
CREATE TABLE IF NOT EXISTS $criar
This explicitly tells MySql not to create the table if it exists, so if you pass the same query parameters to your php then it'll not be able to create the same table again.
Probably you could change it to:
$page_id = $_GET['id'];
$criar = $tabela . $nivel . $page_id;
And then pass a different id and/or different tabela every time.
this code looks behind the issue to me :
$tabela = $_GET['tabela'];
$_GET['id']; //this line looks odd
$criar = $tabela . $nivel . $page_id;
and maybe it's not creating new tables because you give the same $criar every time.
After hours of trying to solve this issue, i finally got good news! :) i was working in my local server (via xampp) and decided to put it online to check if something changes... and dont know why, but it works perfectly online and dont work with xampp! What a mess!! but its working!! thanks all for your help!! ;)

Delete images from two directories

I have a script that loads images in the database and in two directories: uploads / original and a directory for the preview: uploads / thumbs
I need to create a small panel to delete inserted images, I have already created the code to delete from the database, but I can not delete them from the two directories.
I know I need to use unlink, but I'm no expert, I do not know where to place the code etc. I ask for help to you.
This is the file that I delete.php structured so far:
<?php
$con = mysql_connect("localhost","*******","******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("**********************", $con);
if($_POST)
{
$ids = isset($_POST['id']) ? $_POST['id'] : array();
elimina_record($ids);
}
elseif(isset($_GET['id']))
{
elimina_record(array($_GET['id']));
}
else
mostra_lista();
function mostra_lista()
{
// mostro un eventuale messaggio
if(isset($_GET['msg']))
echo '<b>'.htmlentities($_GET['msg']).'</b><br /><br />';
// preparo la query
$query = "SELECT id,name,filename FROM image";
// invio la query
$result = mysql_query($query);
// controllo l'esito
if (!$result) {
die("Errore nella query $query: " . mysql_error());
}
echo '
<form name="form1" method="post" action="">
<table border="1">
<tr>
<th> </th>
<th>ID</th>
<th> </th>
</tr>';
while ($row = mysql_fetch_assoc($result))
{
$name = htmlentities($row['name']);
$id = htmlentities($row['id']);
$filename = htmlentities($row['filename']);
// preparo il link per la modifica dei dati del record
$link = $_SERVER['PHP_SELF'].'?id=' . $row['id'];
echo "<tr>
<td><input name=\"id[]\" type=\"checkbox\" value=\"$row[id]\" /></td>
<td>$id</td>
<td>delete</td>
</tr>";
}
echo '</table>
<br />
<input type="submit" name="Submit" value="Elimina record selezionati" />
</form>';
// libero la memoria di PHP occupata dai record estratti con la SELECT
mysql_free_result($result);
// chiudo la connessione a MySQL
mysql_close();
}
function elimina_record($ids)
{
// verifico che almeno un id sia stato selezionato
if(count($ids) < 1)
{
$messaggio = urlencode("Nessun record selezionato!");
header('location: '.$_SERVER['PHP_SELF'].'?msg='.$messaggio);
exit;
}
// per precauzione converto gli ID in interi
$ids = array_map('intval',$ids);
// creo una lista di ID per la query
$ids = implode(',',$ids);
// preparo la query
$query = "DELETE FROM image WHERE id IN ($ids)";
// invio la query
$result = mysql_query($query);
// controllo l'esito
if (!$result) {
die("Errore nella query $query: " . mysql_error());
}
// conto il numero di record cancellati
$num_record = mysql_affected_rows();
// chiudo la connessione a MySQL
mysql_close();
$messaggio = urlencode("Numero record cancellati: $num_record");
header('location: '.$_SERVER['PHP_SELF'].'?msg='.$messaggio);
}
?>
While, it may be useful, even paste the file to upload.php files:
session_start();
$_SESSION['id']="1";
$id=$_SESSION['id'];
include 'config.php'; //assume you have connected to database already.
$folder = 'uploads/';
$name = date('YmdHis');
$filename = md5($_SERVER['REMOTE_ADDR'].rand()).'.jpg';
$original = $folder.$filename;
// The JPEG snapshot is sent as raw input:
$input = file_get_contents('php://input');
if(md5($input) == '7d4df9cc423720b7f1f3d672b89362be'){
// Blank image. We don't need this one.
exit;
}
$result = file_put_contents($original, $input);
if (!$result) {
echo '{
"error" : 1,
"message" : "Failed save the image. Make sure you chmod the uploads folder and its subfolders to 777."
}';
exit;
}
$info = getimagesize($original);
if($info['mime'] != 'image/jpeg'){
unlink($original);
exit;
}
// Moving the temporary file to the originals folder:
rename($original,'uploads/original/'.$filename);
$original = 'uploads/original/'.$filename;
// Using the GD library to resize
// the image into a thumbnail:
$origImage = imagecreatefromjpeg($original);
$newImage = imagecreatetruecolor(154,110);
imagecopyresampled($newImage,$origImage,0,0,0,0,154,110,520,370);
imagejpeg($newImage,'uploads/thumbs/'.$filename);
echo '{"status":1,"message":"Success!","filename":"'.$filename.'"}';
$sql="INSERT INTO image VALUES ('','$name','$filename')";
$result=mysqli_query($con,$sql);
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
$cart_1="/uploads/original/";
$cart_2="/uploads/thumbs/";
foreach($files as $file){
$f_1=$cart_1.$file;
$f_2=$cart_2.$file;
unlink($f_1);
unlink($f_2);
}
Check this out:
$dir1 = '/upload/original/';
$dir2 = '/upload/thumbs/';
$image = 'abc.jpg';
if(file_exists($dir1.$image))
unlink($dir1.$image);
if(file_exists($dir2.$image))
unlink($dir2.$image);

no database selected php/mysql

i have a trouble with this T_T this is a searching/consult script for cars parts
this is the php
<?php
if ($_POST['buscar'])
{
// Tomamos el valor ingresado
$buscar = $_POST['palabra'];
// Si está vacío, lo informamos, sino realizamos la búsqueda
if(empty($buscar))
{
echo "No se ha ingresado una cadena a buscar";
}else{
//Conexión a la base de datos
$servidor = "localhost"; //Nombre del servidor
$usuario = "root"; //Nombre de usuario en tu servidor
$password = "1234"; //Contraseña del usuario
$base = "db_maquinas"; //Nombre de la BD
$con = mysql_connect($servidor, $usuario, $password) or die("Error al conectarse al servidor");
$sql= mysql_query("SELECT * FROM repuestos WHERE 'id','descripcion' LIKE '%$buscar%' ORDER BY id", $con) or die(mysql_error($con));
mysql_select_db($base, $con) or die("Error al conectarse a la base de datos");
$result = mysql_query($sql, $con);
// Tomamos el total de los resultados
if($result) { $total = mysql_num_rows($result); } else { die('Invalid query' . mysql_error($con)); }
echo "<table border = '1'> \n";
//Mostramos los nombres de las tablas
echo "<tr> \n";
while ($field = mysql_fetch_field($result)){
echo "<td>$field->name</td> \n";
}
echo "</tr> \n";
do {
echo "<tr> \n";
echo "<td>".$row["id"]."</td> \n";
echo "<td>".$row["descripcion"]."</td> \n";
echo "<td>".$row["cantidad"]."</td> \n";
echo "</tr> \n";
} while ($row = mysql_fetch_array($result));
echo "</table> \n";
echo "¡ No se ha encontrado ningún registro !";
}
}
?>
that when on the form i press "Send or Search" this send me to another page that says "NO DATABASE SELECTED"
I hope somebody can help me with that..
PD: i'm using a localhost DB with PhpMyAdmin i have items on tables, i verified tables not empty...
You select your database after you attempt to run queries. Place the code before you attempt to run queries:
mysql_select_db($base, $con) or die("Error al conectarse a la base de datos");
$sql= mysql_query("SELECT * FROM repuestos WHERE 'id','descripcion' LIKE '%$buscar%' ORDER BY id", $con) or die(mysql_error($con));
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
place the mysql_selectdb() before the mysql_query().

I can't delete fields in a mysql database

I need to delete to generate a form to select in checkboxes which users I want to delete from the database. To search the users and generate the form I use this code:
<?php
$con = new mysqli('localhost', 'root', '', 'prueba');
$busqueda ="";
$busqueda=$_POST['busqueda'] ;
// funcion para convertir el contenido de un array en un string
function makestring($array)
{
$outval = '';
if (is_array($array)) {
foreach($array as $key=>$value)
{
if(is_array($value))
{
$outval = makestring($value);
}
else
{
$outval = $value;
}
}
}
return $outval;
}
if ($busqueda!=""){
$busca = mysqli_query($con, " SELECT usuario FROM usuarios WHERE
usuario LIKE '%$busqueda%'");
echo "<form action='borrar.php' method='post' enctype='multipart/form-data'>";
while ($array= mysqli_fetch_array($busca)){
$user=makestring($array);
echo"Usuario: <input type='checkbox' name='borrar_usuario[]' value='$user' />$user<br/>";
}
echo " <input type='submit' name='boton' value='eliminar' />";
echo "</form>";
}
$all =$_POST['todos'] ;
if ($all=='borrar_todos'){
$busca = mysqli_query($con, "select usuario from usuarios ");
echo "<form action='borrar.php' method='post' enctype='multipart/form-data'>";
while ($f = mysqli_fetch_array($busca)){
$user=makestring($f);
echo "Usuario: <input type='checkbox' name='borrar_usuario[]' value='$user' />$user<br/>";
}
echo " <input type='submit' name='boton' value='eliminar' />";
echo "</form>";
}
?>
I use this code to collect the data from the forms with this code:
<?php
$con = new mysqli('localhost', 'root', '', 'prueba');
if(isset($_REQUEST["borrar_usuario"])) {
$del_user = $_POST["borrar_usuario"];
$mensaje = "¿Está seguro que quiere eliminar el usuario <b>$row[usuarioNombre]</b>?";
}
// mostramos el mensage
echo $mensaje;
mysqli_query($con, "delete usuario, password, descripcion from usuarios
where usuario in like '$del_user'");
echo "usuario borrado";
header('refresh: 3; url= exito.php');
?>
But it doesn't delete anything in the database. Any help please?
DELETE deletes the entire row from the database. You question feels like you need to Empty some specific fields. Try the following Code
mysqli_query($con, "UPDATE usuarios SET usuario = null, password =null,
descripcion=null where usuario like '$del_user'");
If you want to empty a field or fields, you need to use update usuarios set usuario = '', password = '', descripcion = '' where usuario like '$del_user'"
Try this as the delete query
"delete from usuarios where usuario = '$del_user'"
Use this if you delete one user at the time:
delete from usuarios where usuario = '$del_user'
or this if you delete more users and have ids in comma(,) delimited list
delete from usuarios where usuario in ('$del_user')

Categories