dongzhuo3376 2016-12-05 00:29
浏览 43
已采纳

在mysqli_query中格式化

I am using PHP to execute a query to a database. I have been successful in executing many queries with the program but one recent one has given me trouble. The original SQL query is as follows:

SELECT Champion, RunnerUp
FROM playoffs
WHERE Champion = "Detroit Red Wings"
AND (RunnerUp = "Montreal Canadiens" OR RunnerUp = "New York Rangers");

This runs successfully and produces the correct output when used in HeidiSQL directly on the database. I tried implementing it in the program as follows, swapping out the actual team names for PHP variables:

$result = mysqli_query($link, "SELECT Champion, RunnerUp
                FROM playoffs
                WHERE Champion = '$champion'
                AND (RunnerUp = '$RunnerUp' OR RunnerUp = '$RunnerUp2')") ;

In this version, it seems that the embedded set of parenthesis is not being identified as such, instead appearing to be part of the quotation. This version produced no output.

I modified it as follows:

$result = mysqli_query($link, "SELECT Champion, RunnerUp
                FROM playoffs
                WHERE Champion = '$champion'
                AND RunnerUp = '$RunnerUp' OR RunnerUp = '$RunnerUp2'") ;

Removing the second set of parenthesis, it executes but does not produce the desired result because the logic reads differently, giving me tuples for whenever $champion and $RunnerUp match or whenever $RunnerUp2 is the runner-up. Is there anyway to execute this statement as I originally intended using PHP?

UPDATE: After putting the query into a variable as follows:

 $query = "SELECT Champion, RunnerUp
                FROM playoffs
                WHERE Champion = '$champion'
                AND (RunnerUp = '$RunnerUp' OR RunnerUp = '$RunnerUp2')";

and echoing it, I got the output

SELECT Champion, RunnerUp FROM playoffs WHERE Champion = '' AND (RunnerUp = 'Montreal Canadiens' OR RunnerUp = 'Toronto St. Patricks')

So it looks like for some reason, my champion variable never receives anything. This is because when calling it originally, it was called as 'Champion' instead of 'champion.'

  • 写回答

1条回答 默认 最新

  • dsogx84602 2016-12-05 00:52
    关注

    After finding out where I went wrong previously, it appears that this code:

    $query = "SELECT Champion, RunnerUp
                FROM playoffs
                WHERE Champion = '$champion'
                AND (RunnerUp = '$RunnerUp' OR RunnerUp = '$RunnerUp2')";
    

    will in fact work. Though, as mentioned in the comments above, it would be cleaner to add the query to a variable and call it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效