Я строю сайт с помощью Dreamweaver CS6, так как мои возможности кодирования немного выше минимальных. Мне удалось заставить работать логин пользователя и регистрацию нового пользователя, а также запросить логин для страницы. Я испытываю трудности при попытке присоединить пользователя к записям, которые они помещают в другие таблицы. У меня есть таблица с именем «users», в которой «user_login» и «user_id» используются для входа на страницу. Я хочу сделать, чтобы при отправке новой записи кнопка «user_login» сравнивала с «user_id», а затем помещала это числовое значение в поле «character_owner» таблицы «символов».
Вот страница и форма с кнопкой:
<?php require_once('Connections/DLP_RPG.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
session_start();
}
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
$logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
//to fully log out a visitor we need to clear the session varialbles
$_SESSION['MM_Username'] = NULL;
$_SESSION['MM_UserGroup'] = NULL;
$_SESSION['PrevUrl'] = NULL;
unset($_SESSION['MM_Username']);
unset($_SESSION['MM_UserGroup']);
unset($_SESSION['PrevUrl']);
$logoutGoTo = "index.php";
if ($logoutGoTo) {
header("Location: $logoutGoTo");
exit;
}
}
?>
<?php
if (!isset($_SESSION)) {
session_start();
}
$MM_authorizedUsers = "0";
$MM_donotCheckaccess = "true";
// *** 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 == "") && true) {
$isValid = true;
}
}
return $isValid;
}
$MM_restrictGoTo = "index.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_insert"])) && ($_POST["MM_insert"] == "PlaySystemForm")) {
$insertSQL = sprintf("INSERT INTO characters (character_name1, character_occupation, play_system, character_owner) VALUES (%s, %s, %s, %s)",
GetSQLValueString($_POST['character_name'], "text"),
GetSQLValueString($_POST['character_type1'], "int"),
GetSQLValueString($_POST['play_system'], "text"),
GetSQLValueString($_POST['CharacterOwner'], "int"));
mysql_select_db($database_DLP_RPG, $DLP_RPG);
$Result1 = mysql_query($insertSQL, $DLP_RPG) or die(mysql_error());
$insertGoTo = "character_input.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
mysql_select_db($database_DLP_RPG, $DLP_RPG);
$query_UserLoginForm = "SELECT * FROM users";
$UserLoginForm = mysql_query($query_UserLoginForm, $DLP_RPG) or die(mysql_error());
$row_UserLoginForm = mysql_fetch_assoc($UserLoginForm);
$totalRows_UserLoginForm = mysql_num_rows($UserLoginForm);
mysql_select_db($database_DLP_RPG, $DLP_RPG);
$query_PlaySystem = "SELECT play_systems.play_system FROM play_systems";
$PlaySystem = mysql_query($query_PlaySystem, $DLP_RPG) or die(mysql_error());
$row_PlaySystem = mysql_fetch_assoc($PlaySystem);
$totalRows_PlaySystem = mysql_num_rows($PlaySystem);
mysql_select_db($database_DLP_RPG, $DLP_RPG);
$query_characters = "SELECT * FROM characters";
$characters = mysql_query($query_characters, $DLP_RPG) or die(mysql_error());
$row_characters = mysql_fetch_assoc($characters);
$totalRows_characters = mysql_num_rows($characters);
mysql_select_db($database_DLP_RPG, $DLP_RPG);
$query_character_type = "SELECT * FROM character_type1";
$character_type = mysql_query($query_character_type, $DLP_RPG) or die(mysql_error());
$row_character_type = mysql_fetch_assoc($character_type);
$totalRows_character_type = mysql_num_rows($character_type);
?>
<!doctype html>
<html>
<head>
</head>
<body>
<div class="content">
<h1>Starting a new character</h1>
<p>The first thing to do when starting a new character is to select the play system from a drop down list</p>
<form action="<?php echo $editFormAction; ?>" method="POST" name="PlaySystemForm" id="PlaySystemForm">
<table width="500" border="1">
<tr>
<th width="129" scope="row">System:</th>
<td width="355"><label for="play_system2"></label>
<select name="play_system" id="play_system2">
<?php
do {
?>
<option value="<?php echo $row_PlaySystem['play_system']?>"><?php echo $row_PlaySystem['play_system']?></option>
<?php
} while ($row_PlaySystem = mysql_fetch_assoc($PlaySystem));
$rows = mysql_num_rows($PlaySystem);
if($rows > 0) {
mysql_data_seek($PlaySystem, 0);
$row_PlaySystem = mysql_fetch_assoc($PlaySystem);
}
?>
</select></td>
</tr>
<tr>
<th scope="row">Name:</th>
<td><span id="sprytextfield1">
<label for="character_name"></label>
<input name="character_name" type="text" id="character_name" size="25" maxlength="128">
<span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldMinCharsMsg">Minimum number of characters not met.</span><span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span></span></td>
</tr>
<tr>
<th scope="row">Type:</th>
<td><label for="character_type1"></label>
<select name="character_type1" id="character_type1">
<?php
do {
?>
<option value="<?php echo $row_character_type['character_type1_id']?>"<?php if (!(strcmp($row_character_type['character_type1_id'], $row_PlaySystem['play_system']))) {echo "selected=\"selected\"";} ?>><?php echo $row_character_type['character_type1']?></option>
<?php
} while ($row_character_type = mysql_fetch_assoc($character_type));
$rows = mysql_num_rows($character_type);
if($rows > 0) {
mysql_data_seek($character_type, 0);
$row_character_type = mysql_fetch_assoc($character_type);
}
?>
</select></td>
</tr>
</table>
<input name="CharacterOwner" type="hidden" id="CharacterOwner" value="<?php echo $row_UserLoginForm['user_id']; ?>">
<p>
<input type="submit" name="NewCharacterSubmit" id="NewCharacterSubmit" value="Create character">
</p>
<input type="hidden" name="MM_insert" value="PlaySystemForm">
</form>
</body>
</html>
<?php
mysql_free_result($UserLoginForm);
mysql_free_result($PlaySystem);
mysql_free_result($characters);
mysql_free_result($character_type);
?>
<input name="CharacterOwner" type="hidden" id="CharacterOwner" value="<?php echo $row_UserLoginForm['user_id']; ?>">
Это код, который я считаю проблемой. Независимо от того, в кого я вошел, например, когда я нажимаю на кнопку submit, я получаю только результат «1», который, я думаю, возвращает результат TRUE, но мне нужен фактический числовой результат, чтобы заполнить поле character_owner, чтобы пользователи будет видеть только то, что они делают.
Я думаю, что я это исправил и вот как:
Я создал этот запрос (я думаю, что я использую правильную терминологию):
mysql_select_db($database_DLP_RPG, $DLP_RPG);
$query_CharacterOwner = "SELECT * FROM users WHERE users.user_id =
(SELECT user_id FROM users WHERE user_login = '{$_SESSION['MM_Username']}')";
$CharacterOwner = mysql_query($query_CharacterOwner, $DLP_RPG) or die(mysql_error());
$row_CharacterOwner = mysql_fetch_assoc($CharacterOwner);
$totalRows_CharacterOwner = mysql_num_rows($CharacterOwner);
Других решений пока нет …