如何从PHP中的列表框进行自动填充

时间:2015-06-02 08:59:16

标签: php mysql textbox listbox

如果你不介意,我需要一些帮助。我正在为学校创建一个简单的常见问题网站,我添加了一个管理部分,他可以在其中更改或删除用户。我在php中创建了一个表单,它有一个列表框(lst_id),它可以获取数据库中的所有id。问题是:当我从列表框中选择ID时,如何自动填充文本框?文本框为:txt_name,txt_password和txt_email。

我正在使用PHP和MySQL。

提前致谢, Slaxer13

<?php require_once('Connections/FAQ.php'); ?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "1";
$MM_donotCheckaccess = "false";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && false) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "login_errado.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
  $updateSQL = sprintf("UPDATE tbl_utilizadores SET utilizador=%s, password=%s, email=%s WHERE id_utilizador=%s",
                       GetSQLValueString($_POST['utilizador'], "text"),
                       GetSQLValueString($_POST['password'], "text"),
                       GetSQLValueString($_POST['email'], "text"),
                       GetSQLValueString($_POST['id_utilizador'], "int"));

  mysql_select_db($database_FAQ, $FAQ);
  $Result1 = mysql_query($updateSQL, $FAQ) or die(mysql_error());

  $updateGoTo = "login.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}

$colname_Utilizadores = "-1";
if (isset($_GET['id_utilizador'])) {
  $colname_Utilizadores = $_GET['id_utilizador'];
}
mysql_select_db($database_FAQ, $FAQ);
$query_Utilizadores = sprintf("SELECT * FROM tbl_utilizadores WHERE id_utilizador = %s", GetSQLValueString($colname_Utilizadores, "int"));
$Utilizadores = mysql_query($query_Utilizadores, $FAQ) or die(mysql_error());
$row_Utilizadores = mysql_fetch_assoc($Utilizadores);
$totalRows_Utilizadores = mysql_num_rows($Utilizadores);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Atualizar Registo</title>
</head>

<body>
<h1>Atualizar Registo</h1>
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
  <table align="center">
    <tr valign="baseline">
      <td nowrap align="right">ID:</td>
      <td><label for="select"></label>
        <label for="select2"></label>
        <select name="select" class="textfields" id="ddl_id">
            <option id="0">-- Selecione o ID --</option>
            <?php
                require("dbconfig.php");
                $get_ids = mysql_query("SELECT * FROM tbl_utilizadores");
                while($vertodos = mysql_fetch_array($get_ids)){ 
            ?>
            <option id="<?php echo $vertodos['id_utilizador'];?>"><?php echo $vertodos['utilizador'] ?></option>
            <?php } ?>
      </select>
      </td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Utilizador:</td>
      <td><input type="text" name="utilizador" value="<?php echo htmlentities($row_Utilizadores['utilizador'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Password:</td>
      <td><input type="text" name="password" value="<?php echo htmlentities($row_Utilizadores['password'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Email:</td>
      <td><input type="text" name="email" value="<?php echo htmlentities($row_Utilizadores['email'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Admin:</td>
      <td><input type="text" name="administrator" value="<?php echo htmlentities($row_Utilizadores['administrator'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">&nbsp;</td>
      <td><input type="submit" value="Atualizar Registo"></td>
    </tr>
  </table>
  <input type="hidden" name="MM_update" value="form1">
  <input type="hidden" name="id_utilizador" value="<?php echo $row_Utilizadores['id_utilizador']; ?>">
</form>
</body>
</html>
<?php
mysql_free_result($Utilizadores);
?>

4 个答案:

答案 0 :(得分:0)

我会使用带有ID变量的Javascript向服务器发送一个AJAX调用,以检索所有相应的值,然后使用JQuery更新它们 - 在不重新加载页面的情况下执行此操作

答案 1 :(得分:0)

最简单的解决方案是在更改复选框时在url中设置lst_id 然后在你的代码中检查是否设置了列表ID,如果是,则获取id的所有条目并将其显示在文本框中。 javascript代码:

$("#lst_id").on('change',function(){
        window.loaction = window.location.href+'?list_id='+$("#lst_id").val();

})

PHP代码:

     if(isset($_GET['lst_id'])){
               // write query to fetch entries for that list id
      }

而不仅仅是设置文本框的值

答案 2 :(得分:0)

<script type="text/javascript"> 
//<![CDATA[ 

$(document).ready(function() {
    $("#idoftextbox").on('change',function(){
        GetData();
    })
}

function GetData() {
    $.ajax({ 
        url: 'linktophpfilewithconnectiontodatabase.php',
        data: "{ id: '" + $('#idoftextbox').val() + "' } ",
        contentType: "application/json; charset=utf-8",
        type: 'post',
        success: fillboxes,
        error: showError
    });
}

function showError(data, status) {
//do your stuff
}

function fillboxes(data, status) {
//with your php you should have sent back a json encoded string, download a debugger of your choice (ie firefox) and find out which attribute of data you need to decode, then just 
      $("#textboxid1").val(extractedvalues[0]);
      $("#textboxid2").val(extractedvalues[1]);
}

//]]>
</script>

答案 3 :(得分:0)

查看用户:(名为utilizadores.php)

<?php
header('Content-Type: text/html; charset=ISO-8859-1');/*Caracteres especiais*/ 
?>
<?php require_once('Connections/FAQ.php'); ?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "1";
$MM_donotCheckaccess = "false";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && false) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "acesso_negado.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_FAQ, $FAQ);
$query_Utilizadores = "SELECT * FROM tbl_utilizadores";
$Utilizadores = mysql_query($query_Utilizadores, $FAQ) or die(mysql_error());
$row_Utilizadores = mysql_fetch_assoc($Utilizadores);
$totalRows_Utilizadores = mysql_num_rows($Utilizadores);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<table border="1">
  <tr>
    <td>id_utilizador</td>
    <td>utilizador</td>
    <td>password</td>
    <td>email</td>
    <td>administrator</td>
    <td>p_nome</td>
    <td>u_nome</td>
  </tr>
  <?php do { ?>
    <tr>
      <td><a href="atualizar_registo.php?id_utilizador=<?php echo $row_Utilizadores['id_utilizador']; ?>"><?php echo $row_Utilizadores['id_utilizador']; ?></a></td>
      <td><?php echo $row_Utilizadores['utilizador']; ?></td>
      <td><?php echo $row_Utilizadores['password']; ?></td>
      <td><?php echo $row_Utilizadores['email']; ?></td>
      <td><?php echo $row_Utilizadores['administrator']; ?></td>
      <td><?php echo $row_Utilizadores['p_nome']; ?></td>
      <td><?php echo $row_Utilizadores['u_nome']; ?></td>
    </tr>
    <?php } while ($row_Utilizadores = mysql_fetch_assoc($Utilizadores)); ?>
</table>
</body>
</html>
<?php
mysql_free_result($Utilizadores);
?>

更新记录:(名为atualizar_registo.php)

<?php require_once('Connections/FAQ.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
  $updateSQL = sprintf("UPDATE tbl_utilizadores SET utilizador=%s, password=%s, email=%s, administrator=%s, p_nome=%s, u_nome=%s WHERE id_utilizador=%s",
                       GetSQLValueString($_POST['utilizador'], "text"),
                       GetSQLValueString($_POST['password'], "text"),
                       GetSQLValueString($_POST['email'], "text"),
                       GetSQLValueString($_POST['administrator'], "int"),
                       GetSQLValueString($_POST['p_nome'], "text"),
                       GetSQLValueString($_POST['u_nome'], "text"),
                       GetSQLValueString($_POST['id_utilizador'], "int"));

  mysql_select_db($database_FAQ, $FAQ);
  $Result1 = mysql_query($updateSQL, $FAQ) or die(mysql_error());

  $updateGoTo = "registos_teste.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}

$colname_Utilizadores = "-1";
if (isset($_GET['id_utilizador'])) {
  $colname_Utilizadores = $_GET['id_utilizador'];
}
mysql_select_db($database_FAQ, $FAQ);
$query_Utilizadores = sprintf("SELECT * FROM tbl_utilizadores WHERE id_utilizador = %s", GetSQLValueString($colname_Utilizadores, "int"));
$Utilizadores = mysql_query($query_Utilizadores, $FAQ) or die(mysql_error());
$row_Utilizadores = mysql_fetch_assoc($Utilizadores);
$totalRows_Utilizadores = mysql_num_rows($Utilizadores);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Actualizar Registo</title>
</head>

<body>
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
  <table align="center">
    <tr valign="baseline">
      <td nowrap align="right">Id_utilizador:</td>
      <td><?php echo $row_Utilizadores['id_utilizador']; ?></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Utilizador:</td>
      <td><input type="text" name="utilizador" value="<?php echo htmlentities($row_Utilizadores['utilizador'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Password:</td>
      <td><input type="text" name="password" value="<?php echo htmlentities($row_Utilizadores['password'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Email:</td>
      <td><input type="text" name="email" value="<?php echo htmlentities($row_Utilizadores['email'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Administrator:</td>
      <td><input type="text" name="administrator" value="<?php echo htmlentities($row_Utilizadores['administrator'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Primeiro Nome:</td>
      <td><input type="text" name="p_nome" value="<?php echo htmlentities($row_Utilizadores['p_nome'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td height="25" align="right" nowrap>Último Nome:</td>
      <td><input type="text" name="u_nome" value="<?php echo htmlentities($row_Utilizadores['u_nome'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">&nbsp;</td>
      <td><input type="submit" value="Update record"></td>
    </tr>
  </table>
  <input type="hidden" name="MM_update" value="form1">
  <input type="hidden" name="id_utilizador" value="<?php echo $row_Utilizadores['id_utilizador']; ?>">
</form>
<p>&nbsp;</p>
</body>
</html>
<?php
mysql_free_result($Utilizadores);
?>

有些东西是葡萄牙语(PT-PT),所以如果你需要翻译什么,请问我;)

和平 Slaxer13