doushi6932 2016-09-22 08:33
浏览 25
已采纳

PHP:包含一个包含$ variables的SQL查询

I really dislike writing SQL queries within my PHP.

Given the following example piece of PHP:

script.php

$name = 'Bill'
$query = "SELECT * FROM a_table WHERE name='$name'";

I'd like to instead write the sql query in it's own file and include (or otherwise) get the contents into my script:

query.sql

SELECT * FROM a_table WHERE name='$name'

script.php

// This doesn't work obviously
$query = '"'.include('query.sql').'"';

Note that I'd like to be able to reference PHP variables within the SQL query (e.g: $name is setup declared in script.php but used as part of the query).

  • 写回答

2条回答 默认 最新

  • doutou7549 2016-09-22 08:37
    关注

    nice and simple solution:

     $sql = file_get_contents("query.sql");
    

    And to reference variables, I suggest using PDO where you reference like this

    $query = $db->query( "SELECT x FROM x WHERE x = :example")
    $query->execute(array("example"=>$value));
    

    ...But you can do something similar to this in mysqli, etc.

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

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题