2

こんにちは、PDO の学習を開始することにしました。ただし、データベースにテーブルが存在するかどうかを確認する関数の作成に問題があります。

個々のアイテムには、テーブル名が ($id) である独自のテーブルがあります。

<?php
include_once('config.php');
include_once('simple_html_dom.php');

$html = file_get_html('http://localhost:8888/CDOnline%20Online.html');

foreach($html->find('div.product-stamp-inner') as $content) {   

$detail['itemid'] = $content->find('a',0)->href;
$detail['itemid'] = substr($detail['itemid'], 40, 6);
if (strpos($detail['itemid'], "?") !== false) {
$detail['itemid'] = substr($detail['itemid'], 0, 5);
}
$id = $detail['itemid'];

tableExists($dbh, $id);
}

function tableExists($dbh, $id)
{
//check if table exists
}

$dbh = null;
?>

私は答えを求めてフォーラムを精査しようとしましたが、手ぶらで出てきました。私の答えに近づいた唯一のことは次のとおりです。

function tableExists($dbh, $id)
{
$results = $dbh->query("SHOW TABLE LIKE `$id`");
if(count($results)>0){echo 'table exists';}
}

しかし、テーブルの半分が存在しない場合、すべてのテーブルが存在すると言っているだけです。

編集:1行以上ある場合、テーブルが存在する必要があります。

4

6 に答える 6

14

の周りでバックティックを使用してい$idます。一重引用符に変更します。このような:

"SHOW TABLES LIKE '$id'"

さらに、ステートメントは機能しないことに注意してくださいcount($results)>0$results->rowCount()代わりに使用する必要があります。


両方のエラーを修正すると、次の機能が得られます。

function tableExists($dbh, $id)
{
    $results = $dbh->query("SHOW TABLES LIKE '$id'");
    if(!$results) {
        die(print_r($dbh->errorInfo(), TRUE));
    }
    if($results->rowCount()>0){echo 'table exists';}
}
于 2013-04-23T21:36:42.273 に答える
0

これは、これを行う最も簡単な方法のようです。この関数には、作成済みの pdo オブジェクトを含む配列を渡します。

$db['pdo']=new PDO('mysqlconnectiongoeshere');
$db['table']='tabletobechecked';

function is_table($db){
   $is_table=$db['pdo']->query("SHOW TABLES LIKE '".$db['table']."'");
   return$is_table->rowCount();
}

このように、テーブルが存在する場合、この関数は「1」を返し、テーブルが存在しない場合、この関数は「0」を返します。

したがって、次のように使用できます。

if(is_table($db)){
  echo"The table".$db['table']." exists.";
}else{
  echo"The table".$db['table']." does not exist.";
}
于 2016-09-08T10:01:15.970 に答える
-1
private function doesTableExist($table)
{
    try {
        $this->db->query("DESC $table");
    } catch (Exception $e) {
         return false;
    }
    return true;
}
于 2016-03-30T10:34:58.277 に答える