dongxi5423 2012-04-30 03:31
浏览 30
已采纳

涉及连字符的PHP MySQL语法错误

$names = array();
$names['full-name'] = 'John Doe';

$query = "INSERT INTO users (full_name) VALUES ('$names[full-name]')";
$result = mysql_query($query) or die(mysql_error());

I have been getting syntax errors whenever I attempt to create a mysql query using an array key that contains a hyphen:

Parse error: syntax error, unexpected '-', expecting ']'

How am I able to fix this? Thank you.

  • 写回答

5条回答 默认 最新

  • duange2971 2012-04-30 03:53
    关注

    Since it hasn't been mentioned yet, here's an another alternative syntax:

    $query = "INSERT INTO users (full_name) VALUES ('{$names['full-name']}')";
    

    Adding the {} braces around the variable/array index allows you to quote it as you would if it were outside of the string. The {} notation also allows you to embed a multi-dimensional array inside a string, e.g.

    echo "$x[1][2]";
    

    would normally be see as array $x[1] followed by literal [2] text by PHP, since its array parsing is not 'greedy'. But putting braces aroudn the whole array reference forces PHP parse the entire thing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信