带引号的环绕字符串

ser*_*hio 9 php string

PHP中是否有一个函数可以为字符串添加引号?

喜欢 "'".str."'"

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

我做以下事情:

$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.");";
Run Code Online (Sandbox Code Playgroud)

out*_*tis 10

不要将值直接插入查询中,而是使用预处理的语句和参数,这些语句和参数不易受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', ...));
Run Code Online (Sandbox Code Playgroud)

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

$db = new PDO('mysql:host=localhost;dbname=db', 'user', 'passwd');
Run Code Online (Sandbox Code Playgroud)

您不应将此分散在您想要数据库连接的每个脚本中.首先,它更多的是安全风险.另一方面,您的代码更容易受到错别字的影响.该解决方案解决了这两个问题:创建一个设置数据库连接的函数或方法.例如:

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];
}
Run Code Online (Sandbox Code Playgroud)

如果您正在处理超过两个或三个元素的数组,则应使用循环或数组函数,而不是类似语句的长序列,如示例代码中所示.例如,您的大部分样本都可以替换为:

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

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

$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.";
    }
}
Run Code Online (Sandbox Code Playgroud)

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


cle*_*tus 9

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

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

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

然后:

$company_name = post('company_name');
Run Code Online (Sandbox Code Playgroud)

然而,所有这些都会减少您略有的样板量.

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

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

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

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


Rob*_*ill 8

以为我会提供一个选项来回答"PHP中是否有一个函数在字符串中添加引号?"的问题.- 是的,你可以使用str_pad(),虽然它可能更容易手动完成.

使用此函数执行此操作的好处是您还可以传递一个字符以在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@
Run Code Online (Sandbox Code Playgroud)


Pho*_*exo 6

创建你自己的。

function addQuotes($str){
    return "'$str'";
}
Run Code Online (Sandbox Code Playgroud)

  • 或者为了使该功能更好,也可以在其中添加 mysql_real_escape_string 。 (2认同)