dongqing6755 2019-01-28 18:13
浏览 79
已采纳

使用JS和PHP将<div>保存到MySQL - 可能吗?

I have a HTML/PHP insert form and one of the entries needs to be refined. The entry in question is the "member".

For that I have the following code (credits to @Joe Warner ) which can be tested without the PHP here

Basically I save the <div> to a PHP variable, and print it. It works just fine.

<?php $msgs = "<div id='output'></div>"
echo $msgs; ?> 

This should be one single string of every member added.

The problem is that I can not push into MySQL with the others fields (every field is pushed when submitting). Seems that the variable is first assumed blank and only after getResults() it gets populated.

I know it is pretty messy, but for now the form cannot be changed.

Any tips?

const optionsSelect = [{
    id: 1,
    title: 'Mr'
  },
  {
    id: 2,
    title: 'Mrs'
  }
];

function getResults() {
  const { selects, inputs } = getInputs();

  return selects.reduce((acc, select, i) => {
    const { title, name } = getValuesFromElements(select, inputs[i]);
     msgs = (title && name) ? `${acc} ${title}. ${name}` : acc;
    document.getElementById("output").innerHTML = msgs; 
    return (title && name) ? `${acc} ${title}. ${name}` : acc;
  }, '');
}

function getValuesFromElements(select, {value: name}) {
  const { title } = optionsSelect[select.value - 1];

  return {title, name};
}

function getContainerElements(query) {
  return Array.from(document.querySelectorAll(`#container > ${query}`));
}

function getInputs() {
  const selects = getContainerElements('select');
  const inputs = getContainerElements('input');

  return {
    selects,
    inputs
  }
}


function addFields() {
  const { value: number } = document.getElementById('member');
  const container = document.getElementById('container');

  while (container.hasChildNodes()) {
    container.removeChild(container.lastChild);
  }

  for (let i = 0; i < number; i++) {
    const select = document.createElement('select');
    for (let j = 0; j < optionsSelect.length; j++) {
      const options = document.createElement('option');
      options.value = optionsSelect[j].id;
      options.text = optionsSelect[j].title;
      select.appendChild(options);
    }
    container.appendChild(select);
    container.appendChild(document.createTextNode(' -> Name ' + (i + 1)));
    const input = document.createElement('input');
    input.type = 'text';
    container.appendChild(input);
    container.appendChild(document.createElement('br'));
  }
}

<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
<a href="#" onclick="console.log(getResults())">Log results</a>
<div id="container"></div>
<?php $msgs = "<div id='output'></div>"
echo $msgs; ?> 

EDIT

I tried to add a second button linked to a PHP function in order to get the current value of $msgs but still doesnt work. It passes the MySQL insertion ("Record updated successfully") but still saves only blank in the DB.

<a href="index.php?msgs=true">Insert into DB</a>

<?php
 $msgs = "<div id='asservat'></div>";
 echo $msgs;

 function insertMsgs() {
   $server = 'myserver';
   $user = 'myuser';
   $pass = 'mypass';
   $db = 'mydb';
   $conn=mysqli_connect($server, $user, $pass, $db);
   if (mysqli_connect_errno()) {
     echo ("Connection failed: " . mysqli_connect_error());
   }
   $sql= "UPDATE mytable SET myfield='$msgs' WHERE member=blabla";
   if (mysqli_query($conn, $sql)) {
       echo "Record updated successfully";
   } else {
       echo ("Error updating record: " . mysqli_error($conn));
   }
   mysqli_close($conn);
}

if (isset($_GET['msgs'])) {
  insertMsgs();
} 
  • 写回答

1条回答 默认 最新

  • dougan5772 2019-02-11 18:37
    关注

    I managed with following code:

    get_names.html

    <head>
    <script src="jquery-3.3.1.min.js"></script>
    </head>
    <script type='text/javascript'>
        const optionsSelect = [{
        id: 1,
        title: 'Mr'
        },
        {
        id: 2,
        title: 'Mrs'
        }
        ];
        function getResults() {
        const { selects, inputs } = getInputs();
    
        return selects.reduce((acc, select, i) => {
        const { title, name } = getValuesFromElements(select, 
    inputs[i]);
        msg = (title && name) ? `${acc} ${title}. ${name}` : acc;
        document.getElementById("asservat").innerHTML = msg;
        var msgs = msg;
        //return (title && name) ? `${acc} ${title}. ${name}` : acc;
        return msgs;
        }, '');
        }
    
        function getResultsAsArray() {
        const { selects, inputs } = getInputs();
    
        const getFieldValues = (select, i) => {
        const { title, name } = getValuesFromElements(select, 
     inputs[i]);
    
        return (title && name) ? `${title}. ${name}` : '';
        };
    
        return selects.map(getFieldValues).filter(Boolean);
        }
    
        function getValuesFromElements(select, {value: name}) {
        const { title } = optionsSelect[select.value - 1];
    
        return {title, name};
        }
    
        function getContainerElements(query) {
        return Array.from(document.querySelectorAll(`#container > 
    ${query}`));
        }
    
        function getInputs() {
        const selects = getContainerElements('select');
        const inputs = getContainerElements('input');
    
        return {
        selects,
        inputs
        }
        }
        function addFields() {
        const { value: number } = document.getElementById('member');
        const container = document.getElementById('container');
    
        while (container.hasChildNodes()) {
        container.removeChild(container.lastChild);
        }
    
        for (let i = 0; i < number; i++) {
        const select = document.createElement('select');
        for (let j = 0; j < optionsSelect.length; j++) {
          const options = document.createElement('option');
          options.value = optionsSelect[j].id;
          options.text = optionsSelect[j].title;
          select.appendChild(options);
        }
        container.appendChild(select);
        container.appendChild(document.createTextNode(' -> Name ' + (i + 1)));
        const input = document.createElement('input');
        input.type = 'text';
        container.appendChild(input);
        container.appendChild(document.createElement('br'));
        }
        }
    
        </script>
    
        <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
        <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
        <a href="#" onclick="console.log(getResults())">Log results</a>
        <p id="container"></p>
        <div id="asservat"></div>
        <input type="button" value="Submit" onclick="post();">ajax<br />
        <script type="text/javascript">
        function post(){
        var name = getResults();
        $.post('return_names.php',{postname:name},
        function(data){
        $('#name').html(data);
        });
        return $('#name').html(data);
        }
        </script>
    

    return_names.php

        <?php
        function data() {
        $name = $_POST['postname'];
        echo "Name as string ->", $name, " <- here";
        return $name;
        }
        data();
        ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler