php SELECT id FROM table_name WHERE column = $variable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16942102/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:56:30  来源:igfitidea点击:

SELECT id FROM table_name WHERE column = $variable

phpselectwhere

提问by Michael

I'm trying to retrieve the id number of a record to use as a variable elsewhere. I only want the id from a record that has a particular value in another column. here is my code:

我正在尝试检索记录的 ID 号以用作其他地方的变量。我只想要在另一列中具有特定值的记录中的 id。这是我的代码:

$result = mysql_query("SELECT id FROM order WHERE orderNumber = '$orderNumber'") or die (mysql_error());
$id = $result;

When I test I get: SQL syntax; check the manual that corresponds to your MySQL server versi0on for the right syntax to use near 'order WHERE orderNumber = '5b0ea3'

当我测试时,我得到: SQL 语法;检查与您的 MySQL 服务器版本相对应的手册,了解在 'order WHERE orderNumber = '5b0ea3' 附近使用的正确语法

Any ideas?

有任何想法吗?

回答by andrewsi

SELECT id FROM order WHERE orderNumber = '$orderNumber

ORDER is a reserver word in SQL; I'd recommend you change the name of the column to something else.

ORDER 是 SQL 中的保留字;我建议您将列的名称更改为其他名称。

If you really can't, then you can escape column and table names with backticks:

如果你真的不能,那么你可以用反引号转义列和表名:

SELECT `id` FROM `order` WHERE `orderNumber` = '$orderNumber'

And also see the comments about stopping using mysqli_functions - they're insecure, and being deprecated.

还可以查看关于停止使用mysqli_函数的评论——它们不安全,并且已被弃用。

回答by mpratt

Since ORDERis a reserved word, you must use backticks on your sql query. And after that use the mysql_fetch_associn order to get the id.

由于ORDER是保留字,因此您必须在 sql 查询中使用反引号。然后使用mysql_fetch_assoc来获取 id。

$result = mysql_query("SELECT `id` FROM `order` WHERE `orderNumber` = '$orderNumber'") or die (mysql_error());
$row = mysql_fetch_assoc($result);
$id = $row['id'];

On the other hand, you should be using PDOor Mysqli, the mysql_*functions are deprecated and considered a bad practice.

另一方面,您应该使用PDOor Mysqli,这些mysql_*功能已被弃用并被认为是一种不好的做法。

If you plan on keep using mysql_query, at least make sure to sanitize the $orderNumbervariable with mysql_real_escape_String.

如果你打算继续使用mysql_query,至少确保$orderNumbermysql_real_escape_String清理变量。

回答by ahmad haboul

mysqli_query($connection,"SELECT `id` FROM `order` WHERE `orderNumber` = '$orderNumber'");

as you see you must include $connection.

如您所见,您必须包含 $connection。

回答by webdevil

Built using custom database class with query function, but the SQL query works

使用具有查询功能的自定义数据库类构建,但 SQL 查询有效

$id = 1;
$database->query("SELECT * FROM tbl_post WHERE post_id = '$id'");