简体   繁体   中英

Get one line result from MySQL

I'm trying to build a simple Database Class in PHP and I'm using MySQL.

Now i have stucked, i can't figure it out how i can show one line result from a database. I have solved how i can get multiple rows from the database but now I'm trying to show only one like username, email, level, reg_date.

My code:

class Database {

  public $mysql;

  function __construct()
  {
    $this->mysql = new mysqli(host, user, password, db) or die('There was a problem connecting to the db');
  }

  function multiLine($sql)
  {
    $this->mysql->query("SET NAMES 'utf8'");
    $this->mysql->query("SET CHARACTER SET 'utf8'");

    if(($result = $this->mysql->query($sql)) != NULL) {
      $x = array();
      while($row = $result->fetch_array()) {
        $x[] = $row;
      }
      return $x;
    }
    else {
      echo $this->mysql->error;
    }
  }


  function singleLine($sql)
  {

      $one = array();
      if(($one = $this->mysql->query($sql)) != NULL)
      {
          $one = $result->fetch_array(); // Error here
      }

      return $one;
  }

  function __destruct() {
    // close out the database connection;
    $this->mysql->close();
  }
}

my function multiLine works and i use it like this:

$db = new Database();
$sql = 'SELECT * FROM users ORDER BY id DESC';

$response = $db->multiLine($sql);

<?php foreach($response as $r) : ?>
<p>ID: <?php echo $r['id']; ?></p>
<p>Username: <?php echo $r['username']; ?></p>
<?php endforeach; ?>

So can somebody give me an hint how to solve the problem? OR maybe somebody have a link to a great tuturial for making a Database Class in PHP.

if(($one = $this->mysql->query($sql)) != NULL)

应该

if(($result = $this->mysql->query($sql)) != NULL)

我不明白是什么问题,为什么您只是不添加LIMIT 1来查询

To force the result to one row, LIMIT 1 on the end of the query will do it.

If you're looking to check if the result happens to be one row, before sending it to multiLine() or singleLine(), mysql_num_rows will tell you how many rows were in your query.

I'm not sure why you'd want to handle them differently, though, because the code that calls it would then have to check to see if it's being returned an array or an object. The return should be consistent.

Get one line result from MySQL:

$val = fetch_one_record("SELECT some_field FROM some_table LIMIT 1);

function fetch_one_record($sql) {
    $conn = db_connect();
    $result = array_shift($conn->query($sql)->fetch_assoc());
    $conn->close();
    return $result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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