Created
May 8, 2018 00:47
-
-
Save ryu1-1uyr/265079aaec455b52e997a9cc5890dcfe to your computer and use it in GitHub Desktop.
php DB接続周りの参考
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>cotemttest</title> | |
</head> | |
<body> | |
<div> | |
<?php | |
$user = 'ryu'; | |
$password = 'ryuryu1207'; | |
$dbname = 'test'; | |
$host = 'localhost:3306'; | |
$mysqli = new mysqli($host,$user,$password,$dbname); | |
if ($mysqli->connect_error) { | |
echo $mysqli->connect_error; | |
}else { | |
echo 'つながったよ'; | |
} | |
?> | |
</div> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$user = 'ryu1'; | |
$password = 'ryuryu1207'; | |
$dbname = 'test'; | |
$host = 'localhost:3306'; | |
$dsn = "mysql:host={$host};dbname={$dbname};charset=utf8"; | |
?> | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>cotemttest</title> | |
</head> | |
<body> | |
<form action="index.php" method="post"> | |
<p><label>名前:<input name="YourName"></label></p> | |
<p><label>メッセージ:<input name="Message"></label></p> | |
<p><button>送信</button></p> | |
</form> | |
<div> | |
<?php | |
//$sql = 'select body from log where name = "hello"'; | |
$pdo = new PDO($dsn, $user, $password);//MySQLに接続てきな! | |
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);//おまじない | |
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//おまじない | |
try{ | |
$name = $_POST['YourName']; | |
$message = $_POST["Message"] ; | |
if ( $message != "" && $name != "") { | |
echo $name . " " . $message."<br>"; | |
$sql = "insert into log VALUE ('$name','$message')"; | |
echo $sql."<br>"; | |
$stm = $pdo->prepare($sql);//SQLの文書をセットする感じ | |
$stm->execute();//SQLここで実行されてる | |
} | |
$name = ""; | |
$message = ""; | |
// $resulut = $stm->fetchAll(PDO::FETCH_ASSOC); | |
} catch(Exception $e){ | |
echo 'エラーが有りました'; | |
echo $e->getMessage(); | |
} | |
try { | |
$sql = 'SELECT * FROM log'; | |
$stm = $pdo->prepare($sql);//SQLの文書をセットする感じ | |
$stm->execute();//SQLここで実行されてる | |
$resulut = $stm->fetchAll(PDO::FETCH_ASSOC); | |
echo "<br>"; | |
echo "データベース{$dbname}に接続しました"; | |
echo "<br>"."<br>"; | |
foreach ($resulut as $row){ | |
echo $row['name']."\n"; | |
echo $row['body']."<br>"; | |
}; | |
$pdo =null; | |
} catch (Exception $e){ | |
echo 'エラーが有りました'; | |
echo $e->getMessage(); | |
exit(); | |
} | |
?> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment