简体   繁体   English

php-mysql查询中变量周围的单引号

[英]php - single quotes around variables in mysql queries

Why do I see in several examples of mysql queries via php the syntax: 为什么我在通过php的mysql查询的几个示例中看到语法:

$q = "CREATE TABLE '$tablename' ('$t_id_name')";

or things similar to that? 或类似的东西? I'm asking about the single quotes around the variable names. 我问的是变量名周围的单引号。 Is this required in MySQL strings? 这是MySQL字符串中必需的吗? If I echo the string, it seems to expand the variables whether the quotes are there or not. 如果我回显字符串,则无论引号是否存在,似乎都在扩展变量。

And would this pose a problem if this were done for something that was intended to be an integer? 如果对原本打算为整数的对象执行此操作,会不会带来问题?

To answer your question, the quotes are necessary, but not to expand the variable. 要回答您的问题,引号是必需的,但不必扩展变量。 A typical SQL query would look like this: 典型的SQL查询如下所示:

$q = "SELECT * FROM `table` WHERE `first_name` = 'user3475234'";

Now, consider the following example: 现在,考虑以下示例:

<?php
$tablename = "users";
$user = "user3475234";

$q = "SELECT * FROM `$tablename` WHERE `first_name` = '$user'";

echo $q;

This will display: SELECT * FROM `users` WHERE `first_name` = 'user3475234' . 这将显示: SELECT * FROM `users` WHERE `first_name` = 'user3475234' Note that the quotes weren't necessary to output the string, but they were a necessary part of the query. 请注意,引号对于输出字符串不是必需的,但它们是查询的必要部分。

That being said, code like this opens your script to SQL injection. 话虽如此,这样的代码将您的脚本打开到SQL注入。 I won't explain too much about it, since there are plenty of resources discussing it, but consider the example where someone's username is user3475234' OR 1==1-- . 我不会对此做太多解释,因为有很多讨论它的资源,但是考虑一个示例,其中某人的用户名是user3475234' OR 1==1-- This username will effectively return all users in the table. 该用户名将有效地返回表中的所有用户。

You must use backticks (`) for field or table name especially if the field or table name are same with mysql command. 字段或表名必须使用反引号(`),特别是如果字段或表名与mysql命令相同。 And you need to use single-quote (') for value. 并且您需要使用单引号(')作为值。

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

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