简体   繁体   English

如何使用字母数字值检索数据?

[英]How to retrieve data using alphanumeric value?

Is it possible to retrieve data using a value that is alphanumeric? 是否可以使用字母数字值检索数据?

Because whenever my "product_id" value is alphanumeric it doesn't work but it only works when the value is numerical. 因为每当我的"product_id"值是字母数字时,它都不起作用,但仅当该值是数字时才起作用。

Eg it only works when the "product_id" = 1 , but when "product_id" = 1a it does not work. 例如,它仅在"product_id" = 1 ,而在"product_id" = 1a时无效。

// get a product from products table
$result = mysql_query("SELECT * FROM tbl_product WHERE product_id = $product_id");

if (!empty($result)) {
    // check for empty result
    if (mysql_num_rows($result) > 0) {

        $result = mysql_fetch_array($result);

        $product = array();
        $product["product_id"] = $result["product_id"];
        $product["product_des"] = $result["product_des"];
        $product["price"] = $result["price"];
        $product["qty"] = $result["qty"];
        $product["product_cat"] = $result["product_cat"];
        $product["product_sect"] = $result["product_sect"];
        // success
        $response["success"] = 1;

        // user node
        $response["product"] = array();

        array_push($response["product"], $product);

You need to use quotes; 您需要使用引号; or preferably prepared statements. 或最好是准备好的陈述。 SQL strings need to be quoted. SQL字符串需要加引号。

Eg 例如

Select * from users where name = chris

is invalid SQL. 是无效的SQL。 But

Select * from users where name = 'chris'

would be valid. 将是有效的。

So 所以

$result = mysql_query("SELECT * FROM tbl_product WHERE product_id = $product_id");

Should be 应该

$result = mysql_query("SELECT * FROM tbl_product WHERE product_id = '$product_id'");

since you are using mysql_ functions be sure that $product_id is being passed through mysql_real_escape_string . 由于您正在使用mysql_函数,因此请确保$product_id已通过mysql_real_escape_string传递。 Note the warnings on all the mysql_ function pages as well and consider updating your driver. 注意所有mysql_函数页面上的警告,并考虑更新驱动程序。

With mysqli and pdo you can use prepared statements, which if used correctly handle the quoting for you. 通过mysqlipdo您可以使用准备好的语句,如果使用正确,这些语句将为您正确处理报价。

A prepared example would be 一个准备好的例子是

$result = $pdo->prepare("SELECT * FROM tbl_product WHERE product_id = ?");
$result->execute(array($product_id));

For additional reading: 有关其他阅读:

https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_Queries.29 https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_Queries.29

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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