php 使用 mySQLi 从数据库中获取单个结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/14624509/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Single Result from Database by using mySQLi
提问by Hiroshi Rana
I am trying to use mySQLi for the first time. I have done it in case of loop. Loop results are showing but i am stuck when i try to show single record. Here is loop code that is working.
我第一次尝试使用 mySQLi。我已经在循环的情况下做到了。循环结果正在显示,但当我尝试显示单个记录时卡住了。这是正在运行的循环代码。
<?php
// Connect To DB
$hostname="localhost";
$database="mydbname";
$username="root";
$password="";
@$conn = mysqli_connect($hostname, $username, $password)
        or die("Could not connect to server " . mysql_error()); 
    mysqli_select_db($conn, $database)
        or die("Error: Could not connect to the database: " . mysql_error());
    /*Check for Connection*/
    if(mysqli_connect_errno()){
        // Display Error message if fails
        echo 'Error, could not connect to the database please try again again.';
    exit();
    }
?>
<?php
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = mysqli_query($conn, $query);
@$num_results = mysqli_num_rows($result);
?>
<?php
/*Loop through each row and display records */
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
?>
<?php // echo 'Name' .$row['ssfullname'] . 'email' . $row['ssemail'] . "\n"; ?>
Name: <?php print $row['ssfullname']; ?>
<br />
Email: <?php print $row['ssemail']; ?>
<br /><br />
<?php 
// end loop
} 
?>
Above code is fine in case of loop. Now how do i show single record, any record, name or email, from first row or whatever, just single record, how would i do that? In single record case, consider all above loop part removed and lets show any single record without loop.
上面的代码在循环的情况下很好。现在我如何显示单条记录、任何记录、姓名或电子邮件,从第一行或其他任何内容,只是单条记录,我该怎么做?在单个记录的情况下,考虑删除上述所有循环部分,让我们显示任何没有循环的单个记录。
回答by Your Common Sense
When just a single result is needed, then no loop should be used. Just fetch the row right away.
当只需要一个结果时,不应使用循环。只需立即获取行。
In case you need to fetch the entire row into associative array:
$row = $result->fetch_assoc();in case you need just a single value
$row = $result->fetch_row(); $value = $row[0];
如果您需要将整行提取到关联数组中:
$row = $result->fetch_assoc();如果您只需要一个值
$row = $result->fetch_row(); $value = $row[0];
Below are complete examples for different use cases
以下是不同用例的完整示例
Variables to be used in the query
查询中使用的变量
When variables are to be used in the query, then a prepared statementmust be used. For example, given we have a variable $id:
当要在查询中使用变量时,必须使用准备好的语句。例如,假设我们有一个变量$id:
$query = "SELECT ssfullname, ssemail FROM userss WHERE ud=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$row = $result->fetch_row();
$value = $row[0];
The detailed explanation of the above process can be found in my article. As to why you must follow it is explained in this famous question
上述过程的详细解释可以在我的文章中找到。至于为什么你必须遵循它在这个著名的问题中有解释
No variables in the query
查询中没有变量
In your case, where no variables to be used in the query, you can use the query()method:
在您的情况下,查询中没有要使用的变量,您可以使用以下query()方法:
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = $conn->($query);
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$row = $result->fetch_row();
$value = $row[0];
By the way, although using raw API while learning is okay, consider using some database abstraction library in the future.
It will turn allyour database code into 3 lines:
顺便说一下,虽然边学边用原生API没问题,但以后考虑用一些数据库抽象库。
它将把你所有的数据库代码变成 3 行:
include 'database.class.php';
$db  = new DB();
$row = $db->getRow("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
回答by MFAL
If you assume just one result you could do this as in Edwin suggested by using specific users id.
如果您只假设一个结果,您可以按照 Edwin 的建议使用特定用户 ID 执行此操作。
$someUserId = 'abc123';
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.
OR as "Your Common Sense" which selects just one user.
或者作为“你的常识”,它只选择一个用户。
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
Nothing really different from the above except for PHP v.5
除了PHP v.5之外,没有什么与上面的完全不同
回答by Edwin Alex
Use  mysqli_fetch_row(). Try this,
使用  mysqli_fetch_row(). 尝试这个,
$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id;
$result = mysqli_query($conn, $query);
$row   = mysqli_fetch_row($result);
$ssfullname = $row['ssfullname'];
$ssemail    = $row['ssemail'];
回答by RaRdEvA
There is an example in php.net, is the #4.
php.net 中有一个例子,就是#4。
http://php.net/manual/en/mysqli.quickstart.statements.php
http://php.net/manual/en/mysqli.quickstart.statements.php
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$res = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $res->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

