2017-09-15 8 views
0

入力ボックス'brand name'JSONという形式を生成する簡単なフォームがあります。私はknockout.jsを使ってフォームからJSONを生成しました。今このデータをphpアクションファイルに入力すると、このJSONデータをテーブル'b_names''brand_name'のテーブルphpに挿入することができますか?knockoutによって生成されたJSONデータをmySqlテーブルに挿入するにはどうすればよいですか?

これは私のフォームです:

<button data-bind='click: addBrandName'>Add a drug</button> 
<form action="php/action.php"> 
    <table data-bind="foreach: brandNames"> 
     <tbody > 
     <td> 
      <label>Brand name</label> 
      <input type="text" data-bind='value: brandName'> 
     </td> 
     </tbody> 
    </table> 
    <button type="submit">Submit</button> 
</form> 
<p> 
    <button data-bind='click: save, enable: brandNames().length > 0'>Save to JSON</button> 
</p> 
<div> 
    <textarea data-bind='value: lastSavedJson' rows='10' cols='33'> 
    </textarea> 
</div> 

これはスクリプトです:

<script> 
    $(document).ready(function() { 
    var initialData = [ 
    ]; 

    var brandNamesModel = function(brandNames) { 
    var self = this; 
    self.brandNames = ko.observableArray(ko.utils.arrayMap(brandNames, function(drug) { 
     return { 
      brandName: drug.brandName }; 
    })); 

    self.addBrandName = function() { 
     self.brandNames.push({ 
      brandName: "" 
     }); 
    }; 

    self.save = function() { 
     self.lastSavedJson(JSON.stringify(ko.toJS(self.brandNames), null, 2)); 
    }; 

    self.lastSavedJson = ko.observable("") 
    }; 

    ko.applyBindings(new brandNamesModel(initialData));   
    }); 
</script> 

私はこのPHPの動作をしようとしていたし、確かにそれは働いていません。

$dbCon = mysqli_connect(localhost, $user, $password, $database) 
     or die ("error connecting database"); 
echo "Connected"; 

$data = file_get_contents($lastSavedJson); 
$arrat = json_decode($data, true); 

foreach($array as $row) 
{ 
    $sql = "INSERT INTO b_name(brand_name) VALUES('".$row["brandName"]."')"; 
    mysqli_query($bdCon, $sql); 
}; 

私はそれを理解しようとしていますが、どんな助けにも感謝します。ここではPHPなし はあなたのPHPでフォーム - fiddle

答えて

0

私はWern Anchetaというブログから最高の助けを得ました。それはすばらしい記事であり、彼はすべてのコードをそこに説明します。

htmlknockoutコード:

<div class="container" data-bind="load: loadData()"> 
    <div class="new_student"> 
     <input type="text" class="name" placeholder="name" data-bind="value: person_name, hasfocus: person_name_focus"/> 
     <input type="text" class="age" placeholder="age" data-bind="value: person_age"/> 

     <button data-bind="click: createPerson">Create</button>  
    </div> 

    <table data-bind="visible: people().length > 0" class="students"> 
     <thead> 
      <tr> 
       <th>Name</th> 
       <th>Age</th> 
       <th>Remove</th> 
       <th>Update</th> 
      </tr> 
     </thead> 
     <tbody data-bind="foreach: people"> 
      <tr> 
       <td> 
        <span data-bind="text: name, click: nameUpdating, visible: !nameUpdate()"></span> 
        <input type="text" class="name" data-bind="value: name, visible: nameUpdate, hasfocus: nameUpdate"> 
       </td> 
       <td> 
        <span data-bind="text: age, click: ageUpdating, visible: !ageUpdate()"></span> 
        <input type="text" class="age" data-bind="value: age, visible: ageUpdate, hasfocus: ageUpdate"> 
       </td> 
       <td><a href="#" data-bind="click: $root.removePerson">remove</a></td> 
       <td><a href="#" data-bind="click: $root.updatePerson">update</a></td> 
      </tr> 
     </tbody> 
    </table>  

    <button data-bind="click: echoPerson">echo</button> 
</div> 




<script> 
var personModel = function(id, name, age){ 
    var self = this; 
    this.id = ko.observable(id); 
    this.name = ko.observable(name); 
    this.age = ko.observable(age); 

    this.nameUpdate = ko.observable(false); 
    this.ageUpdate = ko.observable(false); 

    this.nameUpdating = function(){ 
     self.nameUpdate(true); 
    }; 
    this.ageUpdating = function(){ 
     self.ageUpdate(true); 
    }; 

}; 

var model = function(){ 

    var self = this; 
    this.person_name = ko.observable(""); 
    this.person_age = ko.observable(""); 
    this.people = ko.observableArray([]); 
    this.person_name_focus = ko.observable(true); 

    this.createPerson = function(){ 
     if(self.validatePerson()){ 

      var person = {'name' : this.person_name(), 'age' : this.person_age()}; 

      $.ajax(
       { 
        url: 'refresher_save.php', 
        type: 'POST', 
        data: {'student' : person, 'action' : 'insert'}, 
        success: function(id){ 
         console.log(this); 
         self.people.push(new personModel(id, self.person_name(), self.person_age())); 
         self.person_name(""); 
         self.person_age(""); 
        } 
       } 
      );   

     }else{ 
      alert("Name and age are required and age should be a number!"); 
     } 
    }; 

    this.validatePerson = function(){ 
     if(self.person_name() !== "" && self.person_age() != "" && Number(self.person_age()) + 0 == self.person_age()){ 
      return true; 
     } 
     return false; 
    }; 

    this.removePerson = function(person){ 

     $.post(
      'refresher_save.php', 
      {'action' : 'delete', 'student_id' : person.id()}, 
      function(response){ 

       self.people.remove(person); 
      } 
     ); 
    }; 


    this.updatePerson = function(person){ 
     var id = person.id(); 
     var name = person.name(); 
     var age = person.age(); 

     var student = {'id' : id, 'name' : name, 'age' : age}; 
     $.post(
      'refresher_save.php', 
      {'action' : 'update', 'student' : student} 

     ); 
    }; 

    this.loadData = function(){ 
     //fetch existing data from database 

     $.ajax({ 
      url : 'refresher_save.php', 
      dataType: 'json', 
      success: function(data){ 


       for(var x in data){ 
        var id = data[x]['id'] 
        var name = data[x]['name']; 
        var age = data[x]['age']; 
        self.people.push(new personModel(id, name, age)); 
       } 

      } 
     }); 
     /* 
     note: nothing would actually show up in the success function if the 
     data that was returned from the server isn't a json string 
     */ 
    }; 


    this.echoPerson = function(){ 
     console.log(ko.toJS(self.people())); 
    }; 

}; 

ko.applyBindings(new model()); 
</script> 

サーバー側phpからconnectinsertupdateここで

は、彼は私が探していた仕事をしていませんどのように彼のバージョンであります deleteデータは:

<?php 
$db = new MySqli('localhost', 'ashonko', '', 'tutorials'); 

$action = (!empty($_POST['action'])) ? $_POST['action'] : ''; 
$student = (!empty($_POST['student'])) ? $_POST['student'] : ''; 


if(!empty($student)){ 
    $name = $student['name']; 
    $age = $student['age']; 
} 

switch($action){ 

    case 'insert': 

     $db->query("INSERT INTO students SET name = '$name', age = '$age'"); 
     echo $db->insert_id; //last insert id 
    break; 

    case 'update': 

     $id = $student['id']; 
     $db->query("UPDATE students SET name = '$name', age = '$age' WHERE id = '$id'"); 
    break; 

    case 'delete': 

     $id = $_POST['student_id']; 
     $db->query("UPDATE students SET status = 0 WHERE id = '$id'"); 
    break; 

    default: 
     $students = $db->query("SELECT * FROM students WHERE status = 1"); 
     $students_r = array(); 
     while($row = $students->fetch_array()){ 

      $id = $row['id']; 
      $name = $row['name']; 
      $age = $row['age']; 
      $name_update = false; 
      $age_update = false; 
      $name_focus = false; 
      $age_focus = false; 

      $students_r[] = array(
       'id' => $id, 'name' => $name, 'age' => $age, 
       'nameUpdate' => $name_update, 'ageUpdate' => $age_update, 
       'nameHasFocus' => $name_focus, 'ageHasFocus' => $age_focus 
       ); 
     } 

     echo json_encode($students_r); 
    break; 
} 
?> 
1

親切に、このようにようにAJAX呼び出しを試してみてください

$.ajax({ 
     url: "your api url", 
     type: "post", 
     data: ko.toJSON(self), 
     contentType: "application/json", 
     success: function(data){ 
      console.log(data); 
      alert("success"); 
     }, 
     error:function(jqXHR, textStatus, errorThrown) { 
      alert("failure"); 
     } 
    }); 

の作業フィドルを使用すると、データは以下のようなPHPファイルで来たりされていないチェックすべきですブラウザのコンソールに&あなたがコンソールで送信したチェックデータが来ています。

print_r($_POST['data']); 
+0

はい、私はこれを保存したい'brand_name'フィールドの 'b_names'という表の入力に応じてヒンジします)。 – Ashonko

+0

ありがとうございますが、エラーを返します: '警告:file_get_contents()[function.file-get-contents]:ファイル名は空ではありません ' – Ashonko

+0

あなたのデータはあなたのPHPファイルには入っていません。これに対してajaxコールを使用できますか?あなたが私にあなたを送ることができると言うなら、jsonでphpにデータを送る方法をajaxコールで伝えることができます。 –

関連する問題