Q&A
実現したいこと
CREATE TABLEのテーブル名を変数からSQLに展開しています。
その際、シングルクォーテーションがついてしまい。エラーとなってしまいす。
バッククォートのみでSQL文の作成はできないでしょうか?
前提
[バージョン]
PHP:7.2.24
MariaDB:10.5.10
エラー文
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''`tmp_tabelname`' select hostid from tbl where 1 and hostid in ('1005','1006'...' at line 1
SQL
# エラーとなるSQL CREATE TEMPORARY TABLE '`tmp_tabelname`' select hostid from tbl where 1 and hostid in ('1005','1006') and col between '2022-07-13 00:00' and '2022-10-05 09:39' # 流したいSQL CREATE TEMPORARY TABLE `tmp_tabelname` select hostid from tbl where 1 and hostid in ('1005','1006') and col between '2022-07-13 00:00' and '2022-10-05 09:39'
検証用コード
create table tbl (hostid int not null primary key, name varchar(30), val varchar(30), col timestamp not null) insert into tbl values (1001,'takuya','grape','2022-07-01 08:30:00'), (1002,'taro','orange','2022-07-01 09:30:00'), (1003,'yuta','apple','2022-07-14 08:30:00'), (1004,'makoto','cat','2022-07-20 08:30:00'), (1005,'shun','dog','2022-08-01 08:30:00'), (1006,'tomo','tiger','2022-09-01 08:30:00');
該当のソースコード
PHP
1<?php 2 3function Hostid_Check(string $start_date, string $end_date){ 4 5 try { 6 $id = array(1005, 1006); 7 $dbh = new PDO('mysql:host=localhost;dbname=base_info', 'waiis', 'Nttdata1!'); 8 9 $data=[]; 10 $sql ="CREATE TEMPORARY TABLE ? select hostid from tbl where 1 \n"; 11 if(count($id)>0){ 12 $sql.="and hostid in (".implode(",",array_fill(0,count($id),"?")).") \n"; 13 $data=array_merge($data,$id); 14 } 15 $sql.="and col between ? and ? \n"; 16 $tablename = "`tmp_tabelname`"; 17 array_unshift($data, $tablename); 18 $data[]=$start_date; 19 $data[]=$end_date; 20 21 $stmt = $dbh->prepare($sql); 22 $stmt->execute($data); 23 $res = $stmt->fetchAll(); 24 var_dump($res); 25 } 26 catch (Exception $e) { 27 print "error!! " . $e->getMessage() . PHP_EOL; 28 } 29} 30 31function Func_Exec(){ 32 33 // 過去〇週間前の日付取得 34 $startDateTime = new DateTime('-12 weeks'); 35 $start_date = $startDateTime->format('Y-m-d 00:00'); 36 37 // 現在時刻取得 38 $endDateTime = new DateTime('now'); 39 $end_date = $endDateTime->format('Y-m-d H:i'); 40 41 Hostid_Check($start_date, $end_date); 42 43} 44// 関数実行 45Func_Exec(); 46 47?>
回答1件
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。