prepare()vs query()mysqli

时间:2010-08-24 18:34:39

标签: php mysql mysqli

我试图理解mysqli的query()和prepare()之间的区别。我有类似下面的代码,我想从两者得到相同的结果。但是,prepare()不能按预期工作。为什么?

  // this works

  if ($query = $this->db->query("SELECT html FROM static_pages WHERE page = 'cities'")) {

     $result = $query->fetch_row();
     echo $result[0];

  $query->close();

  }

  //this does not work
  //result is empty

     $cities = 'cities';

     $stmt = $this->db->prepare("SELECT html FROM static_pages WHERE page = ?");
     $stmt -> bind_param("s", $cities);
     $stmt->execute();
     $stmt->bind_result($result);
     $stmt->fetch();
     echo $result;
     $stmt->close();

     $this->db->close();

这些是我所要求的服务器配置:

OS

Vista 64bit / PHP版本5.2.9

的mysqli

启用了MysqlI支持

客户端API库版本5.0.51a

客户端API标头版本5.0.51a

MYSQLI_SOCKET /tmp/mysql.sock

指令本地值主值

mysqli.default_host没有值没有值

mysqli.default_port 3306 3306

mysqli.default_pw无值无值

mysqli.default_socket没有值没有值

mysqli.default_user没有值没有值

mysqli.max_links Unlimited Unlimited

mysqli.reconnect关闭

3 个答案:

答案 0 :(得分:2)

您可以在$stmt->store_result();$stmt->execute();之间尝试$stmt->bind_result($result);吗?

答案 1 :(得分:2)

任何的mysqli_ *函数都可能失败。在这种情况下,返回值为falsemysqlimysqli_stmt对象的error / errno属性包含有关错误的更多信息。脚本必须测试每个返回值并在错误条件下做出适当的反应(例如,如果连接失败,则准备语句没有意义。)

<?php
$foo = new Foo;
$foo->init();
$foo->bar();
class Foo {
  public function bar() {
    $cities = 'cities';  
    $stmt = $this->db->prepare("SELECT html FROM soTest WHERE page = ?");
    if ( !$stmt ) {
      echo "prepare failed\n";
      echo "error: ", $this->db->error, "\n";
      return;
    }

    $rc = $stmt->bind_param("s", $cities);
    if ( !$rc ) {
      echo "bind_param failed\n";
      echo "error: ", $stmt->error, "\n";
      return;
    }

    $rc=$stmt->execute();
    if ( !$rc ) {
      echo "execute failed\n";
      echo "error: ", $stmt->error, "\n";
      return;
    }

    $rc = $stmt->bind_result($result);
    if ( !$rc ) {
      echo "bind_result failed\n";
      echo "error: ", $stmt->error, "\n";
      return;
    }

    $rc = $stmt->fetch();
    if ( !$rc ) {
      echo "no such record\n";
    }
    else {
      echo 'result: ', $result, "\n";
    }
    $stmt->close();
  }

  public function init() {
    $this->db = new mysqli('localhost', 'localonly', 'localonly', 'test');
    if ($this->db->connect_error) {
      die('connection failed: ' . $this->db->connect_error);
    }
    $rc = $this->db->query('CREATE TEMPORARY TABLE
      soTest (id int auto_increment, html varchar(16), page varchar(16),primary key(id))'
    );
    if ( !$rc ) {  die('error: '.$this->db->error); }
    $rc = $this->db->query("INSERT INTO soTest (html,page) VALUES ('htmlFoo','foo'),('htmlCities','cities')");
    if ( !$rc ) {  die('error: '.$this->db->error); }
  }
}

牢记CWE-209: Information Exposure Through an Error Message。在我的示例脚本中打印实际的错误消息仅用于测试。而且您可能会使用比die()更复杂的错误处理。

答案 2 :(得分:0)

echo $result;不是echo $results;