2015-05-25 4 views
3

Я постараюсь сделать это как можно более кратким, но любая помощь очень ценится. Мой уровень навыка немного выше минимального в PHP/MySQL, поэтому я использую Dreamweaver CS6, чтобы попытаться запустить мой сайт. Мне нужно ограничить данные, возвращаемые из базы данных, пользователю, который создал запись, поэтому я хотел повторно использовать информацию для входа, чтобы отслеживать, кто вводит данные.Попытка использовать поля MySQL в качестве ограничения для данных

<?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_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); 
 
?> 
 
<?php 
 
// *** Validate request to login to this site. 
 
if (!isset($_SESSION)) { 
 
    session_start(); 
 
} 
 

 
$loginFormAction = $_SERVER['PHP_SELF']; 
 
if (isset($_GET['accesscheck'])) { 
 
    $_SESSION['PrevUrl'] = $_GET['accesscheck']; 
 
} 
 

 
if (isset($_POST['UserLogin'])) { 
 
    $loginUsername=$_POST['UserLogin']; 
 
    $password=$_POST['UserPass']; 
 
    $MM_fldUserAuthorization = ""; 
 
    $MM_redirectLoginSuccess = "main.php"; 
 
    $MM_redirectLoginFailed = "UserRegistration.php"; 
 
    $MM_redirecttoReferrer = false; 
 
    mysql_select_db($database_DLP_RPG, $DLP_RPG); 
 
    
 
    $LoginRS__query=sprintf("SELECT user_login, user_pass FROM users WHERE user_login=%s AND user_pass=%s", 
 
    GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); 
 
    
 
    $LoginRS = mysql_query($LoginRS__query, $DLP_RPG) or die(mysql_error()); 
 
    $loginFoundUser = mysql_num_rows($LoginRS); 
 
    if ($loginFoundUser) { 
 
    $loginStrGroup = ""; 
 
    
 
\t if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();} 
 
    //declare two session variables and assign them 
 
    $_SESSION['MM_Username'] = $loginUsername; 
 
    $_SESSION['MM_UserGroup'] = $loginStrGroup; \t  
 

 
    if (isset($_SESSION['PrevUrl']) && false) { 
 
     $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; \t 
 
    } 
 
    header("Location: " . $MM_redirectLoginSuccess); 
 
    } 
 
    else { 
 
    header("Location: ". $MM_redirectLoginFailed); 
 
    } 
 
} 
 
?> 
 
<!doctype html> 
 
<html> 
 
<head> 
 
    </head> 
 

 
<body> 
 
<div class="container"> 
 
    <div class="header"><a href="#"><img src="" alt="Insert Logo Here" name="Insert_logo" width="180" height="90" id="Insert_logo" style="background-color: #C6D580; display:block;" /></a> 
 
    <!-- end .header --></div> 
 
    <div class="sidebar1"> 
 
    <ul class="nav"> 
 
     <li><a href="character_list.php">My Characters</a></li> 
 
     <li><a href="#">Link two</a></li> 
 
     <li><a href="#">Link three</a></li> 
 
     <li><a href="#">Link four</a></li> 
 
    </ul> 
 
    <form action="<?php echo $loginFormAction; ?>" method="POST" name="UserLoginForm" id="UserLoginForm"> 
 
     <table width="200" border="1"> 
 
     <tr> 
 
      <td>Username:</td> 
 
     </tr> 
 
     <tr> 
 
      <td><label for="UserLogin"></label> 
 
      <input name="UserLogin" type="text" id="UserLogin" size="28"></td> 
 
     </tr> 
 
     <tr> 
 
      <td>Password:</td> 
 
     </tr> 
 
     <tr> 
 
      <td><span id="sprypassword1"> 
 
      <label for="UserPass"></label> 
 
      <input name="UserPass" type="password" id="UserPass" size="28"> 
 
      <span class="passwordRequiredMsg">A value is required.</span></span></td> 
 
     </tr> 
 
     <tr> 
 
      <td><input type="submit" name="UserLoginSubmit" id="UserLoginSubmit" value="Submit"></td> 
 
     </tr> 
 
     </table><input name="user_status" type="hidden" value=""> 
 
    </form> 
 
    <p>&nbsp;</p> 
 
    <p><a href="UserRegistration.php">Register</a></p> 
 
    <!-- end .sidebar1 --></div> 
 
    <div class="content"> 
 
    <h1>Please login to proceed</h1> 
 
    <p>This is a testing site only, no guarantees of security so watch yourself</p> 
 
    <!-- end .content --></div> 
 
    <div class="footer"> 
 
    <p>This .footer contains the declaration position:relative; to give Internet Explorer 6 hasLayout for the .footer and cause it to clear correctly. If you're not required to support IE6, you may remove it.</p> 
 
    <!-- end .footer --></div> 
 
    <!-- end .container --></div> 
 
</body> 
 
</html> 
 
<?php 
 
mysql_free_result($UserLoginForm); 
 
?>

Так выше информация Логин. База данных - rpg_test, а таблица - пользователи, соответствующие поля, которые я ищу для отслеживания, - user_id и user_login. Как и следовало ожидать, user_id является целым первичным ключом и user_login буквенно-цифровым именем пользователя. Страница использует это для входа на другие страницы и, похоже, удерживает переменную, которая включает действительное имя пользователя.

Это пример одной из страниц пользователя, который уже вошел в систему:

<?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']); 
 
\t 
 
    $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; 
 
} 
 
} 
 

 
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 WHERE characters.character_owner"; 
 
$characters = mysql_query($query_characters, $DLP_RPG) or die(mysql_error()); 
 
$row_characters = mysql_fetch_assoc($characters); 
 
$totalRows_characters = mysql_num_rows($characters); 
 
?> 
 
<!doctype html> 
 
<html> 
 
<head> 
 
    </head> 
 

 
<body> 
 

 
<div class="container"> 
 
    <div class="header"><a href="#"><img src="" alt="Insert Logo Here" name="Insert_logo" width="180" height="90" id="Insert_logo" style="background-color: #C6D580; display:block;" /></a> 
 
    <!-- end .header --></div> 
 
    <div class="sidebar1"> 
 
    <ul class="nav"> 
 
    
 
     <li><a href="#">My Characters</a></li> 
 
     <li><a href="new_character1.php">New Character</a></li> 
 
     <li><a href="#">Link three</a></li> 
 
     <li><a href="#">Link four</a></li> 
 
    </ul> 
 
    <p><a href="<?php echo $logoutAction ?>">Logout</a></p><br> I should come up with a way to show this only if you're logged in<br> 
 

 
    <!-- end .sidebar1 --></div> 
 
    <div class="content"> 
 
    <h1>List of characters</h1> 
 
    <p>This page should list all of your characters, and just your characters.</p> 
 
    <p>Edit and delete buttons should be included.</p> 
 
    <p>&nbsp;</p> 
 
    <table border="1"> 
 
     <tr> 
 
     <td>Name:</td> 
 
     <td>Type:</td> 
 
     <td>System:</td> 
 
     <td>Owner:</td> 
 
     </tr> 
 
     <?php do { ?> 
 
     <tr> 
 
      <td><?php echo $row_characters['character_name1']; ?></td> 
 
      <td><?php echo $row_characters['character_occupation']; ?></td> 
 
      <td><?php echo $row_characters['play_system']; ?></td> 
 
      <td><?php echo $row_characters['character_owner']; ?></td> 
 
     </tr> 
 
     <?php } while ($row_characters = mysql_fetch_assoc($characters)); ?> 
 
    </table> 
 
<!-- end .content --></div> 
 
    </body> 
 
</html> 
 
<?php 
 
mysql_free_result($UserLoginForm); 
 

 
mysql_free_result($PlaySystem); 
 

 
mysql_free_result($characters); 
 
?>

То, что я хотел, чтобы быть в состоянии сделать это иметь поле «Владелец» в таблица html, которая показывает символы, будет показывать только персонажи, принадлежащие человеку, который их создал. Я бы идеально ограничил бы его поле user_id равным тому, что использует отслеживание входа в систему для доступа к странице. Я предполагаю, что это какая-то постоянная переменная, которую я могу надеяться вызвать и вставить в качестве данных при обновлении таблицы.

Есть ли такая переменная? Я продолжаю видеть $ UserName и другие вещи, но, возможно, я собираюсь в кругах. Любая помощь будет оценена по достоинству.

EDIT: Из того, что я могу найти на сайте, мне нужно использовать переменную сеанса.

Я сделал print_r ($ SESSION) одной из страниц, и это дает:

Array ([PrevUrl] => /rpg/character_list.php [MM_Username] => joecook [MM_UserGroup] =>)

Вход для MM-Username - это то, что поместилось бы в поле user_login, но в таблице ниже показано, что поле, используемое таблицей, - user_id. Я зарегистрирован как user_id = 2, и я хочу видеть только записи, которые относятся ко мне.

<table border="1"> 
 
     <tr> 
 
     <td>Name:</td> 
 
     <td>Type:</td> 
 
     <td>System:</td> 
 
     <td>Owner:</td> 
 
     </tr> 
 
       <tr> 
 
      <td>Fuzz Duck</td> 
 
      <td>1</td> 
 
      <td>Palladium Megaverse</td> 
 
      <td>1</td> 
 
     </tr> 
 
       <tr> 
 
      <td>another heresy test for owner</td> 
 
      <td>17</td> 
 
      <td>Heresy Game Engine</td> 
 
      <td>2</td> 
 
     </tr> 
 
       <tr> 
 
      <td>Another Heresy test</td> 
 
      <td>17</td> 
 
      <td>Heresy Game Engine</td> 
 
      <td>2</td> 
 
     </tr> 
 
      </table>

Это предыдущая форма, которая заполняет таблицу выше с данными, если это помогает:

<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); 
 
\t $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); 
 
\t $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>

ответ

1

Вам нужно добавить условие к вашему запрос, т.е.

WHERE characters.character_owner = users.user_id 

Поскольку вы только хранение user_login/($_SESSION['MM_Username']), а не user_id, вам нужно будет использовать подзапрос, чтобы получить user_id.Попробуйте изменить -

$query_characters = "SELECT * FROM characters WHERE characters.character_owner"; 

в

$query_characters = "SELECT * FROM characters WHERE characters.character_owner = 
    (SELECT user_id FROM users WHERE user_login = '{$_SESSION['MM_Username']}')"; 

USER_LOGIN

+0

Это удивительно, спасибо так много. Теперь мне нужно выяснить, почему он не вводит правильный user_id в форме ввода, и я назову эту страницу успешной. Опять же, большое вам спасибо. –

 Смежные вопросы

  • Нет связанных вопросов^_^