*php 서버 위치 :
$cd /var/www/htrml
*파일 권한설정 755
$ sudo chmod 755 -R ./*
try.php
localhost : 로컬호스트, 일반적으로 로컬호스트 고정
root : mysql의 user
mysql : 패스워드
testdb : root 계정에 존재하는 databasae 이름
<?php
$link=mysqli_connect("localhost", "root", "mysql", "testdb");
if (!$link)
{
echo "MySQL 접속 에러 : ";
echo mysqli_connect_error();
exit();
}
mysqli_set_charset($link,"utf8");
$sql="select * from solar";
$result=mysqli_query($link,$sql);
$data = array();
if($result){
while($row=mysqli_fetch_array($result)){
array_push($data,
array('id'=>$row[0]
));
}
header('Content-Type: application/json; charset=utf8');
$json = json_encode(array("webnautes"=>$data), JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
echo $json;
}
else{
echo "SQL문 처리중 에러 발생 : ";
echo mysqli_error($link);
}
mysqli_close($link);
?>
insert.php
dbcon.php의 연결을 이어받아서 insert 명령어를 수행한다.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
include('dbcon.php');
if( ($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['submit']))
{
$name=$_POST['name'];
$country=$_POST['country'];
if(empty($name)){
$errMSG = "이름을 입력하세요.";
}
else if(empty($country)){
$errMSG = "나라를 입력하세요.";
}
if(!isset($errMSG))
{
try{
$stmt = $con->prepare('INSERT INTO person(name, country) VALUES(:name, :country)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':country', $country);
if($stmt->execute())
{
$successMSG = "새로운 사용자를 추가했습니다.";
}
else
{
$errMSG = "사용자 추가 에러";
}
} catch(PDOException $e) {
die("Database error: " . $e->getMessage());
}
}
}
?>
<html>
<body>
<?php
if (isset($errMSG)) echo $errMSG;
if (isset($successMSG)) echo $successMSG;
?>
<form action="<?php $_PHP_SELF ?>" method="POST">
Name: <input type = "text" name = "name" />
Country: <input type = "text" name = "country" />
<input type = "submit" name = "submit" />
</form>
</body>
</html>
<?php
}
?>
dbcon.php
<?php
$host = 'localhost';
$username = 'root'; # MySQL 계정 아이디
$password = 'mysql'; # MySQL 계정 패스워드
$dbname = 'testdb'; # DATABASE 이름
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try {
$con = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8",$username, $password);
} catch(PDOException $e) {
die("Failed to connect to the database: " . $e->getMessage());
}
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
function undo_magic_quotes_gpc(&$array) {
foreach($array as &$value) {
if(is_array($value)) {
undo_magic_quotes_gpc($value);
}
else {
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
#session_start();
?>
참고
[1] https://webnautes.tistory.com/828
[2] https://yoo-hyeok.tistory.com/17?category=708422
'리눅스 > 데이터베이스' 카테고리의 다른 글
PHP 서버 설정 (0) | 2019.07.11 |
---|---|
Ubuntu에서 mysql 명령어 사용 (0) | 2019.07.11 |