php 用引号包围字符串

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

Surround string with quotes

phpstring

提问by serhio

Is there a function in PHP that adds quotes to a string?

PHP 中是否有将引号添加到字符串的函数?

like "'".str."'"

喜欢 "'".str."'"

This is for a sql query with varchars. I searched a little, without result...

这是用于使用 varchars 的 sql 查询。我搜索了一下,没有结果......

I do the following:

我执行以下操作:

$id = "NULL";
$company_name = $_POST['company_name'];         
$country = $_POST['country'];
$chat_language = $_POST['chat_language'];
$contact_firstname = $_POST['contact_firstname'];
$contact_lastname = $_POST['contact_lastname'];
$email = $_POST['email'];
$tel_fix = $_POST['tel_fix'];
$tel_mob = $_POST['tel_mob'];       
$address = $_POST['address'];       
$rating = $_POST['rating'];

$company_name = "'".mysql_real_escape_string(stripslashes($company_name))."'";
$country = "'".mysql_real_escape_string(stripslashes($country))."'";
$chat_language = "'".mysql_real_escape_string(stripslashes($chat_language))."'";
$contact_firstname = "'".mysql_real_escape_string(stripslashes($contact_firstname))."'";
$contact_lastname = "'".mysql_real_escape_string(stripslashes($contact_lastname))."'";
$email = "'".mysql_real_escape_string(stripslashes($email))."'";
$tel_fix = "'".mysql_real_escape_string(stripslashes($tel_fix))."'";
$tel_mob = "'".mysql_real_escape_string(stripslashes($tel_mob))."'";
$address = "'".mysql_real_escape_string(stripslashes($address))."'";
$rating = mysql_real_escape_string(stripslashes($rating));

$array = array($id, $company_name, $country, $chat_language, $contact_firstname, 
$contact_lastname, $email, $tel_fix, $tel_mob, $address, $rating);
$values = implode(", ", $array);

$query = "insert into COMPANIES values(".$values.");";

采纳答案by cletus

Firstly, I see you're using stripslashes(). That implies you have magic quoteson. I would suggest turning that off.

首先,我看到您正在使用stripslashes(). 这意味着你有魔术引号。我建议关闭它。

What you might want to do is put some of this in a function:

您可能想要做的是将其中的一些放在一个函数中:

function post($name, $string = true) {
  $ret = mysql_real_escape_string(stripslashes($_POST[$name]));
  return $string ? "'" . $ret . "'" : $ret;
}

and then:

进而:

$company_name = post('company_name');

All this does however is reduce the amount of boilerplate you have slightly.

然而,这一切只是稍微减少了样板文件的数量。

Some have suggested using PDO or mysqli for this just so you can use prepared statements. While they can be useful it's certainly notnecessary. You're escaping the fields so claims of vulnerability to SQL injection (at least in the case of this code) are misguided.

有些人建议为此使用 PDO 或 mysqli,以便您可以使用准备好的语句。虽然它们可能很有用,但肯定没有必要。您正在逃避这些字段,因此声称存在 SQL 注入漏洞(至少在此代码的情况下)是错误的。

Lastly, I wouldn't construct a query this way. For one thing it's relying on columns in the companies table being of a particular type and order. It's far better to be explicit about this. I usually do this:

最后,我不会以这种方式构造查询。一方面,它依赖于公司表中具有特定类型和顺序的列。明确说明这一点要好得多。我通常这样做:

$name = mysql_real_escape_string($_POST['name']);
// etc
$sql = <<<END
INSERT INTO companies
(name, country, chat_language)
VALUES
($name, $country, $language)
END;

That will sufficient for the task. You can of course investigate using either mysqli or PDO but it's not necessary.

这足以完成任务。您当然可以使用 mysqli 或 PDO 进行调查,但这不是必需的。

回答by outis

Rather than inserting the value directly into the query, use prepared statementsand parameters, which aren't vulnerable to SQL injection.

不要将值直接插入到查询中,而是使用准备好的语句和参数,它们不易受到SQL 注入的影响

$query = $db->prepare('SELECT name,location FROM events WHERE date >= ?');
$query->execute(array($startDate));

$insertContact = $db->prepare('INSERT INTO companies (company_name, country, ...) VALUES (?, ?, ...)');
$insertContact->execute(array('SMERSH', 'USSR', ...));

Creating a PDO object (which also connects to the DB and is thus a counterpart to mysql_connect) is simple:

创建一个 PDO 对象(它也连接到数据库,因此是 的对应物mysql_connect)很简单:

$db = new PDO('mysql:host=localhost;dbname=db', 'user', 'passwd');

You shouldn't scatter this in every script where you want a DB connection. For one thing, it's more of a security risk. For another, your code will be more susceptible to typos. The solution addresses both issues: create a function or method that sets up the DB connection. For example:

您不应该将其分散在需要数据库连接的每个脚本中。一方面,这更多是一种安全风险。另一方面,您的代码将更容易出现拼写错误。该解决方案解决了这两个问题:创建一个函数或方法来设置数据库连接。例如:

function localDBconnect($dbName='...') {
    static $db = array();
    if (is_null($db[$dbName])) {
        $db[$dbName] = new PDO("mysql:host=localhost;dbname=$dbName", 'user', 'passwd');
        $db[$dbName]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    return $db[$dbName];
}

If you're working with an array of more than two or three elements, you should use loops or array functions rather than a long sequence of similar statements, as is done in the sample code. For example, most of your sample can be replaced with:

如果您正在处理包含两个或三个以上元素的数组,则应使用循环或数组函数,而不是像示例代码中所做的那样,使用一长串类似的语句。例如,您的大部分样本都可以替换为:

$array = array();
foreach ($_POST as $key => $val) {
    $array[$key] = "'" . mysql_real_escape_string(stripslashes($val)) . "'";
}

Here's a more comprehensive example of creating an insert query. It's far from production ready, but it illustrates the basics.

这是创建插入查询的更全面的示例。它远未准备好生产,但它说明了基础知识。

$db = localDBconnect();

// map input fields to table fields
$fields = array(
  'company' => 'company_name',
  'country' => 'country',
  'lang' => 'chat_language',
  'fname' => 'contact_firstname',
  'lname' => 'contact_lastname',
  'email' => 'email',
  'land' => 'tel_fix',
  'mobile' => 'tel_mob',
  'addr' => 'address',
  'rating' => 'rating',
);
if ($missing = array_diff_key($fields, $_POST)) {
    // Form is missing some fields, or request doesn't come from the form.
    ...
} else {
    $registration = array_intersect_key($_POST, $fields);

    $stmt = 'INSERT INTO `dbname`.`Companies` (`' 
        . implode('`, `', $fields) . '`) VALUES (' 
        . implode(', ', array_fill(0, count($registration), '?')) . ')';
    try {
        $query = $db->prepare($stmt);
        $query->execute(array_values($registration));
    } catch (PDOException $exc) {
        // log an 
        error_log($exc);
        echo "An error occurred. It's been logged, and we'll look into it.";
    }
}

To make it production ready, the code should be refactored into functions or classes that hide everything database related from the rest of the code; this is called a "data access layer". The use of $fieldsshows one way of writing code that will work for arbitrary table structures. Look up "Model-View-Controller" architectures for more information. Also, validation should be performed.

为了使其做好生产准备,应该将代码重构为函数或类,以隐藏与其余代码相关的所有数据库;这称为“数据访问层”。的使用$fields显示了一种编写适用于任意表结构的代码的方法。查找“模型-视图-控制器”架构以获取更多信息。此外,还应进行验证。

回答by Robbie Averill

Thought I'd contribute an option that answers the question of "Is there a function in PHP that adds quotes to a string?" - yes, you canuse str_pad(), although it's probably easier to do it manually.

我想我会贡献一个选项来回答“PHP 中是否有一个函数可以为字符串添加引号?” -是的,您可以使用str_pad(),尽管手动执行可能更容易。

Benefits of doing it with this function are that you could also pass a character to wrap around the variable natively within PHP:

使用此函数执行此操作的好处是您还可以传递一个字符以在 PHP 中本机环绕变量:

function str_wrap($string = '', $char = '"')
{
    return str_pad($string, strlen($string) + 2, $char, STR_PAD_BOTH);
}

echo str_wrap('hello world');      // "hello world"
echo str_wrap('hello world', '@'); // @hello world@

回答by Phoexo

Create your own.

创建自己的。

function addQuotes($str){
    return "'$str'";
}

回答by Ignacio Vazquez-Abrams

Don't do this. Instead use parametrized queries, such as those with PDO.

不要这样做。而是使用参数化查询,例如带有PDO 的查询。

回答by Brian Powell

This isn't a function - but it's the first post that comes up on google when you type "php wrap string in quotes". If someone just wants to wrap an existing string in quotes, without running it through a function first, here is the correct syntax:

这不是一个函数 - 但它是当你输入“php wrap string in引号”时出现在谷歌上的第一篇文章。如果有人只想将现有字符串用引号括起来,而不先通过函数运行它,那么正确的语法如下:

echo $var   // hello

$var = '"'.$var.'"';

echo $var   // "hello"