简体   繁体   English

PDO不从MySQL查询返回结果

[英]PDO not returning results from mysql query

I am comfortable with using mysqli style php queries but am trying to use more PDO. 我对使用mysqli样式的php查询感到满意,但尝试使用更多的PDO。 I think I understand most of how to use it but every now and again something comes up which throws me. 我想我大部分都了解如何使用它,但是时不时地出现一些使我感到不适的东西。

So I am doing a basic SELECT query to a mysql database and I cant get any results from the query 所以我正在对mysql数据库进行基本的SELECT查询,但无法从查询中获取任何结果

PHP PHP

try {
    $dbhandle = new PDO("mysql:dbname = {$dbname}; host = {$dbhost}; port = {$dbport}", $dbuser, $dbpass);
} catch (PDOException $e)
{
    echo "Error when creating Database Handle. Error: " .$e;
}

$sql = $dbhandle->prepare("SELECT projectName FROM `__projects`");
$sql->execute();

$projectList = $sql->fetch(PDO::FETCH_BOTH);

$size = sizeof($projectList);
echo $size;

I don't understand why The array returned is empty. 我不明白为什么返回的数组为空。 Am I making a mistake. 我犯错了吗? I know the user/pass are ok as I can return results using the same query when using mysqli methods. 我知道用户/密码还可以,因为使用mysqli方法时可以使用相同的查询返回结果。

What am I doing wrong? 我究竟做错了什么?

Try adjusting your connection statement. 尝试调整您的连接语句。 I'm not certain if the order will affect it, but from the documentation, it should be similar to: 我不确定命令是否会影响它,但是从文档中看,它应该类似于:

mysql:host=localhost;port=3307;dbname=testdb

http://php.net/manual/en/ref.pdo-mysql.connection.php http://php.net/manual/en/ref.pdo-mysql.connection.php

Thanks, 谢谢,

Andrew 安德鲁

When you want to execute a query, first make sure it will run by making it not equal or equal to false. 当您要执行查询时,请先通过使其不等于或等于false来确保其将运行。 That way you can debug your script. 这样,您可以调试脚本。 Try to prepare the Query alone instead of executing it right away. 尝试单独准备查询,而不是立即执行查询。

The following example selects the rows in which the 'id' is 1 or 3. 下面的示例选择'id'为1或3的行。

<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';

try {
// Connect and create the PDO object
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

  // Define and perform the SQL SELECT query
  $sql = "SELECT * FROM `sites` WHERE `id` IN(1, 3)";
  $result = $conn->query($sql);

  // If the SQL query is succesfully performed ($result not false)
  if($result !== false) {
   $cols = $result->columnCount();           // Number of returned columns

 echo 'Number of returned columns: '. $cols. '<br />';

// Parse the result set
foreach($result as $row) {
  echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}

$conn = null;        // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>

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

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