使用php在varchar字段中使用斜杠插入查询

时间:2013-09-12 21:41:41

标签: php mysql sql string

我在php变量中有这个查询:

insert into `activadosmil` set cod='TAB08-150', stock='5', precio='111.23', categoria='Articulos destacados', subcategoria='PROMOS', descripcion='YARVIK JUNIOR 8" A9 1GB 8GB KIDO'Z ANDRO', ean='8717534019003', canon='111.23', fabricante='YARVIK'

它的描述='YARVIK JUNIOR 8“A9 1GB 8GB KIDO'Z ANDRO'

我尝试使用  htmlspecialchars($ descripcion)

但是不起作用。

如何在php中替换我需要用于mysql的代码?

提前致谢

3 个答案:

答案 0 :(得分:6)

使用反斜杠转义字符。

insert into `activadosmil` set cod='TAB08-150', stock='5', precio='111.23', categoria='Articulos destacados', subcategoria='PROMOS', descripcion='YARVIK JUNIOR 8\" A9 1GB 8GB KIDO\'Z ANDRO', ean='8717534019003', canon='111.23', fabricante='YARVIK'

答案 1 :(得分:2)

您应该使用正确的函数来转义字符串中的特殊SQL字符。取决于您使用的是哪种驱动程序,即mysql_real_escape_stringmysqli::real_escape_stringPDO::quote

不仅需要逃脱。使用正确的函数保证,您没有忘记一些特殊字符,并且还正确处理字符编码(假设您已使用mysqli::set_charset()或相应的mysql或PDO设置了正确的字符编码)。

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
$mysqli->set_charset("utf8");

// The original string
$description = 'YARVIK JUNIOR 8" A9 1GB 8GB KIDO\'Z ANDRO';

// Escape any special characters in the correct way for this database connection
$escaped_description = $mysqli->real_escape_string($description);

$mysqli->query("INSERT INTO activadosmil (description)" .
               " VALUES ('$escaped_description');");

答案 2 :(得分:1)

我建议调查PHP手册页中描述的mysqli类的准备功能:

http://www.php.net/manual/en/mysqli-stmt.prepare.php

以及bind_params功能:

http://www.php.net/manual/en/mysqli-stmt.bind-param.php

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create a prepared statement */
$stmt = mysqli_stmt_init($link);

$query='INSERT INTO activadosmil (cod, stock, precio, subcategoria, ".
"descripcion, ean, canon, fabricante) VALUES (?, ?, ?, ?, ?, ?, ?,?)';
if (mysqli_stmt_prepare($stmt, $query));{

    /* bind parameters for markers */
    // NB: the first parameter is a string of single char type indicators
    //      - One for each of the actual parameters s=string, d=double, I=integer, b=blob
    //      - In this case all 8 appear to be string - so 'ssssssss'
    mysqli_stmt_bind_param('ssssssss', $cod, $stock, $precio, $subcategoria, $descripcion, 
                           $ean, $canon, $fabricante);

    /* execute query */
    mysqli_stmt_execute($stmt);


    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?> 

使用bind_param可以防止引号出现任何问题。