php 单值 Mysqli
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11456707/
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 Value Mysqli
提问by Refiking
I am trying to write a function that will check for a single value in the db using mysqli without having to place it in an array. What else can I do besides what I am already doing here?
我正在尝试编写一个函数,该函数将使用 mysqli 检查数据库中的单个值,而不必将其放入数组中。除了我已经在这里做的事情之外,我还能做什么?
function getval($query){
$mysqli = new mysqli();
$mysqli->connect(HOST, USER, PASS, DB);
$result = $mysqli->query($query);
$value = $mysqli->fetch_array;
$mysqli->close();
return $value;
}
回答by Mike
How about
怎么样
$name = $mysqli->query("SELECT name FROM contacts WHERE id = 5")->fetch_object()->name;
回答by prl77
The mysql extension could do this using mysql_result, but mysqli has no equivalent function as of today, afaik. It always returns an array.
mysql 扩展可以使用 mysql_result 来做到这一点,但 mysqli 到目前为止还没有等效的功能,afaik。它总是返回一个数组。
If I didn't just create the record, I do it this way:
如果我不只是创建记录,我会这样做:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
Or if I did just create the record and the userID column is AI, I do:
或者,如果我只是创建了记录并且 userID 列是 AI,我会这样做:
$userID = mysqli_insert_id($link);
回答by jbrahy
Always best to create the connection once at the beginning and close at the end. Here's how I would implement your function.
始终最好在开始时创建连接并在结束时关闭。这是我将如何实现您的功能。
$mysqli = new mysqli();
$mysqli->connect(HOSTNAME, USERNAME, PASSWORD, DATABASE);
$value_1 = get_value($mysqli,"SELECT ID FROM Table1 LIMIT 1");
$value_2 = get_value($mysqli,"SELECT ID FROM Table2 LIMIT 1");
$mysqli->close();
function get_value($mysqli, $sql) {
$result = $mysqli->query($sql);
$value = $result->fetch_array(MYSQLI_NUM);
return is_array($value) ? $value[0] : "";
}
回答by rybo111
Here's what I ended up with:
这是我的结果:
function get_col($sql){
global $db;
if(strpos(strtoupper($sql), 'LIMIT') === false) {
$sql .= " LIMIT 1";
}
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query);
return $row[0];
}
This way, if you forget to include LIMIT 1in your query (we've all done it), the function will append it.
这样,如果您忘记LIMIT 1在查询中包含(我们都已完成),该函数将附加它。
Example usage:
用法示例:
$first_name = get_col("SELECT `first_name` FROM `people` WHERE `id`='123'");
回答by Your Common Sense
First and foremost,
首先,
Such a function should support prepared statements
这样的函数应该支持准备好的语句
Otherwise it will be horribly insecure.
否则会非常不安全。
Also, such a function should never connect on its own, but accept an existing connection variableas a parameter.
此外,这样的函数不应该自己连接,而是接受现有的连接变量作为参数。
Given all the above, only acceptable way to call such a function would be be like
鉴于以上所有,调用这样一个函数的唯一可接受的方法是
$name = getVal($mysqli, $query, [$param1, $param2]);
allowing $queryto contain only placeholders, while the actual data has to be added separately. Any other variant, including all other answers posted here, should never be used.
允许$query只包含占位符,而实际数据必须单独添加。不应使用任何其他变体,包括此处发布的所有其他答案。
function getVal($mysqli, $sql, $values = array())
{
$stm = $mysqli->prepare($sql);
if ($values)
{
$types = str_repeat("s", count($values));
$stm->bind_param($types, ...$values);
}
$stm->execute();
$stm->bind_result($ret);
$stm->fetch();
return $ret;
}
Which is used like this
像这样使用
$name = getVal("SELECT name FROM users WHERE id = ?", [$id]);
and it's the only proper and safe way to call such a function, while all other variants lack security and, often, readability.
这是调用这样一个函数的唯一正确和安全的方法,而所有其他变体都缺乏安全性,而且通常缺乏可读性。
回答by John
Even this is an old topic, I don't see here pretty simple way I used to use for such assignment:
即使这是一个古老的话题,我在这里也没有看到我过去用于此类分配的非常简单的方法:
list($value) = $mysqli->fetch_array;
you can assign directly more variables, not just one and so you can avoid using arrays completely. See the php function list()for details.
您可以直接分配更多变量,而不仅仅是一个,因此您可以完全避免使用数组。有关详细信息,请参阅 php 函数list()。
回答by Tom Lucas
This doesn't completely avoid the array but dispenses with it in one line.
这并没有完全避免阵列,而是在一行中省去了它。
function getval($query) {
$mysqli = new mysqli();
$mysqli->connect(HOST, USER, PASS, DB);
return $mysqli->query($query)->fetch_row()[0];
}
回答by Coopz
Procedural style Expanded:
程序风格扩展:
$sql = "SELECT xyz from table WHERE conditional";
$res = mysqli_query($conn, $sql);
$value = array_values(mysqli_fetch_array($res,MYSQLI_NUM))[0];
Expanded for clarity. trivial to compose as single line, and swear at it later.
为清楚起见进行了扩展。微不足道的组成单行,然后发誓。
$value = array_values(mysqli_fetch_array(mysqli_query($conn, "SELECT xyz from table WHERE conditional"),MYSQLI_NUM))[0];
回答by Mick
Try something like this:
尝试这样的事情:
$last = $mysqli->query("SELECT max(id) as last FROM table")->fetch_object()->last;
Cheers
干杯

