Help us understand the problem. What is going on with this article?

【PHP】PHPでPDOを使ってMySQLでデータ取得・書き込み・更新などなど

More than 5 years have passed since last update.

phpでmysqlのデータをinsertやらupdateやらselectやらやるときにPDOで取得するやり方。
sql実行したデータをwhileしてーってより書き方すっきりした。

DB接続

事前に記載、funciton化して最初に実行でも可。

define('DATABASE_NAME','xxxx');
define('DATABASE_USER','xxxx');
define('DATABASE_PASSWORD','xxxx');
define('DATABASE_HOST','localhost');

// pdo values
define('PDO_DSN','mysql:dbname=' . DATABASE_NAME .';host=' . DATABASE_HOST);

$pdo = new PDO( PDO_DSN, DATABASE_USER, DATABASE_PASSWORD );

insert

prepare関数を使ってsql設定してexecute関数で実行。
その際、変数とかぶっこむならbindvalueとかで変数と型指定したりなど。

$smt = $pdo->prepare('insert into テーブル名 (name,tel) values(?,?)');
$smt->bindParam(1,$name, PDO::PARAM_STR);
$smt->bindValue(2,(int)$tel, PDO::PARAM_INT);
$smt->execute();
// 実行結果を配列に返す。
$select_data = $smt->fetchAll();

bindParamは文字列を返す。
bindValueは数値型を返すことも可能だが指定の必要があり。

update

$smt = $pdo->prepare('update テーブル名 set count = ?, count2 = ?, count3 = ? where entry_id = ?');
$smt->bindValue(1,(int)$count, PDO::PARAM_INT);
$smt->bindValue(2,(int)$count2, PDO::PARAM_INT);
$smt->bindValue(3,(int)$count3, PDO::PARAM_INT);
$smt->bindValue(4,(int)$entry_id, PDO::PARAM_INT);
$smt->execute();

deleteもこのノリでいける。

select

変数付与しないベタの形でよければquery関数使えばexecuteしなくてもよいぽい。

$smt = $pdo->query('select * from テーブル名 order by entry_id desc');
// 実行結果を配列に返す。
$select_data = $smt->fetchAll();

もちろんcreateもdropもこの手法でかける。
楽~。

_shogo_
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした