A PHP DOM program to import Freemind document in database - php

I put my code after some explanations.
I program this because i need to fill a database used by an application with .mm document (Freemind docs, .mm is the extension for "mind mapping")
The application and database need i keep the structure inside the Freemind doc. I don't program the application and the database, it's the work of an another guy.
This is the reason because i have all this
"if the child of the current node is a node with a child is an icon with an attribute called BUILTIN contains idea, this child is not an other object to put in the database, but the "contenu" value of the object create by the current node"
Just horrible to explain (it's horrible to explain it in French... And i try to make it clear in English. I hope it's clear.)
When i try to use my program, i can select the Freemind docs i want to convert is SQL, but i have this error just after:
Fatal error: Can't use method return value in write context in C:\xampp\htdocs\test2\transfertXmlBdd.php on line 25
Someone know why it's doesn't work and how i can make it works?
I think it's this part
if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$chaineXML = $target_file;
I try to keep the uploaded file in the $chaineXML for charge it with DOM after.
$dom->loadXML($chaineXML);
But i probably do it wrong.
uploadForm
<form action="upload.php" method="post" enctype="multipart/form-data">
Selectionner le document Freemind a charger:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Charger le document" name="submit">
</form>
</body>
</html>
upload
// Check if image file is a actual image or fake image
//if(isset($_POST["submit"])) {
// $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
// if($check !== false) {
// echo "File is an image - " . $check["mime"] . ".";
// $uploadOk = 1;
// } else {
// echo "File is not an image.";
// $uploadOk = 0;
// }
//}
// Check if file already exists
if (file_exists($target_file)) {
echo "Le fichier a deja ete charger.";
$uploadOk = 0;
}
// Check file size
//if ($_FILES["fileToUpload"]["size"] > 50000000) {
// echo "Le fichier est trop lourd.";
// $uploadOk = 0;
//}
// Allow certain file formats
if($imageFileType != "mm") {
echo "Vous ne pouvez upload que des fichiers XML au format MM (mind mapping).";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Echec du chargement.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$chaineXML = $target_file;
echo "Le fichier ". basename( $_FILES["fileToUpload"]["name"]). " a ete charger.";
//on appelle la conversion/transfert
include_once('C:/xampp/htdocs/test2/transfertXmlBdd.php');
echo "Les donnees ont ete enregistre dans la BDD.";
} else {
echo "Une erreur s'est produite.";
}
}
?>
transferXmlBdd
$dom->loadXML($chaineXML);
$element = $listeElements->item(0);
//variables
$id= NULL;
$nom = NULL;
$type = NULL;
$contenu = NULL;
$idParent = NULL;
$idFils = NULL;
//comper le nombres d'elements déjà présent dans la table
$res = $bdd->query('select count(*) as nb from element');
$data = $res->fetch();
$id = $data['nb'];
foreach($xml as $node)
{
//on vérifie la présence ou non de BUILTIN de valeur idea, on passe à l'itération suivante (en forçant) si oui
if($node->hasChild("icon")->hasAttribute("BUILTIN")="idea")
{
continue;
}
//on génere les valeurs id et nom
$nom = getAttributeNode('NAME');
$id = $id + 1;
$idFils = $id;
//
$node.setAttribute(bddid,$id);
//on vérifie la parenté de l'enregistrement
if($node->hasParent("node"))
{
$idParent = getAttributeParent('bddid');
$req = $bdd->prepare('INSERT INTO fils_des_element(id_elem, id_fils) VALUES( idParent, :idFils)');
}
else
{
// affilié à l'élement 0
$req = $bdd->prepare('INSERT INTO fils_des_element(id_elem, id_fils) VALUES( 0, :idFils)');
}
//vérification de contenu
if($node->hasChild("node")->hasChild("icon")->hasAttribute("BUILTIN")=idea)
{
$contenu = getChildAttribute('NAME');
}
//détermination du type
if($node->hasChild("icon")-hasAttribute("BUILTIN")=button_ok)
{
$type = "Avec Solution";
}
elseif($node->hasChild("icon")-hasAttribute("BUILTIN")=button_cancel)
{
$type = "Sans Solution";
}
else
{
$type = NULL;
}
//création de l'entré dans la table
$req = $bdd->prepare('INSERT INTO element(id_element, nom, type, proprietaire, visible, contenu, date_modif) VALUES( :id, :nom, :type, drn, 0, :contenu, CURDATE())');
}
?>

Related

My php code loops and doesn't explore my database [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 1 year ago.
Hello I'm currently trying to create a page based on a database under mysql that would update itself for a client. However what I'm trying to do loops and returns the first value of the database each time and indefinetely when I want it to go on to another object in the database. Here is the code, I'm a beginner so the error might be flagrant, thanks for the help.
<?php
try
{
$db = new PDO('mysql:host=localhost;dbname=labase', 'root' ,'');
$db->exec(" SET CHARACTER SET utf8 ");
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e){
echo'une erreur est survenue';
die();
}
for ($i = 1; $i < 10; $i++) {
if ($i=1){
$select = $db->prepare("Select profession from contact where affiliation='nord' group by profession"); // je récupère les professions de la bdd
$select->execute();
}
$data = $select->fetch(PDO::FETCH_OBJ);
$profess=$data->profession; // je prends la prochaine profession
$selectionner = $db->prepare("Select nomcontact, count(*) as nbrcontact from contact where affiliation='nord' and profession='$profess'"); // je prends les contacts qui ont cette profession ainsi que leur nombre
$selectionner->execute();
$prendre = $selectionner->fetch(PDO::FETCH_OBJ);
$nbrcontact=$prendre->nbrcontact;// je récupère leur nombre
echo $profess;
echo $nbrcontact;
}
?>
I am not a PHP expert and never use PDO, but in Msqli, there is a fetch_array() to get multiple result (instead of fetch for single result), maybe in PDO you have a fetch_array too. Then, you can loop on the result array
Something like that (using msqli)
$sql = "SELECT... FROM ..";
$result = $link->query($sql);
while($row =mysqli_fetch_array($result))
{
}
if ($i=1) { // here is should be == or ===
You're causing an infinite loop by declaring $i=1
<?php
try
{
$db = new PDO('mysql:host=localhost;dbname=labase', 'root' ,'');
$db->exec(" SET CHARACTER SET utf8 ");
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e){
echo'une erreur est survenue';
die();
}
for ($i = 1; $i < 10; $i++) {
if ($i == 1){ // added code
$select = $db->prepare("Select profession from contact where affiliation='nord' group by profession"); // je récupère les professions de la bdd
$select->execute();
}
$data = $select->fetch(PDO::FETCH_OBJ);
$profess=$data->profession; // je prends la prochaine profession
$selectionner = $db->prepare("Select nomcontact, count(*) as nbrcontact from contact where affiliation='nord' and profession='$profess'"); // je prends les contacts qui ont cette profession ainsi que leur nombre
$selectionner->execute();
$prendre = $selectionner->fetch(PDO::FETCH_OBJ);
$nbrcontact=$prendre->nbrcontact;// je récupère leur nombre
echo $profess;
echo $nbrcontact;
}
?>
Use == for comparison

ajax didn't call the server php program

I am quite new in the programming and I try to check if a shop has been already assigned to an user. if yes nobody can be assigned to this shop anymore.
so in the index file I make a call via $.ajax of searchunicusershop.php but it didn't seem to call it.
in index.php
unic = {};
data = "siret=" + $('#siret').val() + "&emllog=" + $('#email_login').text();
$.ajax({
type: 'GET',
url: 'searchunicusershop.php',
data: data,
dataType: 'json',
success: function(result, statut) {
unic = {};
unic = result;
if (unic.response == false) {
if (unic.status == 'alreadyassign') {
$('.messmenu').text('shop already assigned');
$('.profile-card-pro').scrollTop(0);
}
}
},
error: function(result, statut, erreur) {
console.log(statut);
console.log(erreur);
},
complete: function(result, statut, erreur) {
}
});
the searchunicusrshop.php
<?php
header("Content-Type: application/json ; charset=utf-8");
header("Cache-Control: no-cache , private");
header("Pragma: no-cache");
$email_login = ' ';
$siret = ' ';
$siren = ' ';
$nic = ' ';
$res1 = ' ';
$res2 = ' ';
$res3 = ' ';
$tunic=[];
$tunic['emllog'] = ' ';
$tunic['siret'] = ' ';
$tunic['status'] = 'false';
$tunic['shopid'] = ' ';
$tunic['admid'] = ' ';
$tunic['emladm'] = ' ';
$tunic['response'] = false;
$shopshop_id = ' ';
$hasshopuser_id = ' ';
$usersuser_email = ' ';
var_dump ($_GET);
require_once('connexionMysqlCheck.php');
if ($connected) {
require_once('connexionMysql.php');
if (isset($_GET['siret']) && isset($_GET['emllog'])) {
$email_login = $_GET['emllog'];
$tunic['emllog'] = $email_login;
$tunic['siret'] = $_GET['$siret'];
$tunic['status'] = 'paramfull';
$siret = $_GET['siret'];
$siren = substr($siret, 0, 9);
$nic = intval(substr($siret, 9, 5));
// Recherche du shop_id avec siret pour accéder ) user_has_shop
$query1="SELECT shop_id FROM shop WHERE siren = ".$siren." and nic = ".$nic."";
var_dump ($query1);
$res1=mysqli_query($connexion,$query1) or die('Erreur SQL !<br />'.$query1.'<br />'.mysqlerror());
if (mysqli_num_rows($res1)>0) { // si le shop est trouvé
while ( $enreg=mysqli_fetch_array($res1) ) { // récupérer le shop_id
$shopshop_id = $enreg['shop_id'];
$tunic['shopid'] = $enreg['shop_id'];
$tunic['status'] = 'shopfound';
mysql_free_result ($res1);
// si shop_id trouvé alors recherche du user_id avec le shop_id dans la table user_has_shop
$query2="SELECT user_id FROM user_has_shop WHERE shop_id = ".$shopshop_id." and shop_admin = 1";
echo $query2;
$res2=mysqli_query($connexion,$query2) or die('Erreur SQL !<br />'.$query2.'<br />'.mysqlerror());
if (mysqli_num_rows($res2)>0) { // s'il y a une association qui existe pour ce shop
while ( $enreg=mysqli_fetch_array($res2) ) { // récupérer le user_id qui est associé dans users has shop
$hasshopuser_id = $enreg['user_id'];
$tunic['admid'] = $hasshopuser_id;
$tunic['status'] = 'assocfound';
mysql_free_result ($res2);
// Recherche si l'utilisateur via son email existe dans users
$query3="SELECT email_login FROM users WHERE user_id = '".$hasshopuser_id"'";
echo $query3;
$res3=mysqli_query($connexion,$query3) or die('Erreur SQL !<br />'.$query3.'<br />'.mysqlerror());
if (mysqli_num_rows($res3)>0) { // si l'utilisateur est trouvé
while ( $enreg=mysqli_fetch_array($res3) ) { // récupérer le user_id de users
$usersuser_email = $enreg['email_login'];
$tunic['emladm'] = $useruser_email;
$tunic['status'] = 'admassocfound';
mysql_free_result ($res3);
if ($email_login == $useruser_email) { // si le shop est déjà associé à lui alors ok
$tunic['status'] = 'assochimself';
$tunic['responses'] = true;
} else { //si il y a déjà une association mais à quelqu'un d'autre alors il ne peut pas
$tunic['status'] = 'alreadyassign';
$tunic['response'] = false;
}
} // fin de while pour récupérer lemail du user associé dans users query3 ***********************
} else {
$tunic['admid'] = $hasshopuser_id;
$tunic['emladm'] = ' ';
$tunic['status'] = 'admnotfoundcritical';
$tunic['response'] = false;
} // si l'utilisateur adm n'est pas trouvé user, c'est pas normal
} // fin de while pour récupérer le user_id de user_has_shop query2 ***********************
} else { // si pas assoc alors c'est bon
$tunic['admid'] = ' ';
$tunic['emladm'] = ' ';
$tunic['status'] = 'noassocfound';
$tunic['response'] = true;
} // si pas d'association alors c'est bon
} // fin while récupérer shop_id query1 uy**************************************
} else { // si le shop_id n'est pas trouvé dans shop ne rien faire c'est false
$tunic['status'] = 'siretnotfound';
$tunic['shopid'] = ' ';
$tunic['admid'] = ' ';
$tunic['emladm'] = ' ';
$tunic['response'] = false;
}// si le shop_id n'est pas trouvé dans shop ne rien faire c'est false
} else { // ne trouve pas not isset. l'un des 2 ou les 2 paramètres email et/ou siret est vide (sont vides)
$tunic['emllog'] = $_GET['emllog'];
$tunic['siret'] = $_GET['siret'];
$tunic['status'] = 'paramempty';
$tunic['shopid'] = ' ';
$tunic['admid'] = ' ';
$tunic['emladm'] = ' ';
$tunic['response'] = false;
} // fin not isset
} // connecté
$result = $tunic;
echo json_encode($result);
?>
I don't know if the index call it or not, if it was successful or in error. I try to debug via chrome but it went through this code but I didn't get any ajax status or result.
Thank you in advance for your help.
I found where the issue is :
$query3="SELECT email_login FROM users WHERE user_id = '".$hasshopuser_id"'";
it should be this instead :
$query3="SELECT email_login FROM users WHERE user_id = ".$hasshopuser_id;

Insert directory path of images in a table with FK [MySQL]

I'm trying to insert directory path of images in a table with FK (MySQL) using PHP-PDO, but I'm receiving this error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (bd-veiculos.fotos, CONSTRAINT fk_fotos_veiculos FOREIGN KEY (veiculos_idveiculos) REFERENCES mydb.veiculos (idveiculos) ON DELETE NO ACTION ON UPDATE NO ACTION)
This is my table:
I'm building a CRUD in php, I've got a table with informations of cars as below:
I've got a submit button called 'AddImages' When I click it, I'm sending via POST the ID of car that I want to change, this is the php page that I send...
uploadimageform.php:
after that I choose some images then I click submit and send the informations to the next php code:
<?php
include "dbconfig.php";
if(isset($_POST['submit'])){
$id = trim(strip_tags($_POST['id']));
# INFO IMAGEM
$file = $_FILES['img'];
$numFile = count(array_filter($file['name']));
# PASTA
$folder = 'uploads';
# REQUISITOS
$permite = array('image/jpeg', 'image/png');
$maxSize = 1024 * 1024 * 5;
# MENSAGENS
$msg = array();
$errorMsg = array(
1 => 'O arquivo no upload é maior do que o limite definido em upload_max_filesize no php.ini.',
2 => 'O arquivo ultrapassa o limite de tamanho em MAX_FILE_SIZE que foi especificado no formulário HTML',
3 => 'o upload do arquivo foi feito parcialmente',
4 => 'Não foi feito o upload do arquivo'
);
if($numFile <= 0)
echo 'Selecione uma Imagem!';
else{
for($i = 0; $i < $numFile; $i++){
$name = $file['name'][$i];
$type = $file['type'][$i];
$size = $file['size'][$i];
$error = $file['error'][$i];
$tmp = $file['tmp_name'][$i];
$extensao = #end(explode('.', $name));
$novoNome = rand().".$extensao";
if($error != 0)
$msg[] = "<b>$name :</b> ".$errorMsg[$error];
else if(!in_array($type, $permite))
$msg[] = "<b>$name :</b> Erro imagem não suportada!";
else if($size > $maxSize)
$msg[] = "<b>$name :</b> Erro imagem ultrapassa o limite de 5MB";
else{
if(move_uploaded_file($tmp, $folder.'/'.$novoNome)):
$msg[] = "<b>$name :</b> Upload Realizado com Sucesso!";
$imgpath[] = $folder.'/'.$novoNome;
else:
$msg[] = "<b>$name :</b> Desculpe! Ocorreu um erro...";
endif;
}
foreach($msg as $pop)
echo $pop.'<br>';
}
}
try
{
$sql = "INSERT INTO fotos (tbl_imagecar) VALUES ";
foreach ($imgpath as $path)
{
$sql .= " ('$path'),";
}
$sql = substr ($sql,0,strlen ($sql)-1);
$result = $DB_con->exec($sql);
echo "Dados criados com sucesso.<br><br>";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
<br><br>
INDEX
<a href="read.php" title""=>LISTAR</a>
Here's the query that I'm trying use to put the informations in the DB:
INSERT INTO fotos SET `tbl_imagecar` = 'uploads/19350.JPG', `veiculos_idveiculos` = (SELECT idveiculos FROM veiculos WHERE idveiculos = 3
from there I can not progress in my code. (Sorry for my bad English)
You are getting database foreign key voilation error. To fix this
Your field
mydb.veiculos (idveiculos)
needs to be first inserted/updated with same value(for example 13232) ,
which you are trying to insert into table field
bd-veiculos.fotos.veiculos_idveiculos

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

cant show up my image php from a DB

the problem is when it does return the binary file, pls help me
<!DOCTYPE html>
<html>
<head>
<title>Tienda Online</title>
<FORM action="upload_imagen.php" enctype="multipart/form-data" method="POST">
<input type="file" name="imagen"> Buscar imagen
<input type="submit" value="Buscar">
</FORM>
<div id="visualizar">
</div>
<form action="mostrar_imagen.php" method="POST">
<input type="text" name="valor" >
<input type="submit" value="mostrar">
</form>
</html>
upload_imagen.php this file upload an image and does storage in a DB
<?php
// Conexion a la base de datos
require "db_model.php";
class upload extends db_model {
function whatever() {
// Comprobamos si ha ocurrido un error.
if (!isset($_FILES["imagen"]) || $_FILES["imagen"]["error"] > 0) {
echo "Ha ocurrido un error.";
} else {
var_dump($_FILES["imagen"]);
// Verificamos si el tipo de archivo es un tipo de imagen permitido.
// y que el tamaño del archivo no exceda los 16MB
$permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
$limite_kb = 16384;
if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 1024) {
// Archivo temporal
$imagen_temporal = $_FILES['imagen']['tmp_name'];
// Tipo de archivo
$tipo = $_FILES['imagen']['type'];
// Leemos el contenido del archivo temporal en binario.
$fp = fopen($imagen_temporal, 'r+b');
$data = fread($fp, filesize($imagen_temporal));
fclose($fp);
//Podríamos utilizar también la siguiente instrucción en lugar de las 3 anteriores.
// $data=file_get_contents($imagen_temporal);
// Escapamos los caracteres para que se puedan almacenar en la base de datos correctamente.
$data = mysql_real_escape_string($data);
// Insertamos en la base de datos.
$this->query ="INSERT INTO imagenes (imagen, tipo_imagen) VALUES ('$data', '$tipo')";
$resultado = $this->execute_query();
if ($resultado) {
echo "El archivo ha sido copiado exitosamente.";
} else {
echo "Ocurrió algun error al copiar el archivo.";
}
} else {
echo "Formato de archivo no permitido o excede el tamaño límite de $limite_kb Kbytes.";
}
}
}
}
$obj = new upload();
$obj->whatever();
?>
mostrar_imagen.php this section retrives the image in binary format, then i want to show it, so i read that i need a header and send it the type of image it is for example .jpg, .gif but i dont know if a i have an error
<?php
require 'db_model.php';
class mostrar extends db_model {
function __construct()
{
$id = $_POST['valor'];
$this->query = "SELECT imagen, tipo_imagen
FROM imagenes
WHERE imagen_id=$id";
$datos = $this->execute_query_as();
$imagen = $datos['imagen']; // Datos binarios de la imagen.
$tipo = $datos['tipo_imagen']; // Mime Type de la imagen.
// Mandamos las cabeceras al navegador indicando el tipo de datos que vamos a enviar.
---- > my problem is here, i guess
header("Content-type: image/jpg");
echo $imagen;
// A continuación enviamos el contenido binario de la imagen.
}
}
$obj = new mostrar();
?>
db_model.php
<?php
/**
* clase de la base de datos
*/
include_once('config.php');
class db_model
{
private $db_host = "localhost";
private $db_user = "root";
private $db_pass = "";
protected $db_name = "tienda_cartas";
protected $query;
protected $rows = array();
private $conection;
private function open_conection()
{
$this->conection = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if ($this->conection->connect_errno) {
echo "error al conectar";
die();
} else {
echo "conectado";
}
}
private function close_conection() {
$this->conection->close();
}
protected function execute_query() {
$this->open_conection();
$result = $this->conection->query($this->query);
if(!$result){
echo "no se pudo ejecutar el sql";
}
$this->close_conection();
return $result;
header("location:index.php");
}
protected function execute_query_as() {
$this->open_conection();
$result = $this->conection->query($this->query);
if(!$result){
echo "no se pudo ejecutar el sql";
}
$array_as = $result->fetch_assoc();
if(!$array_as){
echo "no hay incidencias";
die();
}
$this->close_conection();
return $array_as;
}
}
?>
This could be your problem:
$data = mysql_real_escape_string($data);
In your classes you use mysqli_* functions, but this one belongs to the deprecated mysql_* functions. When you call it it will automatically try to open a new database connection with mysql_connect(), which will fail because it doesn't have any information about your host. mysql_real_escape_string() will then return false:
Warning: mysql_real_escape_string(): A link to the server could not be established in test.php on line 2
bool(false)
Just remove the line, escaping binary data will most probably ruin it anyway. Instead you should use prepared statements to prevent SQL injections.

Categories