简体   繁体   English

使用 PHP/SQL 将带有逗号 (,) 的值插入到数据库中

[英]Inserting a value with a comma ( , ) into a database using PHP/SQL

I am trying to insert values with a comma into a database but the comma is splitting the query so that the part of the string before the comma goes into the correct column, while the bit after the comma goes into the next and every item in the query after that is displaced into the next column.我试图用逗号将值插入到数据库中,但逗号正在拆分查询,以便逗号之前的字符串部分进入正确的列,而逗号之后的位进入下一个和每个项目中的之后的查询被转移到下一列。

My connection file to my db is as follows:我到我的数据库的连接文件如下:

define('DB_HOST', 'localhost');
define('DB_NAME', '********');
define('DB_USER', '********');
define('DB_PASS', '********');
define('DB_CHAR', 'utf8');

class DB
{
    protected static $instance = null;
    protected function __construct() {}
    protected function __clone() {}

    public static function instance(){
        if (self::$instance === null){
            $opt  = array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => FALSE,
            );
            $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHAR;
            self::$instance = new PDO($dsn, DB_USER, DB_PASS, $opt);
        }
        return self::$instance;
    }

    public static function __callStatic($method, $args){
        return call_user_func_array(array(self::instance(), $method), $args);
    }

    public static function run($sql, $args = []){
        if (!$args){
            return self::instance()->query($sql);
        }
        $stmt = self::instance()->prepare($sql);
        $stmt->execute($args);
        return $stmt;
    }
}

And then I do my query like this:然后我做我这样的查询:

$item1 = 'item1';
$item2 = 'item_with_a_,_symbol';
$item3 = 'item3';

$params = [$item1,$item2,$item3];
$sql = "INSERT INTO table (col1,col2,col3) VALUES(?,?,?)";
$stmt = DB::run($sql,$params);

In this case my database would be like so:在这种情况下,我的数据库将是这样的:

col1            col2            col3
item1           item_with_a_    _symbol

What is the best way to get around this?解决这个问题的最佳方法是什么?

Try escaping the input before running the insert.在运行插入之前尝试转义输入。mysqli_real_escape_string() should do the trickmysqli_real_escape_string()应该可以解决问题

Check this entry in the PHP manual for reference检查PHP 手册中的此条目以供参考

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

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