php mysql 데이터베이스 테이블에 데이터가 안들어가요..
글쓴이: onerat / 작성시간: 토, 2019/04/27 - 5:16오후
안녕하세요 저는 php를 이용해서 웹페이지를 만들고 있는데 회원가입/로그인 성공 이후 프로필 편집을 통해 사진 업로드 및 소개를 추가(즉 수정)하려고 하는데 왜 테이블에 들어가지가 않습니다..... 몇 주 동안 여기서 막혀있습니다 ..........제발 도와주세요..ㅠㅁㅠ..어떤 부분이 문제인지 도무지 모르겠습니다..엉엉
일단 users 테이블 형태는 올려놓은 파일과 같습니다.
첫 째 edit.php 파일은 프로필 편집 화면입니다.
<?
include "processForm.php"
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>프로필 편집</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="/assets/css/profile.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-4 offset-md-4 form-div">
<form action="edit.php" method="post" enctype="multipart/form-data">
<h2 class="text-center mb-3 mt-3">정보 수정</h2>
<?php if (!empty($msg)): ?>
<div class="alert <?php echo $msg_class ?>" role="alert">
<?php echo $msg; ?>
</div>
<?php endif; ?>
<div class="form-group text-center" style="position: relative;" >
<span class="img-div">
<div class="text-center img-placeholder" onClick="triggerClick()">
<h4>정보 수정</h4>
</div>
<img src="images/avatar.jpg" onClick="triggerClick()" id="profileDisplay">
</span>
<input type="file" name="profileImage" onChange="displayImage(this)" id="profileImage" class="form-control">
</div>
<div class="form-group">
<label>이름</label>
<input class="form-control" type="text" size="35" name="username" value="<?php echo $_SESSION['user']['username'];?>">
</div>
<div class="form-group">
<label>비밀번호</label>
<input class="form-control" type="password" size="35" name="password" value="<?php echo $_SESSION['user']['password']; ?>">
</div>
<div class="form-group">
<label>소개</label>
<textarea name="bio" class="form-control"><?php echo $_SESSION['user']['bio'];?></textarea>
</div>
<div class="form-group">
<button type="submit" name="edit_btn" class="btn btn-primary btn-block">제출</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<script src="assets/js/script.js"></script>둘 째로 processForm.php는 실제 수정을 구현하는 파일입니다.
<?php
include "functions.php";
$conn = mysqli_connect("localhost", "root", "", "projectdb");
$msg = "";
$msg_class = "";
$username = e($_POST['username']);
$password = e($_POST['password']);
if (isset($_POST['edit_btn'])) {
// for the database
$bio = stripslashes($_POST['bio']);
$profileImageName = time() . '-' . $_FILES["profileImage"]["name"];
// For image upload
$target_dir = "images/";
$target_file = $target_dir . basename($profileImageName);
// VALIDATION
// validate image size. Size is calculated in Bytes
if($_FILES['profileImage']['size'] > 200000) {
$msg = "Image size should not be greated than 200Kb";
$msg_class = "alert-danger";
}
// check if file exists
if(file_exists($target_file)) {
$msg = "File already exists";
$msg_class = "alert-danger";
}
// Upload image only if no errors
if (empty($error)) {
if(move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target_file)) {
$sql = "update users set username='$username',password='$password','$profileImageName', bio='$bio' where email='".$_SESSION['user']['email']."'";
if(mysqli_query($conn, $sql)){
$msg = "Image uploaded and saved in the Database";
$msg_class = "alert-success";
} else {
$msg = "There was an error in the database";
$msg_class = "alert-danger";
}
} else {
$error = "There was an erro uploading the file";
$msg = "alert-danger";
}
}
}
?>셋째로, functions.php는 로그인/회원가입에 대한 함수를 구현한 파일인데, 여기서 세션을 정의했기 때문에 앞서 processForm.php에서 include하였습니다.
<?php
// connect to database
$db = mysqli_connect('localhost', 'root', '', 'projectdb');
// variable declaration
$username = "";
$email = "";
$errors = array();
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
register();
}
// REGISTER USER
function register(){
// call these variables with the global keyword to make them available in function
global $db, $errors, $username, $email;
// receive all input values from the form. Call the e() function
// defined below to escape form values
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "이름은 필수 정보입니다.");
}
if (empty($email)) {
array_push($errors, "이메일은 필수 정보입니다.");
}
if (empty($password_1)) {
array_push($errors, "비밀번호는 필수 정보입니다.");
}
if ($password_1 != $password_2) {
array_push($errors, "비밀번호가 일치하지 않습니다.");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "새 사용자를 등록하였습니다.";
header('location: login.php');
}else{
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$password')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['success'] = "로그인 되었습니다.";
header('location: index.php');
}
}
}
// return user array from their id
function getUserById($id){
global $db;
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
// escape string
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
// log user out if logout button clicked
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
header("location: login.php");
}
// call the login() function if register_btn is clicked
if (isset($_POST['login_btn'])) {
login();
}
// LOGIN USER
function login(){
global $db, $email, $errors;
// grap form values
$email = e($_POST['email']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($email)) {
array_push($errors, "이메일을 입력해주세요.");
}
if (empty($password)) {
array_push($errors, "비밀번호를 입력해주세요.");
}
// attempt login if no errors on form
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE email='$email' AND password='$password' LIMIT 1";
$results = mysqli_query($db, $query);
$useremail= $row[email];
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: home.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}else {
array_push($errors, "아이디 혹은 비밀번호 오류입니다.");
}
}
}
// ...
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}도대체 어떤 것이 문제일까요....ㅠㅡㅠ 이 방법이 틀린 방법이라면 다른 방법을 제발 알려주세요...........ㅠㅠ
게시판에 게시글 추가하는 것 역시 테이블에 넣어지지가 않습니다. 넘넘...............골치가 아프네요........제발 도와주세요 ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ
File attachments:
| 첨부 | 파일 크기 |
|---|---|
| 168.07 KB |
Forums:


이 정도 규모 프로그램이 "결과적으로 안 돌았다"면
이 정도 규모 프로그램이 "결과적으로 안 돌았다"면 원인이 어디에든 있을 수 있죠.
dbms id/pw가 틀렸거나 해당 db(projectdb) 권한이 없거나 sql문이 틀렸거나 등등.
저라면 일단 mysqli_query 등 각 함수들의 반환값을 꼼꼼히 체크할 겁니다. 파일로 로그를 출력해보세요.
댓글 달기