PHP & MySQL

02. PHP와 MySQL의 연동

drizzle0925 2021. 3. 17. 22:36
728x90

PHP와 MySQL의 연동

 

google에서 php mysql api로 검색 > Choosing an API 선택

 

www.php.net/manual/ja/mysqlinfo.api.choosing.php

 

PHP: どの API を使うか - Manual

query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");$row = $result->fetch_assoc();echo htmlentities($row['_message']);// PDO$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');$statement = $pdo->query

www.php.net

어느 API를 사용할까

PHP에는 다양한 MySQL과 연결하는 API가 있다. 아래는 mysqli와 PDO가 제공하는 API이다. 각각의 코드는 "example.com" 위에서 가동하는 MySQL서버에 유저명 "user" 패스워드 "password"로 접속한 것이다.

그리고 쿼리를 실행해서 유저와 인사하고 있다.

 

 

 

www.php.net/manual/ja/mysqli.construct.php

 

PHP: mysqli::__construct - Manual

mysqli can succeed in surprising ways, depending on the privileges granted to the user. For example,GRANT USAGE ON *.* TO 'myuser'@'localhost' IDENTIFIED BY PASSWORD 'mypassword';GRANT ALL PRIVILEGES ON `database_a`.* TO 'myuser'@'localhost';CREATE DATABAS

www.php.net

mysqil::__construct -- mysqli::connect -- mysqli_connect - 신규로 MySQL 서버에 접속을 연결한다.

 

Syntax

<?php 
mysqli_connect("호스트","유저이름","패스워드","데이터베이스이름");
?>

 

insert.php

<?php 
mysqli_connect("localhost","root","111111","tutorials");
?>

쿼리실행

데이터베이스와 연결이 끝났으면 쿼리를 실행해보자.

쿼리 실행을 위해 mysqli_query() 함수를 이용한다.

 

www.php.net/manual/ja/mysqli.query.php

 

PHP: mysqli::query - Manual

this is a variant of mysqli_query that returns output parameters as a rowset. = '0' && $command[$i2] <= '9') ||          ($command[$i2] >= 'A' && $command[$i2] <= 'Z') ||          ($command[$i2] >= 'a' && $command[$i2] <= 'z') ||          ($

www.php.net

mysqli_qurry(mysqli 링크, 실행할 쿼리)

 

insert.php

<?php
$conn = mysqli_connect("localhost", "root", "111111", "opentutorials");
mysqli_query($conn, "
    INSERT INTO topic (
        title,
        description,
        created
    ) VALUES (
        'MySQL',
        'MySQL is ....',
        NOW()
    )");
?>

데이터를 저장하는 쿼리

 

github.com/jun0925/tutorials/commit/a1a8b4109996f8b1fe51cd5c3f37c548f31befc4


디버그

mysqli_error를 통해 error 내용을 확인할 수 있다.

www.php.net/manual/ja/mysqli.error.php

 

PHP: mysqli::$error - Manual

The mysqli_sql_exception class is not available to PHP 5.05I used this code to catch errors query($query);if (!$res) {   printf("Errormessage: %s\n", $mysqli->error);}?>The problem with this is that valid values for $res are: a mysqli_result object , tru

www.php.net

직전의 에러 내용을 문자열로 돌려준다.

insert.php

<?php
$conn = mysqli_connect("localhost", "root", "111111", "tutorials");
$sql  = "
    INSER INTO topic (
        title,
        description,
        created
    ) VALUES (
        'MySQL',
        'MySQL is ....',
        NOW()
    )";
$result = mysqli_query($conn, $sql);
if($result === false){
    echo mysqli_error($conn);
}
?>

 

github.com/jun0925/tutorials/blob/insert_create/insert.php

728x90