繁体   English   中英

是否可以为按钮分配动态变量? 在while循环中从查询中获取的每一行都会发生变化?

[英]Is it possible to assign a button a dynamic variable; that changes for each row fetched from the query in a while loop?

我有一个query ,使用query while loop为找到的每一行生成一个表。 但是我的目标是让每个row与添加按钮按下时有两个变量和INSERTS另一个表中的新行。 我相信我的代码无法正常工作的原因在于系统无法识别哪个添加按钮属于哪一行。 我尝试将每行的UserID分配给button id但仍然无法执行INSERT (它不会产生任何错误)。

有什么建议可以实现我的目标吗?

HTML + PHP:

<div class="RightBody">
  <form name="search_form" method="post" action="" >
    <input type="text" name="search_box" value="" placeholder="Search for skills or a user." />
    <input type="submit" name="search" value="Search" />
  </form>
  <table width="100%" cellpadding="5" cellspacing="5" >
        <p><strong>Search Results:</strong></p>
        <tr>
          <td></td>
          <td><strong>First Name</strong></td>
          <td><strong>Last Name</strong></td>
          <td><strong>Job Role</strong></td>
          <td><strong>Skill(s)</strong></td>
        </tr>
        <?php
    if(isset($_POST['search']))
    {
      if(@mysqli_num_rows($search_query)!=0){
          do{ 
            if(isset($_POST['adduser'])){
              $AddUserID = $search_rs['UserID'];
              $AddProjectID = $Project;

              $sql = $con->query("INSERT INTO userprojects (UserID, ProjectID) VALUES  ('$AddUserID', '$AddProjectID')") or die(mysqli_error($con)); 
            }?>
            <tr>
              <td>
                <input type="submit" name="adduser" value="Add"  id="<?php echo htmlspecialchars($search_rs['UserID']); ?>"/>
              </td>
              <td><?php echo $search_rs['Fname']; ?></td>
              <td><?php echo $search_rs['Lname']; ?></td>
              <td><?php echo $search_rs['JobRole']; ?></td>
              <td><?php echo $search_rs['Description']; ?></td>
            </tr>
            <?php   
          } 
          while ($search_rs=mysqli_fetch_assoc($search_query));
      } 
      else 
      {
        echo "No results found";
      }
    }?>
        </table>
</div>

PHP:

<?php 
$value = isset($_POST['search_box']) ? $_POST['search_box'] : '';

$search_sql = "SELECT * FROM User INNER JOIN UserSkills ON User.UserId = UserSkills.UserId JOIN Skills ON UserSkills.SkillId = Skills.SkillId WHERE Description LIKE '%".$value."%' OR FName LIKE '%".$value."%' OR LName LIKE '%".$value."%' OR JobRole LIKE '%".$value."%' GROUP BY Description" or die(mysqli_error($con));

$search_query = mysqli_query($con, $search_sql);
if(mysqli_num_rows($search_query) !=0) {
  $search_rs = mysqli_fetch_assoc($search_query);
}

您需要在<form>指定action属性。

同样, htmlspecialchars(value) 返回一个字符串,而不是输出它 ,所以不要使用:

<?php htmlspecialchars($search_rs['UserID']);

你需要使用

<?php echo htmlspecialchars($search_rs['UserID']);

与其使用submit按钮,不如将其更改为标准按钮,并为每个按钮提供您提到的变量作为数据值。

/* in the php loop */
<input type='button' class='dynbttn' data-uid='{$AddUserID}' data-pid='{$AddProjectID}' value='Add User' />

/* javascript listeners */
var col=document.querySelectorAll('input.dynbttn');
for( var n in col )if( col[n].nodeType==1 ) col[n].onclick=function(e){
    var el=typeof(e.target)!='undefined' ? e.target : e.srcElement;
    var uid=el.dataset.uid;
    var pid=el.dataset.pid;
    alert( 'Use ajax to submit the values:'+uid+','+pid );
};

例:

<script>
    function ajax(m,u,p,c){
        /*
            m=method
            u=url
            p=params {name:value}
            c=callback
        */
        var xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if( xhr.readyState==4 && xhr.status==200 )c.call(this,xhr.response);
        };

        var params=[];
        for( var n in p )params.push(n+'='+p[n]);

        switch( m.toLowerCase() ){
            case 'post':
                p=params;
            break;
            case 'get':
                u+='?'+params;
                p=null;
            break;  
        }

        xhr.open( m.toUpperCase(), u, true );
        xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
        xhr.send( p );
    }

    function callback(r){
        alert(r);
    }

    function bindEvents(){
        var col=document.querySelectorAll('input.dynbttn');
        for( var n in col )if( col[n].nodeType==1 ) col[n].onclick=function(e){
            var el=typeof(e.target)!='undefined' ? e.target : e.srcElement;
            var uid=el.dataset.uid;
            var pid=el.dataset.pid;

            ajax.call( this, 'post', '/path/to/script.php', { uid:uid,pid:pid }, callback );
        };
    }   
    document.addEventListener( 'DOMContentLoaded',bindEvents,false );
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM