There is a form ("Add car model"). I write in it for example: Model: Gelentvagen, Description: Cool jeep. And ship photo. I send it via POST to "process.php" in DB (Denver, php 5.2.12). In him:

$json=normJsonStr(json_encode($_POST)); // где, normJsonStr - это функция для отображения кириллицы. $sql = "INSERT INTO car_models (model_name, photo, opisanie, marka_id, json)values('$mod_name','$file_name','$opisanie', $marka_id, '$json')"; 

In the database, in the json field is inserted:

{"target":"add_model","model_name":"Гелентваген","opisanie":"Классный джип","marka_id":"11"}

A photo inside is not inserted!

Although in the usual field "photo" there is a photo of Gelentvagen!

How to make it appear in json'e?

Update

In a hurry, completely forgot! Sorry!

The photo comes to the database through $_FILES .

 $mod_name=@$_POST['model_name']; $opisanie=@$_POST['opisanie']; $marka_id=@$_POST['marka_id']; $json=normJsonStr(json_encode($_POST)); $file_name=null; $file_error=@$_FILES['photo_file']['error']; if($file_error==0){ $file_name=@$_FILES['photo_file']['name']; $file_tmp_name=@$_FILES['photo_file']['tmp_name']; move_uploaded_file($file_tmp_name,"../uploads/$file_name"); } 

Where at the output he gets $file_name - which is inserted into the INSERT. Therefore, it does not cling. Now I try to combine them - it does not work.

Maybe you have thoughts?

  • JSON photo will not be displayed. This is a text format for exchanging data. In the 'photo' field you have a link to the file. But, in JSON, you don’t have this link for some reason. Only the description of the car. - Streletz
  • And further. Better stop using Denwer. This is a terrible quality platform. In addition, it has not really developed for a long time (the last change on the office website dates back to June 2, 2013). - Streletz
  • 1) Yes, the name is stored there - "2.jpg"; That is the name I need. - aiba
  • 2) Thanks for the advice! I think soon go to OpenServer! - aiba

2 answers 2

  1. Use multipart / form-data ( https://ru.wikipedia.org/wiki/Multipart/form-data )
  2. Use the file transfer guide to the server:

a) http://javascript.ru/blog/gordon-freeman/AJAX-otpravka-fajla-Kak-otpravit-fajl-s-pomoshu-Ajax-Kak-otpravit-fajl-javasrip b) https://wpcafe.org / hacks / ajax-zagruzka-faylov-na-server-s-pomoshhyu-jquery /

I like working with jQuery (below - the text from the site):

 // Переменная куда будут располагаться данные файлов var files; // Вешаем функцию на событие // Получим данные файлов и добавим их в переменную $('input[type=file]').change(function(){ files = this.files; }); 

This is a form field handler that accepts the file to load.

And then - file transfer to the processing script:

 // Вешаем функцию ан событие click и отправляем AJAX запрос с данными файлов $('.submit.button').click(function( event ){ event.stopPropagation(); // Остановка происходящего event.preventDefault(); // Полная остановка происходящего // Создадим данные формы и добавим в них данные файлов из files var data = new FormData(); $.each( files, function( key, value ){ data.append( key, value ); }); // Отправляем запрос $.ajax({ url: './submit.php?uploadfiles', type: 'POST', data: data, cache: false, dataType: 'json', processData: false, // Не обрабатываем файлы (Don't process the files) contentType: false, // Так jQuery скажет серверу что это строковой запрос success: function( respond, textStatus, jqXHR ){ // Если все ОК if( typeof respond.error === 'undefined' ){ // Файлы успешно загружены, делаем что нибудь здесь // выведем пути к загруженным файлам в блок '.ajax-respond' var files_path = respond.files; var html = ''; $.each( files_path, function( key, val ){ html += val +'<br>'; } ) $('.ajax-respond').html( html ); } else{ console.log('ОШИБКИ ОТВЕТА сервера: ' + respond.error ); } }, error: function( jqXHR, textStatus, errorThrown ){ console.log('ОШИБКИ AJAX запроса: ' + textStatus ); } }); }); 

Further - variations on json_encode - i.e. on the server side, we find the key for the file and de-serialize it or write to the database as a BLOB.

The output - in the opposite direction - from the BLOB to the serialized view and - to the output.

But I warn you - this is not the way of the Jedi! Better to just put the pictures on the content server or just on the disk! Do not kill the performance of your database!

    The result was such an answer. I hope it will be useful to my colleagues! :-)

    1) From the form "index.php" send data to "process.php".

     <?php<br> if($target=="add_model"){<br> $mod_name=@$_POST['model_name']; // пришло название модели <br> $opisanie=@$_POST['opisanie']; // ее описание<br> $marka_id=@$_POST['marka_id']; // id марки<br> $file_name=null; // фото модели<br> $file_error=@$_FILES['photo_file']['error'];<br> if($file_error==0){<br> $file_name=@$_FILES['photo_file']['name'];<br> $file_tmp_name=@$_FILES['photo_file']['tmp_name'];<br> move_uploaded_file($file_tmp_name,"../uploads/$file_name");<br> } $far=array('model_name'=>$mod_name, 'opisanie'=>$opisanie, 'marka_id'=>$marka_id, 'photo'=>$file_name); <br> // создаем массив из поступивших данных<br> $json=normJsonStr(json_encode($far)); // обработка json <br> // В итоге в БД, в поле "json" получаем <br> // {"model_name":"C-Class Coupe","opisanie":"Купе класса G1.","marka_id":"11","photo":"5.jpg"}<br> $sql="SELECT * FROM car_models WHERE model_name='$mod_name'";<br> $res=mysqli_query($connect,$sql) or die(mysqli_error($connect));<br> $get=mysqli_fetch_assoc($res);<br> if($get['id']==0){ <br> $sql = "INSERT INTO car_models (model_name, photo, opisanie, marka_id, json)values('$mod_name','$file_name','$opisanie', $marka_id, '$json')";<br> $res = mysqli_query($connect,$sql);<br> echo "<script>window.location='index.php'</script>";<br> } <br> }<br> ?><br>