数据库结果中的Pesky Apostrophes

时间:2013-10-09 14:33:18

标签: php sql database

好的......长话短说......这是我的代码......


<?php 

$con = mysql_connect($db_server_name,$db_username,$db_password);
if (!$con)
  {
  echo "0";
  }
mysql_select_db("" . $db_database_name . "", $con);
$result = mysql_query("SELECT * FROM sched_posts
WHERE user_id='$user_id'");

while($row = mysql_fetch_array($result))
  {
  $post_id = $row['ID'];
  $post_year = $row['post_year'];
  $post_month = $row['post_month'];
  $post_day = $row['post_day'];
  $post_hour = $row['post_hour'];
  $post_minute = $row['post_minute'];
  $post_privacy = $row['post_privacy'];
  $post_message = $row['post_message'];
echo "              {";
echo "                  id: " . $post_id . ",";
echo "                  title: ' " . $post_message . "',";
echo "                  start: new Date(" . $post_year . ", " . $post_month . "-1, " . $post_day . ", " . $post_hour . ", " . $post_minute . "),";
echo "                  allDay: false";
echo "              },";
  }
?>

当返回结果时,post_message有时会返回撇号。如何才能将这些结果显示为“而不仅仅是”(换句话说......前面有反斜杠)?

PS ..我知道这些代码看起来不必要,但请尽量忽略....这只是为我正在为facebook SDK结果做的一些测试设置这种方式(例如,内部的标识符) WHILE声明)。

问题是,返回的撇号会导致整个事情变得循环...你知道我的意思。

3 个答案:

答案 0 :(得分:1)

如果您将所有这些“日期部分”列转换为时间戳,则只需使用json_encode()

$ts = mktime($post_hour, $post_minute, 0, $post_month, $post_day, $post_year);

echo json_encode(array(
    'id' => $row['ID'],
    'title' => $row['post_message'],
    'start' => date('r', $ts), // <-- that's a string now
    'allDay' => false,
));

使用rfc822格式化日期时,JavaScript没有问题。

答案 1 :(得分:0)

要添加反斜杠,函数addslashes()将适用于此:

http://php.net/manual/en/function.addslashes.php

为了可靠地编码JSON 100%(特别是对于你无法预测/期望某些值/输入的这样的字段),最好使用json_encode():

while($row = mysql_fetch_array($result))
{
  $post_id = $row['ID'];
  $post_year = $row['post_year'];
  $post_month = $row['post_month'];
  $post_day = $row['post_day'];
  $post_hour = $row['post_hour'];
  $post_minute = $row['post_minute'];
  $post_privacy = $row['post_privacy'];
  $post_message = $row['post_message'];
  $dateString = ''; // computed date string...
  echo json_encode(array("id"=>$post_id,"title"=>$post_message,"start"=>
  $dateString,"allDay"=>false));
}

答案 2 :(得分:0)

json_encode()函数用于生成JSON数据,但由于JSON是JavaScript的子集,因此它是生成动态字符串的最佳选择。这是一个使用示例:

<?php

$post_id = 314;
$post_message = <<<EOM
Jim "Big Boy" O'brian wrote:

<strong>Hi</strong>

EOM;
$post_year = 2013;
$post_month = 10;
$post_day = 9;
$post_hour = 17;
$post_minute = 4;

echo "{";
echo "    id: " . $post_id . ",";
echo "    title: " . json_encode($post_message) . ",";
echo "    start: new Date(" . $post_year . ", " . $post_month . "-1, " . $post_day . ", " . $post_hour . ", " . $post_minute . "),";
echo "    allDay: false";
echo "},";

......产生:

title: "Jim \"Big Boy\" O'brian wrote:\r\n\r\n<strong>Hi<\/strong>\r\n"

请注意,您必须省略周围的引号;该功能为您添加它们。