简体   繁体   English

PHP和MySQL PDO查询

[英]Php and mysql pdo query

I want to make query to mysql, but when i execute it at end of the page i have needless text. 我想对mysql进行查询,但是当我在页面末尾执行它时,我得到了不必要的文本。 How can i delete it? 如何删除?

this is the code: 这是代码:

try {

    //create PDO connection
    $db = new PDO("mysql:host=".DBHOST.";port=3306;dbname=".DBNAME, DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {
    //show error
    echo '<p class="bg-danger">'.$e->getMessage().'</p>';
    exit;
}

$stmt = $db->query('SELECT * FROM temperature');
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['timestamp'] . "\t" . $row['humidity'] . "\n";
}
?>

This is the output: 这是输出:

2015-06-16 13:07:47 89 2015-06-16 13:08:46 0 2015-06-16 13:08:56 86 2015-06-16 13:09:06 86 2015-06-16 13:09:16 86 2015-06-16 13:09:27 86 query('SELECT * FROM temperature '); 2015-06-16 13:07:47 89 2015-06-16 13:08:46 0 2015-06-16 13:08:56 86 2015-06-16 13:09:06 86 2015-06-16 13 :09:16 86 2015-06-16 13:09:27 86 query('SELECT * FROM temperature '); while ( $row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo $row['timestamp'] . while($ row = $ stmt-> fetch(PDO :: FETCH_ASSOC)){echo $ row ['timestamp']。 "\\t" . “ \\ t”。 $row['humidity'] . $ row ['humidity']。 "\\n"; “ \\ n”; } } } */?> }}} * /?>

I can't see it in the code code you posted but you have a typo in the original: "$stmt = $db->query" has an extra question mark "$stmt = $db-?>query". 我在您发布的代码中看不到它,但原文有错字:“ $ stmt = $ db-> query”还有一个问号“ $ stmt = $ db-?> query”。 Or maybe you have commented out an area with html tags and php comments which are incorrectly nested? 或者,也许您用不正确嵌套的html标记和php注释注释了一个区域?

Either way, it will break out of PHP parsing and produce the results you describe. 无论哪种方式,它都会脱离PHP解析并产生您描述的结果。

Here's a fun and different way you could write that loop: 这是您编写循环的一种有趣且不同的方式:

foreach($db->query('SELECT * FROM temperature') as $row) {
    echo "{$row['timestamp']}\t{$row['humidity']}\n";
}

See if doing it that way gets the same issue. 看看这样做是否会遇到同样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM