-1

mysql表中有一些文本作为长文本存储。它包含 ' 字符。

试图逃避这些,以便我可以获取结果。任何有 ' 的东西都会出错。

review_text with ' 无法带回任何东西。答案应该是 mysql_real_escape_string 但这不起作用。

while ($row = mysql_fetch_array($result)) {
    $review = array();
    $review["name"] = $row["reviewer_name"];
    $review["title"] = $row["review_title"];
    $review["content"] = $row["review_text"];
    $review["rating"] = $row["review_rating"];
    $review["time"] = $row["date_time"];
    // push single product into final response array
    array_push($response["reviews"], $review);
}
4

1 回答 1

0

有几种方法可以处理这个问题,但是首先你需要停止使用不推荐使用的mysql_扩展。“已弃用”意味着它们不再包含在 php 中,并且很快就会停止工作,正如官方 php 网站上所说:http: //php.net/manual/en/function.mysql-fetch-array.php

警告

此扩展自 PHP 5.5.0 起已弃用,并将在未来删除。相反,应该使用 MySQLi 或 PDO_MySQL 扩展。另请参阅 MySQL:选择 API 指南和相关的常见问题解答以获取更多信息。此功能的替代方案包括:

mysqli_fetch_array()
PDOStatement::fetch()

您可以使用 mysqli_real_escape_string 来“转义”您的变量,但是使用准备好的语句要好得多。要么mysqli_PDO将工作。

在这种情况下,您使用选择获取变量,您可以执行以下操作(不清楚您在哪里获取变量,但让我们以此作为假设),您可以像这样连接到您的数据库:

$conn = new mysqli($host, $username, $password, $dbname);

if  ($conn->connect_error) {
    die("Connection failed: " . $dbc->connect_error);

$stmt = $conn->prepare(select name, title, content, rating, time from tablename where variable = ?);
// this is assuming that this is a string, so "s" is used, otherwise use "i" for string
$stmt->bind_param("s",$variable);
$stmt->execute();
//then you can bind your results into tidy variables all of which have been "escaped"
$stmt->bind_result($name, $title, $content, $rating, $time);
$stmt->close();

要获取您的变量,而不是使用mysql_fetch_array()您,只需使用$stmt->fetch();

或像这样:

while (stmt->fetch()) {
    [stuff here]
}

瞧,你的变量很干净。 注意:虽然这些将处理引号、撇号等,但它们对于防止 SQL 注入也将更加安全。您也可以使用 PDO。

于 2015-06-25T01:39:52.723 回答