如何将php变量放入sql查询中

时间:2016-04-24 19:17:22

标签: php html sql foreach navbar

所以这是我的代码:

lst = [90, 100, 95, 95]
lst.remove(min(lst))
print(sum(lst) / len(lst))

一切正常,直到<nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">WebSiteName</a> </div> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <?php $dbconn= new PDO('sqlite:negozio.db'); $sqlcate = "SELECT * FROM categoria"; foreach($dbconn->query($sqlcate) as $row) { ?> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"><?php echo $row['des_categoria']; ?> <span class="caret"></span></a> <ul class="dropdown-menu"> <?php $sqltipocate = "SELECT tipo.des_tipo FROM tipo, categoria, tipo_cate WHERE tipo_cate.id_cate = categoria.id_categoria AND tipo_cate.id_tipo = tipo.id_tipo AND tipo_cate.id_categoria = " . $row['id_categoria'] . " "" "; foreach($dbconn->query($sqltipocate) as $row1) { ?> <li><a href="#"><?php echo $row1['des_tipo']; ?></a></li> <?php } ?> </ul> </li> <?php } ?> </ul> </div> </nav> blabla ......

此错误始终显示:

  

语法错误,意外T_CONSTANT_ENCAPSED_STRING

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

以前的答案中认为是连接问题。我可以添加一些东西可以让你的生活更轻松。它是 sprintf

您的SQL查询字符串将是format的{​​{1}}参数,如下所示:

sprintf

答案 1 :(得分:0)

使用花括号。

示例:

$id = 1;
$sql = "SELECT * FROM something WHERE id = {$id}";

echo $sql;
//SELECT * FROM something WHERE id = 1

代码链接:http://codepad.org/V9QasGHH

答案 2 :(得分:0)

将$ row [&#39; id_categoria&#39;]存储在变量中,如

$ id = $ row [&#39; id_categoria&#39;];

然后将$ id放入查询中,如:

$ sqltipocate =&#34; SELECT tipo.des_tipo FROM tipo,categoria,tipo_cate WHERE tipo_cate.id_cate = categoria.id_categoria AND tipo_cate.id_tipo = tipo.id_tipo AND tipo_cate.id_categoria =&#39;&#34;。 $ ID&#34;&#39;&#34 ;;

请参阅此tipo_cate.id_categoria =&#39; &#34; $ id&#34; &#39;