只在数据库中拉出第一条记录

时间:2012-08-23 23:55:51

标签: php

当我在PHP中运行它时,它只会拉取表中的第一条记录然后显示它。我需要这个来为从表中登录的用户提取数据。希望你知道我的意思:

<?php
$getall = mysql_query("SELECT name,username,email FROM users");
$row = mysql_fetch_assoc($getall);

$fullnameDB         = $row['name'];
$emailDB            = $row['email'];
$usernameDB         = $row['username'];
?>

3 个答案:

答案 0 :(得分:1)

使用mysql_fetch_assoc($ getall),您一次只能获取一行。这就是为什么你应该用“while”来获得所有!

$user_id = 1;
$getall = mysql_query("SELECT name,username,email FROM users WHERE user_id = $user_id");
$arr = array();
while ( $result = mysql_fetch_assoc($getall) ) {
  $arr[] = $result;
}

$date = $arr[0]["date"]; //first row date
$name = $arr[0]["name"]; //first row name
$comments = $arr[0]["comments"]; //first row comments

$ arr是一个包含每一行数据的数组。

答案 1 :(得分:0)

更改查询:

SELECT name, username, email FROM users WHERE username = '{YourUsernameHere}' LIMIT 1

答案 2 :(得分:0)

//按用户ID

<?php
$user_id = 1;
$getall = mysql_query("SELECT name,username,email FROM users WHERE user_id = $user_id");
$row = mysql_fetch_assoc($getall);

$fullnameDB         = $row['name'];
$emailDB            = $row['email'];
$usernameDB         = $row['username'];
?>

//通过电子邮件和密码

<?php
$email = $_POST["email"];
$password = $_POST["password"];
$getall = mysql_query("SELECT name,username,email FROM users WHERE email = '$email' AND password = '$password'");
$row = mysql_fetch_assoc($getall);

$fullnameDB         = $row['name'];
$emailDB            = $row['email'];
$usernameDB         = $row['username'];
?>

我会通过(codeigniter模型有查询)来做到这一点:

 $this->load->model("ModelName");
 $query = $this->ModelName->functionNameInModel(params);
 $result = $query->result();
 if ($query->num_rows() > 0)
 {
      $row = $query->row(); 
      $var = $row->table_column;
      echo("var = " . $var);
 } else {
// No records returned! HOLY ****! HUSTON WE GOT A PROBLEM!
    // Handle it with some code here...     
 }