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.

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

报告相同问题?

悬赏问题

  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置