Мне нужна помощь, если ты не против. Я создаю простой faq-сайт для школы, и я добавил раздел администратора, где он может изменять или удалять пользователей. Я создал форму в php, которая имеет один список (lst_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"> </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);
?>
Я бы отправил вызов AJAX на сервер, используя Javascript с переменной ID, чтобы получить все соответствующие значения, а затем обновить их с помощью JQuery — чтобы сделать это без перезагрузки страницы
Простейшее решение этой проблемы — установить lst_id в URL при смене флажка.
а затем в своем коде проверьте, установлен ли список идентификаторов, если да, то извлеките все записи для идентификатора и отобразите его в текстовых полях.
код 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
}
И чем просто установить значение для ваших текстовых полей
<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>
Просмотр пользователей: (называется 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"> </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> </p>
</body>
</html>
<?php
mysql_free_result($Utilizadores);
?>
Некоторые вещи на португальском (PT-PT), так что если вам нужно что-то перевести, просто спросите меня;)
Мир,
Slaxer13